1 //===--- CodeGenOptions.h ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the CodeGenOptions interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_BASIC_CODEGENOPTIONS_H
14 #define LLVM_CLANG_BASIC_CODEGENOPTIONS_H
15 
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Basic/XRayInstr.h"
18 #include "llvm/ADT/FloatingPointMode.h"
19 #include "llvm/Frontend/Debug/Options.h"
20 #include "llvm/Frontend/Driver/CodeGenOptions.h"
21 #include "llvm/Support/CodeGen.h"
22 #include "llvm/Support/Regex.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
25 #include <map>
26 #include <memory>
27 #include <string>
28 #include <vector>
29 
30 namespace llvm {
31 class PassBuilder;
32 }
33 namespace clang {
34 
35 /// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
36 /// that this large collection of bitfields is a trivial class type.
37 class CodeGenOptionsBase {
38   friend class CompilerInvocation;
39   friend class CompilerInvocationBase;
40 
41 public:
42 #define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
43 #define ENUM_CODEGENOPT(Name, Type, Bits, Default)
44 #include "clang/Basic/CodeGenOptions.def"
45 
46 protected:
47 #define CODEGENOPT(Name, Bits, Default)
48 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) unsigned Name : Bits;
49 #include "clang/Basic/CodeGenOptions.def"
50 };
51 
52 /// CodeGenOptions - Track various options which control how the code
53 /// is optimized and passed to the backend.
54 class CodeGenOptions : public CodeGenOptionsBase {
55 public:
56   enum InliningMethod {
57     NormalInlining,     // Use the standard function inlining pass.
58     OnlyHintInlining,   // Inline only (implicitly) hinted functions.
59     OnlyAlwaysInlining  // Only run the always inlining pass.
60   };
61 
62   enum ObjCDispatchMethodKind {
63     Legacy = 0,
64     NonLegacy = 1,
65     Mixed = 2
66   };
67 
68   enum TLSModel {
69     GeneralDynamicTLSModel,
70     LocalDynamicTLSModel,
71     InitialExecTLSModel,
72     LocalExecTLSModel
73   };
74 
75   enum StructReturnConventionKind {
76     SRCK_Default,  // No special option was passed.
77     SRCK_OnStack,  // Small structs on the stack (-fpcc-struct-return).
78     SRCK_InRegs    // Small structs in registers (-freg-struct-return).
79   };
80 
81   enum ProfileInstrKind {
82     ProfileNone,       // Profile instrumentation is turned off.
83     ProfileClangInstr, // Clang instrumentation to generate execution counts
84                        // to use with PGO.
85     ProfileIRInstr,    // IR level PGO instrumentation in LLVM.
86     ProfileCSIRInstr, // IR level PGO context sensitive instrumentation in LLVM.
87   };
88 
89   enum EmbedBitcodeKind {
90     Embed_Off,      // No embedded bitcode.
91     Embed_All,      // Embed both bitcode and commandline in the output.
92     Embed_Bitcode,  // Embed just the bitcode in the output.
93     Embed_Marker    // Embed a marker as a placeholder for bitcode.
94   };
95 
96   enum InlineAsmDialectKind {
97     IAD_ATT,
98     IAD_Intel,
99   };
100 
101   enum DebugSrcHashKind {
102     DSH_MD5,
103     DSH_SHA1,
104     DSH_SHA256,
105   };
106 
107   // This field stores one of the allowed values for the option
108   // -fbasic-block-sections=.  The allowed values with this option are:
109   // {"labels", "all", "list=<file>", "none"}.
110   //
111   // "labels":      Only generate basic block symbols (labels) for all basic
112   //                blocks, do not generate unique sections for basic blocks.
113   //                Use the machine basic block id in the symbol name to
114   //                associate profile info from virtual address to machine
115   //                basic block.
116   // "all" :        Generate basic block sections for all basic blocks.
117   // "list=<file>": Generate basic block sections for a subset of basic blocks.
118   //                The functions and the machine basic block ids are specified
119   //                in the file.
120   // "none":        Disable sections/labels for basic blocks.
121   std::string BBSections;
122 
123   // If set, override the default value of MCAsmInfo::BinutilsVersion. If
124   // DisableIntegratedAS is specified, the assembly output will consider GNU as
125   // support. "none" means that all ELF features can be used, regardless of
126   // binutils support.
127   std::string BinutilsVersion;
128 
129   enum class FramePointerKind {
130     None,        // Omit all frame pointers.
131     NonLeaf,     // Keep non-leaf frame pointers.
132     All,         // Keep all frame pointers.
133   };
134 
getFramePointerKindName(FramePointerKind Kind)135   static StringRef getFramePointerKindName(FramePointerKind Kind) {
136     switch (Kind) {
137     case FramePointerKind::None:
138       return "none";
139     case FramePointerKind::NonLeaf:
140       return "non-leaf";
141     case FramePointerKind::All:
142       return "all";
143     }
144 
145     llvm_unreachable("invalid FramePointerKind");
146   }
147 
148   enum class SwiftAsyncFramePointerKind {
149     Auto, // Choose Swift async extended frame info based on deployment target.
150     Always, // Unconditionally emit Swift async extended frame info.
151     Never,  // Don't emit Swift async extended frame info.
152     Default = Always,
153   };
154 
155   enum FiniteLoopsKind {
156     Language, // Not specified, use language standard.
157     Always,   // All loops are assumed to be finite.
158     Never,    // No loop is assumed to be finite.
159   };
160 
161   enum AssignmentTrackingOpts {
162     Disabled,
163     Enabled,
164     Forced,
165   };
166 
167   /// The code model to use (-mcmodel).
168   std::string CodeModel;
169 
170   /// The code model-specific large data threshold to use
171   /// (-mlarge-data-threshold).
172   uint64_t LargeDataThreshold;
173 
174   /// The filename with path we use for coverage data files. The runtime
175   /// allows further manipulation with the GCOV_PREFIX and GCOV_PREFIX_STRIP
176   /// environment variables.
177   std::string CoverageDataFile;
178 
179   /// The filename with path we use for coverage notes files.
180   std::string CoverageNotesFile;
181 
182   /// Regexes separated by a semi-colon to filter the files to instrument.
183   std::string ProfileFilterFiles;
184 
185   /// Regexes separated by a semi-colon to filter the files to not instrument.
186   std::string ProfileExcludeFiles;
187 
188   /// The version string to put into coverage files.
189   char CoverageVersion[4];
190 
191   /// Enable additional debugging information.
192   std::string DebugPass;
193 
194   /// The string to embed in debug information as the current working directory.
195   std::string DebugCompilationDir;
196 
197   /// The string to embed in coverage mapping as the current working directory.
198   std::string CoverageCompilationDir;
199 
200   /// The string to embed in the debug information for the compile unit, if
201   /// non-empty.
202   std::string DwarfDebugFlags;
203 
204   /// The string containing the commandline for the llvm.commandline metadata,
205   /// if non-empty.
206   std::string RecordCommandLine;
207 
208   llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
209 
210   /// Prefix replacement map for source-based code coverage to remap source
211   /// file paths in coverage mapping.
212   llvm::SmallVector<std::pair<std::string, std::string>, 0> CoveragePrefixMap;
213 
214   /// The ABI to use for passing floating point arguments.
215   std::string FloatABI;
216 
217   /// The file to use for dumping bug report by `Debugify` for original
218   /// debug info.
219   std::string DIBugsReportFilePath;
220 
221   /// The floating-point denormal mode to use.
222   llvm::DenormalMode FPDenormalMode = llvm::DenormalMode::getIEEE();
223 
224   /// The floating-point denormal mode to use, for float.
225   llvm::DenormalMode FP32DenormalMode = llvm::DenormalMode::getIEEE();
226 
227   /// The float precision limit to use, if non-empty.
228   std::string LimitFloatPrecision;
229 
230   struct BitcodeFileToLink {
231     /// The filename of the bitcode file to link in.
232     std::string Filename;
233     /// If true, we set attributes functions in the bitcode library according to
234     /// our CodeGenOptions, much as we set attrs on functions that we generate
235     /// ourselves.
236     bool PropagateAttrs = false;
237     /// If true, we use LLVM module internalizer.
238     bool Internalize = false;
239     /// Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker.
240     unsigned LinkFlags = 0;
241   };
242 
243   /// The files specified here are linked in to the module before optimizations.
244   std::vector<BitcodeFileToLink> LinkBitcodeFiles;
245 
246   /// The user provided name for the "main file", if non-empty. This is useful
247   /// in situations where the input file name does not match the original input
248   /// file, for example with -save-temps.
249   std::string MainFileName;
250 
251   /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
252   /// attribute in the skeleton CU.
253   std::string SplitDwarfFile;
254 
255   /// Output filename for the split debug info, not used in the skeleton CU.
256   std::string SplitDwarfOutput;
257 
258   /// Output filename used in the COFF debug information.
259   std::string ObjectFilenameForDebug;
260 
261   /// The name of the relocation model to use.
262   llvm::Reloc::Model RelocationModel;
263 
264   /// If not an empty string, trap intrinsics are lowered to calls to this
265   /// function instead of to trap instructions.
266   std::string TrapFuncName;
267 
268   /// A list of dependent libraries.
269   std::vector<std::string> DependentLibraries;
270 
271   /// A list of linker options to embed in the object file.
272   std::vector<std::string> LinkerOptions;
273 
274   /// Name of the profile file to use as output for -fprofile-instr-generate,
275   /// -fprofile-generate, and -fcs-profile-generate.
276   std::string InstrProfileOutput;
277 
278   /// Name of the profile file to use with -fprofile-sample-use.
279   std::string SampleProfileFile;
280 
281   /// Name of the profile file to use as output for with -fmemory-profile.
282   std::string MemoryProfileOutput;
283 
284   /// Name of the profile file to use as input for -fmemory-profile-use.
285   std::string MemoryProfileUsePath;
286 
287   /// Name of the profile file to use as input for -fprofile-instr-use
288   std::string ProfileInstrumentUsePath;
289 
290   /// Name of the profile remapping file to apply to the profile data supplied
291   /// by -fprofile-sample-use or -fprofile-instr-use.
292   std::string ProfileRemappingFile;
293 
294   /// Name of the function summary index file to use for ThinLTO function
295   /// importing.
296   std::string ThinLTOIndexFile;
297 
298   /// Name of a file that can optionally be written with minimized bitcode
299   /// to be used as input for the ThinLTO thin link step, which only needs
300   /// the summary and module symbol table (and not, e.g. any debug metadata).
301   std::string ThinLinkBitcodeFile;
302 
303   /// Prefix to use for -save-temps output.
304   std::string SaveTempsFilePrefix;
305 
306   /// Name of file passed with -fcuda-include-gpubinary option to forward to
307   /// CUDA runtime back-end for incorporating them into host-side object file.
308   std::string CudaGpuBinaryFileName;
309 
310   /// List of filenames passed in using the -fembed-offload-object option. These
311   /// are offloading binaries containing device images and metadata.
312   std::vector<std::string> OffloadObjects;
313 
314   /// The name of the file to which the backend should save YAML optimization
315   /// records.
316   std::string OptRecordFile;
317 
318   /// The regex that filters the passes that should be saved to the optimization
319   /// records.
320   std::string OptRecordPasses;
321 
322   /// The format used for serializing remarks (default: YAML)
323   std::string OptRecordFormat;
324 
325   /// The name of the partition that symbols are assigned to, specified with
326   /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html).
327   std::string SymbolPartition;
328 
329   enum RemarkKind {
330     RK_Missing,            // Remark argument not present on the command line.
331     RK_Enabled,            // Remark enabled via '-Rgroup'.
332     RK_EnabledEverything,  // Remark enabled via '-Reverything'.
333     RK_Disabled,           // Remark disabled via '-Rno-group'.
334     RK_DisabledEverything, // Remark disabled via '-Rno-everything'.
335     RK_WithPattern,        // Remark pattern specified via '-Rgroup=regexp'.
336   };
337 
338   /// Optimization remark with an optional regular expression pattern.
339   struct OptRemark {
340     RemarkKind Kind = RK_Missing;
341     std::string Pattern;
342     std::shared_ptr<llvm::Regex> Regex;
343 
344     /// By default, optimization remark is missing.
345     OptRemark() = default;
346 
347     /// Returns true iff the optimization remark holds a valid regular
348     /// expression.
hasValidPatternOptRemark349     bool hasValidPattern() const { return Regex != nullptr; }
350 
351     /// Matches the given string against the regex, if there is some.
patternMatchesOptRemark352     bool patternMatches(StringRef String) const {
353       return hasValidPattern() && Regex->match(String);
354     }
355   };
356 
357   /// Selected optimizations for which we should enable optimization remarks.
358   /// Transformation passes whose name matches the contained (optional) regular
359   /// expression (and support this feature), will emit a diagnostic whenever
360   /// they perform a transformation.
361   OptRemark OptimizationRemark;
362 
363   /// Selected optimizations for which we should enable missed optimization
364   /// remarks. Transformation passes whose name matches the contained (optional)
365   /// regular expression (and support this feature), will emit a diagnostic
366   /// whenever they tried but failed to perform a transformation.
367   OptRemark OptimizationRemarkMissed;
368 
369   /// Selected optimizations for which we should enable optimization analyses.
370   /// Transformation passes whose name matches the contained (optional) regular
371   /// expression (and support this feature), will emit a diagnostic whenever
372   /// they want to explain why they decided to apply or not apply a given
373   /// transformation.
374   OptRemark OptimizationRemarkAnalysis;
375 
376   /// Set of sanitizer checks that are non-fatal (i.e. execution should be
377   /// continued when possible).
378   SanitizerSet SanitizeRecover;
379 
380   /// Set of sanitizer checks that trap rather than diagnose.
381   SanitizerSet SanitizeTrap;
382 
383   /// List of backend command-line options for -fembed-bitcode.
384   std::vector<uint8_t> CmdArgs;
385 
386   /// A list of all -fno-builtin-* function names (e.g., memset).
387   std::vector<std::string> NoBuiltinFuncs;
388 
389   std::vector<std::string> Reciprocals;
390 
391   /// The preferred width for auto-vectorization transforms. This is intended to
392   /// override default transforms based on the width of the architected vector
393   /// registers.
394   std::string PreferVectorWidth;
395 
396   /// Set of XRay instrumentation kinds to emit.
397   XRayInstrSet XRayInstrumentationBundle;
398 
399   std::vector<std::string> DefaultFunctionAttrs;
400 
401   /// List of dynamic shared object files to be loaded as pass plugins.
402   std::vector<std::string> PassPlugins;
403 
404   /// List of pass builder callbacks.
405   std::vector<std::function<void(llvm::PassBuilder &)>> PassBuilderCallbacks;
406 
407   /// Path to allowlist file specifying which objects
408   /// (files, functions) should exclusively be instrumented
409   /// by sanitizer coverage pass.
410   std::vector<std::string> SanitizeCoverageAllowlistFiles;
411 
412   /// The guard style used for stack protector to get a initial value, this
413   /// value usually be gotten from TLS or get from __stack_chk_guard, or some
414   /// other styles we may implement in the future.
415   std::string StackProtectorGuard;
416 
417   /// The TLS base register when StackProtectorGuard is "tls", or register used
418   /// to store the stack canary for "sysreg".
419   /// On x86 this can be "fs" or "gs".
420   /// On AArch64 this can only be "sp_el0".
421   std::string StackProtectorGuardReg;
422 
423   /// Specify a symbol to be the guard value.
424   std::string StackProtectorGuardSymbol;
425 
426   /// Path to ignorelist file specifying which objects
427   /// (files, functions) listed for instrumentation by sanitizer
428   /// coverage pass should actually not be instrumented.
429   std::vector<std::string> SanitizeCoverageIgnorelistFiles;
430 
431   /// Path to ignorelist file specifying which objects
432   /// (files, functions) listed for instrumentation by sanitizer
433   /// binary metadata pass should not be instrumented.
434   std::vector<std::string> SanitizeMetadataIgnorelistFiles;
435 
436   /// Name of the stack usage file (i.e., .su file) if user passes
437   /// -fstack-usage. If empty, it can be implied that -fstack-usage is not
438   /// passed on the command line.
439   std::string StackUsageOutput;
440 
441   /// Executable and command-line used to create a given CompilerInvocation.
442   /// Most of the time this will be the full -cc1 command.
443   const char *Argv0 = nullptr;
444   std::vector<std::string> CommandLineArgs;
445 
446   /// The minimum hotness value a diagnostic needs in order to be included in
447   /// optimization diagnostics.
448   ///
449   /// The threshold is an Optional value, which maps to one of the 3 states:
450   /// 1. 0            => threshold disabled. All remarks will be printed.
451   /// 2. positive int => manual threshold by user. Remarks with hotness exceed
452   ///                    threshold will be printed.
453   /// 3. None         => 'auto' threshold by user. The actual value is not
454   ///                    available at command line, but will be synced with
455   ///                    hotness threshold from profile summary during
456   ///                    compilation.
457   ///
458   /// If threshold option is not specified, it is disabled by default.
459   std::optional<uint64_t> DiagnosticsHotnessThreshold = 0;
460 
461   /// The maximum percentage profiling weights can deviate from the expected
462   /// values in order to be included in misexpect diagnostics.
463   std::optional<uint32_t> DiagnosticsMisExpectTolerance = 0;
464 
465   /// The name of a file to use with \c .secure_log_unique directives.
466   std::string AsSecureLogFile;
467 
468 public:
469   // Define accessors/mutators for code generation options of enumeration type.
470 #define CODEGENOPT(Name, Bits, Default)
471 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) \
472   Type get##Name() const { return static_cast<Type>(Name); } \
473   void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
474 #include "clang/Basic/CodeGenOptions.def"
475 
476   CodeGenOptions();
477 
getNoBuiltinFuncs()478   const std::vector<std::string> &getNoBuiltinFuncs() const {
479     return NoBuiltinFuncs;
480   }
481 
482   /// Check if Clang profile instrumenation is on.
hasProfileClangInstr()483   bool hasProfileClangInstr() const {
484     return getProfileInstr() == ProfileClangInstr;
485   }
486 
487   /// Check if IR level profile instrumentation is on.
hasProfileIRInstr()488   bool hasProfileIRInstr() const {
489     return getProfileInstr() == ProfileIRInstr;
490   }
491 
492   /// Check if CS IR level profile instrumentation is on.
hasProfileCSIRInstr()493   bool hasProfileCSIRInstr() const {
494     return getProfileInstr() == ProfileCSIRInstr;
495   }
496 
497   /// Check if any form of instrumentation is on.
hasProfileInstr()498   bool hasProfileInstr() const { return getProfileInstr() != ProfileNone; }
499 
500   /// Check if Clang profile use is on.
hasProfileClangUse()501   bool hasProfileClangUse() const {
502     return getProfileUse() == ProfileClangInstr;
503   }
504 
505   /// Check if IR level profile use is on.
hasProfileIRUse()506   bool hasProfileIRUse() const {
507     return getProfileUse() == ProfileIRInstr ||
508            getProfileUse() == ProfileCSIRInstr;
509   }
510 
511   /// Check if CSIR profile use is on.
hasProfileCSIRUse()512   bool hasProfileCSIRUse() const { return getProfileUse() == ProfileCSIRInstr; }
513 
514   /// Check if type and variable info should be emitted.
hasReducedDebugInfo()515   bool hasReducedDebugInfo() const {
516     return getDebugInfo() >= llvm::codegenoptions::DebugInfoConstructor;
517   }
518 
519   /// Check if maybe unused type info should be emitted.
hasMaybeUnusedDebugInfo()520   bool hasMaybeUnusedDebugInfo() const {
521     return getDebugInfo() >= llvm::codegenoptions::UnusedTypeInfo;
522   }
523 
524   // Check if any one of SanitizeCoverage* is enabled.
hasSanitizeCoverage()525   bool hasSanitizeCoverage() const {
526     return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
527            SanitizeCoverageTraceCmp || SanitizeCoverageTraceLoads ||
528            SanitizeCoverageTraceStores || SanitizeCoverageControlFlow;
529   }
530 
531   // Check if any one of SanitizeBinaryMetadata* is enabled.
hasSanitizeBinaryMetadata()532   bool hasSanitizeBinaryMetadata() const {
533     return SanitizeBinaryMetadataCovered || SanitizeBinaryMetadataAtomics ||
534            SanitizeBinaryMetadataUAR;
535   }
536 
537   /// Reset all of the options that are not considered when building a
538   /// module.
539   void resetNonModularOptions(StringRef ModuleFormat);
540 };
541 
542 }  // end namespace clang
543 
544 #endif
545