Config.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-Config.h - LLVM Link Time Optimizer Configuration ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the lto::Config data structure, which allows clients to
  15. // configure LTO.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_LTO_CONFIG_H
  19. #define LLVM_LTO_CONFIG_H
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/DiagnosticInfo.h"
  23. #include "llvm/IR/GlobalValue.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/LegacyPassManager.h"
  26. #include "llvm/Passes/PassBuilder.h"
  27. #include "llvm/Support/CodeGen.h"
  28. #include "llvm/Target/TargetOptions.h"
  29. #include <functional>
  30. #include <optional>
  31. namespace llvm {
  32. class Error;
  33. class Module;
  34. class ModuleSummaryIndex;
  35. class raw_pwrite_stream;
  36. namespace lto {
  37. /// LTO configuration. A linker can configure LTO by setting fields in this data
  38. /// structure and passing it to the lto::LTO constructor.
  39. struct Config {
  40. enum VisScheme {
  41. FromPrevailing,
  42. ELF,
  43. };
  44. // Note: when adding fields here, consider whether they need to be added to
  45. // computeLTOCacheKey in LTO.cpp.
  46. std::string CPU;
  47. TargetOptions Options;
  48. std::vector<std::string> MAttrs;
  49. std::vector<std::string> MllvmArgs;
  50. std::vector<std::string> PassPlugins;
  51. /// For adding passes that run right before codegen.
  52. std::function<void(legacy::PassManager &)> PreCodeGenPassesHook;
  53. std::optional<Reloc::Model> RelocModel = Reloc::PIC_;
  54. std::optional<CodeModel::Model> CodeModel;
  55. CodeGenOpt::Level CGOptLevel = CodeGenOpt::Default;
  56. CodeGenFileType CGFileType = CGFT_ObjectFile;
  57. unsigned OptLevel = 2;
  58. bool DisableVerify = false;
  59. /// Use the standard optimization pipeline.
  60. bool UseDefaultPipeline = false;
  61. /// Flag to indicate that the optimizer should not assume builtins are present
  62. /// on the target.
  63. bool Freestanding = false;
  64. /// Disable entirely the optimizer, including importing for ThinLTO
  65. bool CodeGenOnly = false;
  66. /// Run PGO context sensitive IR instrumentation.
  67. bool RunCSIRInstr = false;
  68. /// Turn on/off the warning about a hash mismatch in the PGO profile data.
  69. bool PGOWarnMismatch = true;
  70. /// Asserts whether we can assume whole program visibility during the LTO
  71. /// link.
  72. bool HasWholeProgramVisibility = false;
  73. /// Always emit a Regular LTO object even when it is empty because no Regular
  74. /// LTO modules were linked. This option is useful for some build system which
  75. /// want to know a priori all possible output files.
  76. bool AlwaysEmitRegularLTOObj = false;
  77. /// Allows non-imported definitions to get the potentially more constraining
  78. /// visibility from the prevailing definition. FromPrevailing is the default
  79. /// because it works for many binary formats. ELF can use the more optimized
  80. /// 'ELF' scheme.
  81. VisScheme VisibilityScheme = FromPrevailing;
  82. /// If this field is set, the set of passes run in the middle-end optimizer
  83. /// will be the one specified by the string. Only works with the new pass
  84. /// manager as the old one doesn't have this ability.
  85. std::string OptPipeline;
  86. // If this field is set, it has the same effect of specifying an AA pipeline
  87. // identified by the string. Only works with the new pass manager, in
  88. // conjunction OptPipeline.
  89. std::string AAPipeline;
  90. /// Setting this field will replace target triples in input files with this
  91. /// triple.
  92. std::string OverrideTriple;
  93. /// Setting this field will replace unspecified target triples in input files
  94. /// with this triple.
  95. std::string DefaultTriple;
  96. /// Context Sensitive PGO profile path.
  97. std::string CSIRProfile;
  98. /// Sample PGO profile path.
  99. std::string SampleProfile;
  100. /// Name remapping file for profile data.
  101. std::string ProfileRemapping;
  102. /// The directory to store .dwo files.
  103. std::string DwoDir;
  104. /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
  105. /// attribute in the skeleton CU. This should generally only be used when
  106. /// running an individual backend directly via thinBackend(), as otherwise
  107. /// all objects would use the same .dwo file. Not used as output path.
  108. std::string SplitDwarfFile;
  109. /// The path to write a .dwo file to. This should generally only be used when
  110. /// running an individual backend directly via thinBackend(), as otherwise
  111. /// all .dwo files will be written to the same path. Not used in skeleton CU.
  112. std::string SplitDwarfOutput;
  113. /// Optimization remarks file path.
  114. std::string RemarksFilename;
  115. /// Optimization remarks pass filter.
  116. std::string RemarksPasses;
  117. /// Whether to emit optimization remarks with hotness informations.
  118. bool RemarksWithHotness = false;
  119. /// The minimum hotness value a diagnostic needs in order to be included in
  120. /// optimization diagnostics.
  121. ///
  122. /// The threshold is an Optional value, which maps to one of the 3 states:
  123. /// 1. 0 => threshold disabled. All emarks will be printed.
  124. /// 2. positive int => manual threshold by user. Remarks with hotness exceed
  125. /// threshold will be printed.
  126. /// 3. None => 'auto' threshold by user. The actual value is not
  127. /// available at command line, but will be synced with
  128. /// hotness threhold from profile summary during
  129. /// compilation.
  130. ///
  131. /// If threshold option is not specified, it is disabled by default.
  132. std::optional<uint64_t> RemarksHotnessThreshold = 0;
  133. /// The format used for serializing remarks (default: YAML).
  134. std::string RemarksFormat;
  135. /// Whether to emit the pass manager debuggging informations.
  136. bool DebugPassManager = false;
  137. /// Statistics output file path.
  138. std::string StatsFile;
  139. /// Specific thinLTO modules to compile.
  140. std::vector<std::string> ThinLTOModulesToCompile;
  141. /// Time trace enabled.
  142. bool TimeTraceEnabled = false;
  143. /// Time trace granularity.
  144. unsigned TimeTraceGranularity = 500;
  145. bool ShouldDiscardValueNames = true;
  146. DiagnosticHandlerFunction DiagHandler;
  147. /// Add FSAFDO discriminators.
  148. bool AddFSDiscriminator = false;
  149. /// Use opaque pointer types. Used to call LLVMContext::setOpaquePointers
  150. /// unless already set by the `-opaque-pointers` commandline option.
  151. bool OpaquePointers = true;
  152. /// If this field is set, LTO will write input file paths and symbol
  153. /// resolutions here in llvm-lto2 command line flag format. This can be
  154. /// used for testing and for running the LTO pipeline outside of the linker
  155. /// with llvm-lto2.
  156. std::unique_ptr<raw_ostream> ResolutionFile;
  157. /// Tunable parameters for passes in the default pipelines.
  158. PipelineTuningOptions PTO;
  159. /// The following callbacks deal with tasks, which normally represent the
  160. /// entire optimization and code generation pipeline for what will become a
  161. /// single native object file. Each task has a unique identifier between 0 and
  162. /// getMaxTasks()-1, which is supplied to the callback via the Task parameter.
  163. /// A task represents the entire pipeline for ThinLTO and regular
  164. /// (non-parallel) LTO, but a parallel code generation task will be split into
  165. /// N tasks before code generation, where N is the parallelism level.
  166. ///
  167. /// LTO may decide to stop processing a task at any time, for example if the
  168. /// module is empty or if a module hook (see below) returns false. For this
  169. /// reason, the client should not expect to receive exactly getMaxTasks()
  170. /// native object files.
  171. /// A module hook may be used by a linker to perform actions during the LTO
  172. /// pipeline. For example, a linker may use this function to implement
  173. /// -save-temps. If this function returns false, any further processing for
  174. /// that task is aborted.
  175. ///
  176. /// Module hooks must be thread safe with respect to the linker's internal
  177. /// data structures. A module hook will never be called concurrently from
  178. /// multiple threads with the same task ID, or the same module.
  179. ///
  180. /// Note that in out-of-process backend scenarios, none of the hooks will be
  181. /// called for ThinLTO tasks.
  182. using ModuleHookFn = std::function<bool(unsigned Task, const Module &)>;
  183. /// This module hook is called after linking (regular LTO) or loading
  184. /// (ThinLTO) the module, before modifying it.
  185. ModuleHookFn PreOptModuleHook;
  186. /// This hook is called after promoting any internal functions
  187. /// (ThinLTO-specific).
  188. ModuleHookFn PostPromoteModuleHook;
  189. /// This hook is called after internalizing the module.
  190. ModuleHookFn PostInternalizeModuleHook;
  191. /// This hook is called after importing from other modules (ThinLTO-specific).
  192. ModuleHookFn PostImportModuleHook;
  193. /// This module hook is called after optimization is complete.
  194. ModuleHookFn PostOptModuleHook;
  195. /// This module hook is called before code generation. It is similar to the
  196. /// PostOptModuleHook, but for parallel code generation it is called after
  197. /// splitting the module.
  198. ModuleHookFn PreCodeGenModuleHook;
  199. /// A combined index hook is called after all per-module indexes have been
  200. /// combined (ThinLTO-specific). It can be used to implement -save-temps for
  201. /// the combined index.
  202. ///
  203. /// If this function returns false, any further processing for ThinLTO tasks
  204. /// is aborted.
  205. ///
  206. /// It is called regardless of whether the backend is in-process, although it
  207. /// is not called from individual backend processes.
  208. using CombinedIndexHookFn = std::function<bool(
  209. const ModuleSummaryIndex &Index,
  210. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)>;
  211. CombinedIndexHookFn CombinedIndexHook;
  212. /// This is a convenience function that configures this Config object to write
  213. /// temporary files named after the given OutputFileName for each of the LTO
  214. /// phases to disk. A client can use this function to implement -save-temps.
  215. ///
  216. /// FIXME: Temporary files derived from ThinLTO backends are currently named
  217. /// after the input file name, rather than the output file name, when
  218. /// UseInputModulePath is set to true.
  219. ///
  220. /// Specifically, it (1) sets each of the above module hooks and the combined
  221. /// index hook to a function that calls the hook function (if any) that was
  222. /// present in the appropriate field when the addSaveTemps function was
  223. /// called, and writes the module to a bitcode file with a name prefixed by
  224. /// the given output file name, and (2) creates a resolution file whose name
  225. /// is prefixed by the given output file name and sets ResolutionFile to its
  226. /// file handle.
  227. ///
  228. /// SaveTempsArgs can be specified to select which temps to save.
  229. /// If SaveTempsArgs is not provided, all temps are saved.
  230. Error addSaveTemps(std::string OutputFileName,
  231. bool UseInputModulePath = false,
  232. const DenseSet<StringRef> &SaveTempsArgs = {});
  233. };
  234. struct LTOLLVMDiagnosticHandler : public DiagnosticHandler {
  235. DiagnosticHandlerFunction *Fn;
  236. LTOLLVMDiagnosticHandler(DiagnosticHandlerFunction *DiagHandlerFn)
  237. : Fn(DiagHandlerFn) {}
  238. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  239. (*Fn)(DI);
  240. return true;
  241. }
  242. };
  243. /// A derived class of LLVMContext that initializes itself according to a given
  244. /// Config object. The purpose of this class is to tie ownership of the
  245. /// diagnostic handler to the context, as opposed to the Config object (which
  246. /// may be ephemeral).
  247. // FIXME: This should not be required as diagnostic handler is not callback.
  248. struct LTOLLVMContext : LLVMContext {
  249. LTOLLVMContext(const Config &C) : DiagHandler(C.DiagHandler) {
  250. setDiscardValueNames(C.ShouldDiscardValueNames);
  251. enableDebugTypeODRUniquing();
  252. setDiagnosticHandler(
  253. std::make_unique<LTOLLVMDiagnosticHandler>(&DiagHandler), true);
  254. setOpaquePointers(C.OpaquePointers);
  255. }
  256. DiagnosticHandlerFunction DiagHandler;
  257. };
  258. }
  259. }
  260. #endif
  261. #ifdef __GNUC__
  262. #pragma GCC diagnostic pop
  263. #endif