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