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