BackendUtil.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/CodeGen/BackendUtil.h"
  10. #include "clang/Basic/CodeGenOptions.h"
  11. #include "clang/Basic/Diagnostic.h"
  12. #include "clang/Basic/LangOptions.h"
  13. #include "clang/Basic/TargetOptions.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/Utils.h"
  16. #include "clang/Lex/HeaderSearchOptions.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringSwitch.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Analysis/TargetLibraryInfo.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Bitcode/BitcodeReader.h"
  24. #include "llvm/Bitcode/BitcodeWriter.h"
  25. #include "llvm/Bitcode/BitcodeWriterPass.h"
  26. #include "llvm/CodeGen/RegAllocRegistry.h"
  27. #include "llvm/CodeGen/SchedulerRegistry.h"
  28. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/IRPrintingPasses.h"
  31. #include "llvm/IR/LegacyPassManager.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/ModuleSummaryIndex.h"
  34. #include "llvm/IR/Verifier.h"
  35. #include "llvm/LTO/LTOBackend.h"
  36. #include "llvm/MC/MCAsmInfo.h"
  37. #include "llvm/MC/SubtargetFeature.h"
  38. #include "llvm/Passes/PassBuilder.h"
  39. #include "llvm/Support/BuryPointer.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/PrettyStackTrace.h"
  43. #include "llvm/Support/TargetRegistry.h"
  44. #include "llvm/Support/Timer.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Target/TargetMachine.h"
  47. #include "llvm/Target/TargetOptions.h"
  48. #include "llvm/Transforms/Coroutines.h"
  49. #include "llvm/Transforms/IPO.h"
  50. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  51. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  52. #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
  53. #include "llvm/Transforms/InstCombine/InstCombine.h"
  54. #include "llvm/Transforms/Instrumentation.h"
  55. #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
  56. #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
  57. #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
  58. #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
  59. #include "llvm/Transforms/ObjCARC.h"
  60. #include "llvm/Transforms/Scalar.h"
  61. #include "llvm/Transforms/Scalar/GVN.h"
  62. #include "llvm/Transforms/Utils.h"
  63. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  64. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  65. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  66. #include <memory>
  67. using namespace clang;
  68. using namespace llvm;
  69. namespace {
  70. // Default filename used for profile generation.
  71. static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
  72. class EmitAssemblyHelper {
  73. DiagnosticsEngine &Diags;
  74. const HeaderSearchOptions &HSOpts;
  75. const CodeGenOptions &CodeGenOpts;
  76. const clang::TargetOptions &TargetOpts;
  77. const LangOptions &LangOpts;
  78. Module *TheModule;
  79. Timer CodeGenerationTime;
  80. std::unique_ptr<raw_pwrite_stream> OS;
  81. TargetIRAnalysis getTargetIRAnalysis() const {
  82. if (TM)
  83. return TM->getTargetIRAnalysis();
  84. return TargetIRAnalysis();
  85. }
  86. void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
  87. /// Generates the TargetMachine.
  88. /// Leaves TM unchanged if it is unable to create the target machine.
  89. /// Some of our clang tests specify triples which are not built
  90. /// into clang. This is okay because these tests check the generated
  91. /// IR, and they require DataLayout which depends on the triple.
  92. /// In this case, we allow this method to fail and not report an error.
  93. /// When MustCreateTM is used, we print an error if we are unable to load
  94. /// the requested target.
  95. void CreateTargetMachine(bool MustCreateTM);
  96. /// Add passes necessary to emit assembly or LLVM IR.
  97. ///
  98. /// \return True on success.
  99. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
  100. raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
  101. std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
  102. std::error_code EC;
  103. auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
  104. llvm::sys::fs::F_None);
  105. if (EC) {
  106. Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
  107. F.reset();
  108. }
  109. return F;
  110. }
  111. public:
  112. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  113. const HeaderSearchOptions &HeaderSearchOpts,
  114. const CodeGenOptions &CGOpts,
  115. const clang::TargetOptions &TOpts,
  116. const LangOptions &LOpts, Module *M)
  117. : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
  118. TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
  119. CodeGenerationTime("codegen", "Code Generation Time") {}
  120. ~EmitAssemblyHelper() {
  121. if (CodeGenOpts.DisableFree)
  122. BuryPointer(std::move(TM));
  123. }
  124. std::unique_ptr<TargetMachine> TM;
  125. void EmitAssembly(BackendAction Action,
  126. std::unique_ptr<raw_pwrite_stream> OS);
  127. void EmitAssemblyWithNewPassManager(BackendAction Action,
  128. std::unique_ptr<raw_pwrite_stream> OS);
  129. };
  130. // We need this wrapper to access LangOpts and CGOpts from extension functions
  131. // that we add to the PassManagerBuilder.
  132. class PassManagerBuilderWrapper : public PassManagerBuilder {
  133. public:
  134. PassManagerBuilderWrapper(const Triple &TargetTriple,
  135. const CodeGenOptions &CGOpts,
  136. const LangOptions &LangOpts)
  137. : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
  138. LangOpts(LangOpts) {}
  139. const Triple &getTargetTriple() const { return TargetTriple; }
  140. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  141. const LangOptions &getLangOpts() const { return LangOpts; }
  142. private:
  143. const Triple &TargetTriple;
  144. const CodeGenOptions &CGOpts;
  145. const LangOptions &LangOpts;
  146. };
  147. }
  148. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  149. if (Builder.OptLevel > 0)
  150. PM.add(createObjCARCAPElimPass());
  151. }
  152. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  153. if (Builder.OptLevel > 0)
  154. PM.add(createObjCARCExpandPass());
  155. }
  156. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  157. if (Builder.OptLevel > 0)
  158. PM.add(createObjCARCOptPass());
  159. }
  160. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  161. legacy::PassManagerBase &PM) {
  162. PM.add(createAddDiscriminatorsPass());
  163. }
  164. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  165. legacy::PassManagerBase &PM) {
  166. PM.add(createBoundsCheckingLegacyPass());
  167. }
  168. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  169. legacy::PassManagerBase &PM) {
  170. const PassManagerBuilderWrapper &BuilderWrapper =
  171. static_cast<const PassManagerBuilderWrapper&>(Builder);
  172. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  173. SanitizerCoverageOptions Opts;
  174. Opts.CoverageType =
  175. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  176. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  177. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  178. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  179. Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
  180. Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
  181. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  182. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  183. Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
  184. Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
  185. Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
  186. Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
  187. Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
  188. PM.add(createSanitizerCoverageModulePass(Opts));
  189. }
  190. // Check if ASan should use GC-friendly instrumentation for globals.
  191. // First of all, there is no point if -fdata-sections is off (expect for MachO,
  192. // where this is not a factor). Also, on ELF this feature requires an assembler
  193. // extension that only works with -integrated-as at the moment.
  194. static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
  195. if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
  196. return false;
  197. switch (T.getObjectFormat()) {
  198. case Triple::MachO:
  199. case Triple::COFF:
  200. return true;
  201. case Triple::ELF:
  202. return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
  203. default:
  204. return false;
  205. }
  206. }
  207. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  208. legacy::PassManagerBase &PM) {
  209. const PassManagerBuilderWrapper &BuilderWrapper =
  210. static_cast<const PassManagerBuilderWrapper&>(Builder);
  211. const Triple &T = BuilderWrapper.getTargetTriple();
  212. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  213. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  214. bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
  215. bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
  216. bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
  217. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
  218. UseAfterScope));
  219. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
  220. UseGlobalsGC, UseOdrIndicator));
  221. }
  222. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  223. legacy::PassManagerBase &PM) {
  224. PM.add(createAddressSanitizerFunctionPass(
  225. /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
  226. PM.add(createAddressSanitizerModulePass(
  227. /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
  228. /*UseOdrIndicator*/ false));
  229. }
  230. static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
  231. legacy::PassManagerBase &PM) {
  232. const PassManagerBuilderWrapper &BuilderWrapper =
  233. static_cast<const PassManagerBuilderWrapper &>(Builder);
  234. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  235. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
  236. PM.add(createHWAddressSanitizerPass(/*CompileKernel*/ false, Recover));
  237. }
  238. static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
  239. legacy::PassManagerBase &PM) {
  240. PM.add(createHWAddressSanitizerPass(
  241. /*CompileKernel*/ true, /*Recover*/ true));
  242. }
  243. static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
  244. legacy::PassManagerBase &PM,
  245. bool CompileKernel) {
  246. const PassManagerBuilderWrapper &BuilderWrapper =
  247. static_cast<const PassManagerBuilderWrapper&>(Builder);
  248. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  249. int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
  250. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
  251. PM.add(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover, CompileKernel));
  252. // MemorySanitizer inserts complex instrumentation that mostly follows
  253. // the logic of the original code, but operates on "shadow" values.
  254. // It can benefit from re-running some general purpose optimization passes.
  255. if (Builder.OptLevel > 0) {
  256. PM.add(createEarlyCSEPass());
  257. PM.add(createReassociatePass());
  258. PM.add(createLICMPass());
  259. PM.add(createGVNPass());
  260. PM.add(createInstructionCombiningPass());
  261. PM.add(createDeadStoreEliminationPass());
  262. }
  263. }
  264. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  265. legacy::PassManagerBase &PM) {
  266. addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
  267. }
  268. static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
  269. legacy::PassManagerBase &PM) {
  270. addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
  271. }
  272. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  273. legacy::PassManagerBase &PM) {
  274. PM.add(createThreadSanitizerLegacyPassPass());
  275. }
  276. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  277. legacy::PassManagerBase &PM) {
  278. const PassManagerBuilderWrapper &BuilderWrapper =
  279. static_cast<const PassManagerBuilderWrapper&>(Builder);
  280. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  281. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  282. }
  283. static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
  284. legacy::PassManagerBase &PM) {
  285. const PassManagerBuilderWrapper &BuilderWrapper =
  286. static_cast<const PassManagerBuilderWrapper&>(Builder);
  287. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  288. EfficiencySanitizerOptions Opts;
  289. if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
  290. Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
  291. else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
  292. Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
  293. PM.add(createEfficiencySanitizerPass(Opts));
  294. }
  295. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  296. const CodeGenOptions &CodeGenOpts) {
  297. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  298. if (!CodeGenOpts.SimplifyLibCalls)
  299. TLII->disableAllFunctions();
  300. else {
  301. // Disable individual libc/libm calls in TargetLibraryInfo.
  302. LibFunc F;
  303. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  304. if (TLII->getLibFunc(FuncName, F))
  305. TLII->setUnavailable(F);
  306. }
  307. switch (CodeGenOpts.getVecLib()) {
  308. case CodeGenOptions::Accelerate:
  309. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  310. break;
  311. case CodeGenOptions::SVML:
  312. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
  313. break;
  314. default:
  315. break;
  316. }
  317. return TLII;
  318. }
  319. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  320. legacy::PassManager *MPM) {
  321. llvm::SymbolRewriter::RewriteDescriptorList DL;
  322. llvm::SymbolRewriter::RewriteMapParser MapParser;
  323. for (const auto &MapFile : Opts.RewriteMapFiles)
  324. MapParser.parse(MapFile, &DL);
  325. MPM->add(createRewriteSymbolsPass(DL));
  326. }
  327. static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
  328. switch (CodeGenOpts.OptimizationLevel) {
  329. default:
  330. llvm_unreachable("Invalid optimization level!");
  331. case 0:
  332. return CodeGenOpt::None;
  333. case 1:
  334. return CodeGenOpt::Less;
  335. case 2:
  336. return CodeGenOpt::Default; // O2/Os/Oz
  337. case 3:
  338. return CodeGenOpt::Aggressive;
  339. }
  340. }
  341. static Optional<llvm::CodeModel::Model>
  342. getCodeModel(const CodeGenOptions &CodeGenOpts) {
  343. unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  344. .Case("tiny", llvm::CodeModel::Tiny)
  345. .Case("small", llvm::CodeModel::Small)
  346. .Case("kernel", llvm::CodeModel::Kernel)
  347. .Case("medium", llvm::CodeModel::Medium)
  348. .Case("large", llvm::CodeModel::Large)
  349. .Case("default", ~1u)
  350. .Default(~0u);
  351. assert(CodeModel != ~0u && "invalid code model!");
  352. if (CodeModel == ~1u)
  353. return None;
  354. return static_cast<llvm::CodeModel::Model>(CodeModel);
  355. }
  356. static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
  357. if (Action == Backend_EmitObj)
  358. return TargetMachine::CGFT_ObjectFile;
  359. else if (Action == Backend_EmitMCNull)
  360. return TargetMachine::CGFT_Null;
  361. else {
  362. assert(Action == Backend_EmitAssembly && "Invalid action!");
  363. return TargetMachine::CGFT_AssemblyFile;
  364. }
  365. }
  366. static void initTargetOptions(llvm::TargetOptions &Options,
  367. const CodeGenOptions &CodeGenOpts,
  368. const clang::TargetOptions &TargetOpts,
  369. const LangOptions &LangOpts,
  370. const HeaderSearchOptions &HSOpts) {
  371. Options.ThreadModel =
  372. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  373. .Case("posix", llvm::ThreadModel::POSIX)
  374. .Case("single", llvm::ThreadModel::Single);
  375. // Set float ABI type.
  376. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  377. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  378. "Invalid Floating Point ABI!");
  379. Options.FloatABIType =
  380. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  381. .Case("soft", llvm::FloatABI::Soft)
  382. .Case("softfp", llvm::FloatABI::Soft)
  383. .Case("hard", llvm::FloatABI::Hard)
  384. .Default(llvm::FloatABI::Default);
  385. // Set FP fusion mode.
  386. switch (LangOpts.getDefaultFPContractMode()) {
  387. case LangOptions::FPC_Off:
  388. // Preserve any contraction performed by the front-end. (Strict performs
  389. // splitting of the muladd intrinsic in the backend.)
  390. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  391. break;
  392. case LangOptions::FPC_On:
  393. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  394. break;
  395. case LangOptions::FPC_Fast:
  396. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  397. break;
  398. }
  399. Options.UseInitArray = CodeGenOpts.UseInitArray;
  400. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  401. Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
  402. Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
  403. // Set EABI version.
  404. Options.EABIVersion = TargetOpts.EABIVersion;
  405. if (LangOpts.SjLjExceptions)
  406. Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
  407. if (LangOpts.SEHExceptions)
  408. Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
  409. if (LangOpts.DWARFExceptions)
  410. Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
  411. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  412. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  413. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  414. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  415. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  416. Options.FunctionSections = CodeGenOpts.FunctionSections;
  417. Options.DataSections = CodeGenOpts.DataSections;
  418. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  419. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  420. Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
  421. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  422. Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
  423. Options.EmitAddrsig = CodeGenOpts.Addrsig;
  424. if (CodeGenOpts.getSplitDwarfMode() != CodeGenOptions::NoFission)
  425. Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
  426. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  427. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  428. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  429. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  430. Options.MCOptions.MCIncrementalLinkerCompatible =
  431. CodeGenOpts.IncrementalLinkerCompatible;
  432. Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
  433. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  434. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  435. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  436. Options.MCOptions.ABIName = TargetOpts.ABI;
  437. for (const auto &Entry : HSOpts.UserEntries)
  438. if (!Entry.IsFramework &&
  439. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  440. Entry.Group == frontend::IncludeDirGroup::Angled ||
  441. Entry.Group == frontend::IncludeDirGroup::System))
  442. Options.MCOptions.IASSearchPaths.push_back(
  443. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  444. }
  445. static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
  446. if (CodeGenOpts.DisableGCov)
  447. return None;
  448. if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
  449. return None;
  450. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  451. // LLVM's -default-gcov-version flag is set to something invalid.
  452. GCOVOptions Options;
  453. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  454. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  455. llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
  456. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  457. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  458. Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
  459. Options.Filter = CodeGenOpts.ProfileFilterFiles;
  460. Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
  461. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  462. return Options;
  463. }
  464. void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
  465. legacy::FunctionPassManager &FPM) {
  466. // Handle disabling of all LLVM passes, where we want to preserve the
  467. // internal module before any optimization.
  468. if (CodeGenOpts.DisableLLVMPasses)
  469. return;
  470. // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
  471. // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
  472. // are inserted before PMBuilder ones - they'd get the default-constructed
  473. // TLI with an unknown target otherwise.
  474. Triple TargetTriple(TheModule->getTargetTriple());
  475. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  476. createTLII(TargetTriple, CodeGenOpts));
  477. PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
  478. // At O0 and O1 we only run the always inliner which is more efficient. At
  479. // higher optimization levels we run the normal inliner.
  480. if (CodeGenOpts.OptimizationLevel <= 1) {
  481. bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
  482. !CodeGenOpts.DisableLifetimeMarkers);
  483. PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
  484. } else {
  485. // We do not want to inline hot callsites for SamplePGO module-summary build
  486. // because profile annotation will happen again in ThinLTO backend, and we
  487. // want the IR of the hot path to match the profile.
  488. PMBuilder.Inliner = createFunctionInliningPass(
  489. CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
  490. (!CodeGenOpts.SampleProfileFile.empty() &&
  491. CodeGenOpts.PrepareForThinLTO));
  492. }
  493. PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
  494. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  495. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  496. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  497. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  498. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  499. PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
  500. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  501. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  502. MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  503. if (TM)
  504. TM->adjustPassManager(PMBuilder);
  505. if (CodeGenOpts.DebugInfoForProfiling ||
  506. !CodeGenOpts.SampleProfileFile.empty())
  507. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  508. addAddDiscriminatorsPass);
  509. // In ObjC ARC mode, add the main ARC optimization passes.
  510. if (LangOpts.ObjCAutoRefCount) {
  511. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  512. addObjCARCExpandPass);
  513. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  514. addObjCARCAPElimPass);
  515. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  516. addObjCARCOptPass);
  517. }
  518. if (LangOpts.CoroutinesTS)
  519. addCoroutinePassesToExtensionPoints(PMBuilder);
  520. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  521. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  522. addBoundsCheckingPass);
  523. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  524. addBoundsCheckingPass);
  525. }
  526. if (CodeGenOpts.SanitizeCoverageType ||
  527. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  528. CodeGenOpts.SanitizeCoverageTraceCmp) {
  529. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  530. addSanitizerCoveragePass);
  531. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  532. addSanitizerCoveragePass);
  533. }
  534. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  535. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  536. addAddressSanitizerPasses);
  537. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  538. addAddressSanitizerPasses);
  539. }
  540. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  541. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  542. addKernelAddressSanitizerPasses);
  543. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  544. addKernelAddressSanitizerPasses);
  545. }
  546. if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
  547. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  548. addHWAddressSanitizerPasses);
  549. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  550. addHWAddressSanitizerPasses);
  551. }
  552. if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
  553. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  554. addKernelHWAddressSanitizerPasses);
  555. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  556. addKernelHWAddressSanitizerPasses);
  557. }
  558. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  559. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  560. addMemorySanitizerPass);
  561. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  562. addMemorySanitizerPass);
  563. }
  564. if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
  565. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  566. addKernelMemorySanitizerPass);
  567. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  568. addKernelMemorySanitizerPass);
  569. }
  570. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  571. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  572. addThreadSanitizerPass);
  573. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  574. addThreadSanitizerPass);
  575. }
  576. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  577. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  578. addDataFlowSanitizerPass);
  579. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  580. addDataFlowSanitizerPass);
  581. }
  582. if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
  583. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  584. addEfficiencySanitizerPass);
  585. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  586. addEfficiencySanitizerPass);
  587. }
  588. // Set up the per-function pass manager.
  589. FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  590. if (CodeGenOpts.VerifyModule)
  591. FPM.add(createVerifierPass());
  592. // Set up the per-module pass manager.
  593. if (!CodeGenOpts.RewriteMapFiles.empty())
  594. addSymbolRewriterPass(CodeGenOpts, &MPM);
  595. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
  596. MPM.add(createGCOVProfilerPass(*Options));
  597. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  598. MPM.add(createStripSymbolsPass(true));
  599. }
  600. if (CodeGenOpts.hasProfileClangInstr()) {
  601. InstrProfOptions Options;
  602. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  603. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  604. // TODO: Surface the option to emit atomic profile counter increments at
  605. // the driver level.
  606. Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
  607. MPM.add(createInstrProfilingLegacyPass(Options));
  608. }
  609. if (CodeGenOpts.hasProfileIRInstr()) {
  610. PMBuilder.EnablePGOInstrGen = true;
  611. if (!CodeGenOpts.InstrProfileOutput.empty())
  612. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  613. else
  614. PMBuilder.PGOInstrGen = DefaultProfileGenName;
  615. }
  616. if (CodeGenOpts.hasProfileIRUse())
  617. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  618. if (!CodeGenOpts.SampleProfileFile.empty())
  619. PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
  620. PMBuilder.populateFunctionPassManager(FPM);
  621. PMBuilder.populateModulePassManager(MPM);
  622. }
  623. static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
  624. SmallVector<const char *, 16> BackendArgs;
  625. BackendArgs.push_back("clang"); // Fake program name.
  626. if (!CodeGenOpts.DebugPass.empty()) {
  627. BackendArgs.push_back("-debug-pass");
  628. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  629. }
  630. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  631. BackendArgs.push_back("-limit-float-precision");
  632. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  633. }
  634. BackendArgs.push_back(nullptr);
  635. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  636. BackendArgs.data());
  637. }
  638. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  639. // Create the TargetMachine for generating code.
  640. std::string Error;
  641. std::string Triple = TheModule->getTargetTriple();
  642. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  643. if (!TheTarget) {
  644. if (MustCreateTM)
  645. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  646. return;
  647. }
  648. Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
  649. std::string FeaturesStr =
  650. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  651. llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
  652. CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
  653. llvm::TargetOptions Options;
  654. initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
  655. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  656. Options, RM, CM, OptLevel));
  657. }
  658. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  659. BackendAction Action,
  660. raw_pwrite_stream &OS,
  661. raw_pwrite_stream *DwoOS) {
  662. // Add LibraryInfo.
  663. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  664. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  665. createTLII(TargetTriple, CodeGenOpts));
  666. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  667. // Normal mode, emit a .s or .o file by running the code generator. Note,
  668. // this also adds codegenerator level optimization passes.
  669. TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
  670. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  671. // "codegen" passes so that it isn't run multiple times when there is
  672. // inlining happening.
  673. if (CodeGenOpts.OptimizationLevel > 0)
  674. CodeGenPasses.add(createObjCARCContractPass());
  675. if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
  676. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  677. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  678. return false;
  679. }
  680. return true;
  681. }
  682. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  683. std::unique_ptr<raw_pwrite_stream> OS) {
  684. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  685. setCommandLineOpts(CodeGenOpts);
  686. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  687. Action != Backend_EmitBC &&
  688. Action != Backend_EmitLL);
  689. CreateTargetMachine(UsesCodeGen);
  690. if (UsesCodeGen && !TM)
  691. return;
  692. if (TM)
  693. TheModule->setDataLayout(TM->createDataLayout());
  694. legacy::PassManager PerModulePasses;
  695. PerModulePasses.add(
  696. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  697. legacy::FunctionPassManager PerFunctionPasses(TheModule);
  698. PerFunctionPasses.add(
  699. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  700. CreatePasses(PerModulePasses, PerFunctionPasses);
  701. legacy::PassManager CodeGenPasses;
  702. CodeGenPasses.add(
  703. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  704. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  705. switch (Action) {
  706. case Backend_EmitNothing:
  707. break;
  708. case Backend_EmitBC:
  709. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  710. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  711. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  712. if (!ThinLinkOS)
  713. return;
  714. }
  715. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  716. CodeGenOpts.EnableSplitLTOUnit);
  717. PerModulePasses.add(createWriteThinLTOBitcodePass(
  718. *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
  719. } else {
  720. // Emit a module summary by default for Regular LTO except for ld64
  721. // targets
  722. bool EmitLTOSummary =
  723. (CodeGenOpts.PrepareForLTO &&
  724. !CodeGenOpts.DisableLLVMPasses &&
  725. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  726. llvm::Triple::Apple);
  727. if (EmitLTOSummary) {
  728. if (!TheModule->getModuleFlag("ThinLTO"))
  729. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  730. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  731. CodeGenOpts.EnableSplitLTOUnit);
  732. }
  733. PerModulePasses.add(createBitcodeWriterPass(
  734. *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  735. }
  736. break;
  737. case Backend_EmitLL:
  738. PerModulePasses.add(
  739. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  740. break;
  741. default:
  742. if (!CodeGenOpts.SplitDwarfFile.empty() &&
  743. (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) {
  744. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
  745. if (!DwoOS)
  746. return;
  747. }
  748. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  749. DwoOS ? &DwoOS->os() : nullptr))
  750. return;
  751. }
  752. // Before executing passes, print the final values of the LLVM options.
  753. cl::PrintOptionValues();
  754. // Run passes. For now we do all passes at once, but eventually we
  755. // would like to have the option of streaming code generation.
  756. {
  757. PrettyStackTraceString CrashInfo("Per-function optimization");
  758. PerFunctionPasses.doInitialization();
  759. for (Function &F : *TheModule)
  760. if (!F.isDeclaration())
  761. PerFunctionPasses.run(F);
  762. PerFunctionPasses.doFinalization();
  763. }
  764. {
  765. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  766. PerModulePasses.run(*TheModule);
  767. }
  768. {
  769. PrettyStackTraceString CrashInfo("Code generation");
  770. CodeGenPasses.run(*TheModule);
  771. }
  772. if (ThinLinkOS)
  773. ThinLinkOS->keep();
  774. if (DwoOS)
  775. DwoOS->keep();
  776. }
  777. static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  778. switch (Opts.OptimizationLevel) {
  779. default:
  780. llvm_unreachable("Invalid optimization level!");
  781. case 1:
  782. return PassBuilder::O1;
  783. case 2:
  784. switch (Opts.OptimizeSize) {
  785. default:
  786. llvm_unreachable("Invalid optimization level for size!");
  787. case 0:
  788. return PassBuilder::O2;
  789. case 1:
  790. return PassBuilder::Os;
  791. case 2:
  792. return PassBuilder::Oz;
  793. }
  794. case 3:
  795. return PassBuilder::O3;
  796. }
  797. }
  798. /// A clean version of `EmitAssembly` that uses the new pass manager.
  799. ///
  800. /// Not all features are currently supported in this system, but where
  801. /// necessary it falls back to the legacy pass manager to at least provide
  802. /// basic functionality.
  803. ///
  804. /// This API is planned to have its functionality finished and then to replace
  805. /// `EmitAssembly` at some point in the future when the default switches.
  806. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  807. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  808. TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
  809. setCommandLineOpts(CodeGenOpts);
  810. // The new pass manager always makes a target machine available to passes
  811. // during construction.
  812. CreateTargetMachine(/*MustCreateTM*/ true);
  813. if (!TM)
  814. // This will already be diagnosed, just bail.
  815. return;
  816. TheModule->setDataLayout(TM->createDataLayout());
  817. Optional<PGOOptions> PGOOpt;
  818. if (CodeGenOpts.hasProfileIRInstr())
  819. // -fprofile-generate.
  820. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
  821. ? DefaultProfileGenName
  822. : CodeGenOpts.InstrProfileOutput,
  823. "", "", "", true,
  824. CodeGenOpts.DebugInfoForProfiling);
  825. else if (CodeGenOpts.hasProfileIRUse())
  826. // -fprofile-use.
  827. PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "",
  828. CodeGenOpts.ProfileRemappingFile, false,
  829. CodeGenOpts.DebugInfoForProfiling);
  830. else if (!CodeGenOpts.SampleProfileFile.empty())
  831. // -fprofile-sample-use
  832. PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile,
  833. CodeGenOpts.ProfileRemappingFile, false,
  834. CodeGenOpts.DebugInfoForProfiling);
  835. else if (CodeGenOpts.DebugInfoForProfiling)
  836. // -fdebug-info-for-profiling
  837. PGOOpt = PGOOptions("", "", "", "", false, true);
  838. PassBuilder PB(TM.get(), PGOOpt);
  839. LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
  840. FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
  841. CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
  842. ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
  843. // Register the AA manager first so that our version is the one used.
  844. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  845. // Register the target library analysis directly and give it a customized
  846. // preset TLI.
  847. Triple TargetTriple(TheModule->getTargetTriple());
  848. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  849. createTLII(TargetTriple, CodeGenOpts));
  850. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  851. MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  852. // Register all the basic analyses with the managers.
  853. PB.registerModuleAnalyses(MAM);
  854. PB.registerCGSCCAnalyses(CGAM);
  855. PB.registerFunctionAnalyses(FAM);
  856. PB.registerLoopAnalyses(LAM);
  857. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  858. ModulePassManager MPM(CodeGenOpts.DebugPassManager);
  859. if (!CodeGenOpts.DisableLLVMPasses) {
  860. bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
  861. bool IsLTO = CodeGenOpts.PrepareForLTO;
  862. if (CodeGenOpts.OptimizationLevel == 0) {
  863. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  864. MPM.addPass(GCOVProfilerPass(*Options));
  865. // Build a minimal pipeline based on the semantics required by Clang,
  866. // which is just that always inlining occurs.
  867. MPM.addPass(AlwaysInlinerPass());
  868. // At -O0 we directly run necessary sanitizer passes.
  869. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  870. MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
  871. // Lastly, add semantically necessary passes for LTO.
  872. if (IsLTO || IsThinLTO) {
  873. MPM.addPass(CanonicalizeAliasesPass());
  874. MPM.addPass(NameAnonGlobalPass());
  875. }
  876. } else {
  877. // Map our optimization levels into one of the distinct levels used to
  878. // configure the pipeline.
  879. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  880. // Register callbacks to schedule sanitizer passes at the appropriate part of
  881. // the pipeline.
  882. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
  883. PB.registerScalarOptimizerLateEPCallback(
  884. [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
  885. FPM.addPass(BoundsCheckingPass());
  886. });
  887. if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
  888. PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
  889. MPM.addPass(GCOVProfilerPass(*Options));
  890. });
  891. if (IsThinLTO) {
  892. MPM = PB.buildThinLTOPreLinkDefaultPipeline(
  893. Level, CodeGenOpts.DebugPassManager);
  894. MPM.addPass(CanonicalizeAliasesPass());
  895. MPM.addPass(NameAnonGlobalPass());
  896. } else if (IsLTO) {
  897. MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
  898. CodeGenOpts.DebugPassManager);
  899. MPM.addPass(CanonicalizeAliasesPass());
  900. MPM.addPass(NameAnonGlobalPass());
  901. } else {
  902. MPM = PB.buildPerModuleDefaultPipeline(Level,
  903. CodeGenOpts.DebugPassManager);
  904. }
  905. }
  906. }
  907. // FIXME: We still use the legacy pass manager to do code generation. We
  908. // create that pass manager here and use it as needed below.
  909. legacy::PassManager CodeGenPasses;
  910. bool NeedCodeGen = false;
  911. std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
  912. // Append any output we need to the pass manager.
  913. switch (Action) {
  914. case Backend_EmitNothing:
  915. break;
  916. case Backend_EmitBC:
  917. if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
  918. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  919. ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
  920. if (!ThinLinkOS)
  921. return;
  922. }
  923. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  924. CodeGenOpts.EnableSplitLTOUnit);
  925. MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
  926. : nullptr));
  927. } else {
  928. // Emit a module summary by default for Regular LTO except for ld64
  929. // targets
  930. bool EmitLTOSummary =
  931. (CodeGenOpts.PrepareForLTO &&
  932. !CodeGenOpts.DisableLLVMPasses &&
  933. llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
  934. llvm::Triple::Apple);
  935. if (EmitLTOSummary) {
  936. if (!TheModule->getModuleFlag("ThinLTO"))
  937. TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
  938. TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  939. CodeGenOpts.EnableSplitLTOUnit);
  940. }
  941. MPM.addPass(
  942. BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
  943. }
  944. break;
  945. case Backend_EmitLL:
  946. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  947. break;
  948. case Backend_EmitAssembly:
  949. case Backend_EmitMCNull:
  950. case Backend_EmitObj:
  951. NeedCodeGen = true;
  952. CodeGenPasses.add(
  953. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  954. if (!CodeGenOpts.SplitDwarfFile.empty()) {
  955. DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
  956. if (!DwoOS)
  957. return;
  958. }
  959. if (!AddEmitPasses(CodeGenPasses, Action, *OS,
  960. DwoOS ? &DwoOS->os() : nullptr))
  961. // FIXME: Should we handle this error differently?
  962. return;
  963. break;
  964. }
  965. // Before executing passes, print the final values of the LLVM options.
  966. cl::PrintOptionValues();
  967. // Now that we have all of the passes ready, run them.
  968. {
  969. PrettyStackTraceString CrashInfo("Optimizer");
  970. MPM.run(*TheModule, MAM);
  971. }
  972. // Now if needed, run the legacy PM for codegen.
  973. if (NeedCodeGen) {
  974. PrettyStackTraceString CrashInfo("Code generation");
  975. CodeGenPasses.run(*TheModule);
  976. }
  977. if (ThinLinkOS)
  978. ThinLinkOS->keep();
  979. if (DwoOS)
  980. DwoOS->keep();
  981. }
  982. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  983. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  984. if (!BMsOrErr)
  985. return BMsOrErr.takeError();
  986. // The bitcode file may contain multiple modules, we want the one that is
  987. // marked as being the ThinLTO module.
  988. if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
  989. return *Bm;
  990. return make_error<StringError>("Could not find module summary",
  991. inconvertibleErrorCode());
  992. }
  993. BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
  994. for (BitcodeModule &BM : BMs) {
  995. Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
  996. if (LTOInfo && LTOInfo->IsThinLTO)
  997. return &BM;
  998. }
  999. return nullptr;
  1000. }
  1001. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  1002. const HeaderSearchOptions &HeaderOpts,
  1003. const CodeGenOptions &CGOpts,
  1004. const clang::TargetOptions &TOpts,
  1005. const LangOptions &LOpts,
  1006. std::unique_ptr<raw_pwrite_stream> OS,
  1007. std::string SampleProfile,
  1008. std::string ProfileRemapping,
  1009. BackendAction Action) {
  1010. StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
  1011. ModuleToDefinedGVSummaries;
  1012. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  1013. setCommandLineOpts(CGOpts);
  1014. // We can simply import the values mentioned in the combined index, since
  1015. // we should only invoke this using the individual indexes written out
  1016. // via a WriteIndexesThinBackend.
  1017. FunctionImporter::ImportMapTy ImportList;
  1018. for (auto &GlobalList : *CombinedIndex) {
  1019. // Ignore entries for undefined references.
  1020. if (GlobalList.second.SummaryList.empty())
  1021. continue;
  1022. auto GUID = GlobalList.first;
  1023. for (auto &Summary : GlobalList.second.SummaryList) {
  1024. // Skip the summaries for the importing module. These are included to
  1025. // e.g. record required linkage changes.
  1026. if (Summary->modulePath() == M->getModuleIdentifier())
  1027. continue;
  1028. // Add an entry to provoke importing by thinBackend.
  1029. ImportList[Summary->modulePath()].insert(GUID);
  1030. }
  1031. }
  1032. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  1033. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  1034. for (auto &I : ImportList) {
  1035. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  1036. llvm::MemoryBuffer::getFile(I.first());
  1037. if (!MBOrErr) {
  1038. errs() << "Error loading imported file '" << I.first()
  1039. << "': " << MBOrErr.getError().message() << "\n";
  1040. return;
  1041. }
  1042. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  1043. if (!BMOrErr) {
  1044. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  1045. errs() << "Error loading imported file '" << I.first()
  1046. << "': " << EIB.message() << '\n';
  1047. });
  1048. return;
  1049. }
  1050. ModuleMap.insert({I.first(), *BMOrErr});
  1051. OwnedImports.push_back(std::move(*MBOrErr));
  1052. }
  1053. auto AddStream = [&](size_t Task) {
  1054. return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
  1055. };
  1056. lto::Config Conf;
  1057. if (CGOpts.SaveTempsFilePrefix != "") {
  1058. if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
  1059. /* UseInputModulePath */ false)) {
  1060. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1061. errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
  1062. << '\n';
  1063. });
  1064. }
  1065. }
  1066. Conf.CPU = TOpts.CPU;
  1067. Conf.CodeModel = getCodeModel(CGOpts);
  1068. Conf.MAttrs = TOpts.Features;
  1069. Conf.RelocModel = CGOpts.RelocationModel;
  1070. Conf.CGOptLevel = getCGOptLevel(CGOpts);
  1071. initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
  1072. Conf.SampleProfile = std::move(SampleProfile);
  1073. Conf.ProfileRemapping = std::move(ProfileRemapping);
  1074. Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
  1075. Conf.DebugPassManager = CGOpts.DebugPassManager;
  1076. Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
  1077. Conf.RemarksFilename = CGOpts.OptRecordFile;
  1078. Conf.DwoPath = CGOpts.SplitDwarfFile;
  1079. switch (Action) {
  1080. case Backend_EmitNothing:
  1081. Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
  1082. return false;
  1083. };
  1084. break;
  1085. case Backend_EmitLL:
  1086. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1087. M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
  1088. return false;
  1089. };
  1090. break;
  1091. case Backend_EmitBC:
  1092. Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
  1093. WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
  1094. return false;
  1095. };
  1096. break;
  1097. default:
  1098. Conf.CGFileType = getCodeGenFileType(Action);
  1099. break;
  1100. }
  1101. if (Error E = thinBackend(
  1102. Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
  1103. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  1104. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  1105. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  1106. });
  1107. }
  1108. }
  1109. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  1110. const HeaderSearchOptions &HeaderOpts,
  1111. const CodeGenOptions &CGOpts,
  1112. const clang::TargetOptions &TOpts,
  1113. const LangOptions &LOpts,
  1114. const llvm::DataLayout &TDesc, Module *M,
  1115. BackendAction Action,
  1116. std::unique_ptr<raw_pwrite_stream> OS) {
  1117. std::unique_ptr<llvm::Module> EmptyModule;
  1118. if (!CGOpts.ThinLTOIndexFile.empty()) {
  1119. // If we are performing a ThinLTO importing compile, load the function index
  1120. // into memory and pass it into runThinLTOBackend, which will run the
  1121. // function importer and invoke LTO passes.
  1122. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  1123. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
  1124. /*IgnoreEmptyThinLTOIndexFile*/true);
  1125. if (!IndexOrErr) {
  1126. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  1127. "Error loading index file '" +
  1128. CGOpts.ThinLTOIndexFile + "': ");
  1129. return;
  1130. }
  1131. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  1132. // A null CombinedIndex means we should skip ThinLTO compilation
  1133. // (LLVM will optionally ignore empty index files, returning null instead
  1134. // of an error).
  1135. if (CombinedIndex) {
  1136. if (!CombinedIndex->skipModuleByDistributedBackend()) {
  1137. runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
  1138. LOpts, std::move(OS), CGOpts.SampleProfileFile,
  1139. CGOpts.ProfileRemappingFile, Action);
  1140. return;
  1141. }
  1142. // Distributed indexing detected that nothing from the module is needed
  1143. // for the final linking. So we can skip the compilation. We sill need to
  1144. // output an empty object file to make sure that a linker does not fail
  1145. // trying to read it. Also for some features, like CFI, we must skip
  1146. // the compilation as CombinedIndex does not contain all required
  1147. // information.
  1148. EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
  1149. EmptyModule->setTargetTriple(M->getTargetTriple());
  1150. M = EmptyModule.get();
  1151. }
  1152. }
  1153. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  1154. if (CGOpts.ExperimentalNewPassManager)
  1155. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  1156. else
  1157. AsmHelper.EmitAssembly(Action, std::move(OS));
  1158. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  1159. // DataLayout.
  1160. if (AsmHelper.TM) {
  1161. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  1162. if (DLDesc != TDesc.getStringRepresentation()) {
  1163. unsigned DiagID = Diags.getCustomDiagID(
  1164. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  1165. "expected target description '%1'");
  1166. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  1167. }
  1168. }
  1169. }
  1170. static const char* getSectionNameForBitcode(const Triple &T) {
  1171. switch (T.getObjectFormat()) {
  1172. case Triple::MachO:
  1173. return "__LLVM,__bitcode";
  1174. case Triple::COFF:
  1175. case Triple::ELF:
  1176. case Triple::Wasm:
  1177. case Triple::UnknownObjectFormat:
  1178. return ".llvmbc";
  1179. }
  1180. llvm_unreachable("Unimplemented ObjectFormatType");
  1181. }
  1182. static const char* getSectionNameForCommandline(const Triple &T) {
  1183. switch (T.getObjectFormat()) {
  1184. case Triple::MachO:
  1185. return "__LLVM,__cmdline";
  1186. case Triple::COFF:
  1187. case Triple::ELF:
  1188. case Triple::Wasm:
  1189. case Triple::UnknownObjectFormat:
  1190. return ".llvmcmd";
  1191. }
  1192. llvm_unreachable("Unimplemented ObjectFormatType");
  1193. }
  1194. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  1195. // __LLVM,__bitcode section.
  1196. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  1197. llvm::MemoryBufferRef Buf) {
  1198. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  1199. return;
  1200. // Save llvm.compiler.used and remote it.
  1201. SmallVector<Constant*, 2> UsedArray;
  1202. SmallPtrSet<GlobalValue*, 4> UsedGlobals;
  1203. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  1204. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  1205. for (auto *GV : UsedGlobals) {
  1206. if (GV->getName() != "llvm.embedded.module" &&
  1207. GV->getName() != "llvm.cmdline")
  1208. UsedArray.push_back(
  1209. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1210. }
  1211. if (Used)
  1212. Used->eraseFromParent();
  1213. // Embed the bitcode for the llvm module.
  1214. std::string Data;
  1215. ArrayRef<uint8_t> ModuleData;
  1216. Triple T(M->getTargetTriple());
  1217. // Create a constant that contains the bitcode.
  1218. // In case of embedding a marker, ignore the input Buf and use the empty
  1219. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  1220. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  1221. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  1222. (const unsigned char *)Buf.getBufferEnd())) {
  1223. // If the input is LLVM Assembly, bitcode is produced by serializing
  1224. // the module. Use-lists order need to be perserved in this case.
  1225. llvm::raw_string_ostream OS(Data);
  1226. llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
  1227. ModuleData =
  1228. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  1229. } else
  1230. // If the input is LLVM bitcode, write the input byte stream directly.
  1231. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  1232. Buf.getBufferSize());
  1233. }
  1234. llvm::Constant *ModuleConstant =
  1235. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  1236. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1237. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  1238. ModuleConstant);
  1239. GV->setSection(getSectionNameForBitcode(T));
  1240. UsedArray.push_back(
  1241. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1242. if (llvm::GlobalVariable *Old =
  1243. M->getGlobalVariable("llvm.embedded.module", true)) {
  1244. assert(Old->hasOneUse() &&
  1245. "llvm.embedded.module can only be used once in llvm.compiler.used");
  1246. GV->takeName(Old);
  1247. Old->eraseFromParent();
  1248. } else {
  1249. GV->setName("llvm.embedded.module");
  1250. }
  1251. // Skip if only bitcode needs to be embedded.
  1252. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  1253. // Embed command-line options.
  1254. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  1255. CGOpts.CmdArgs.size());
  1256. llvm::Constant *CmdConstant =
  1257. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  1258. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  1259. llvm::GlobalValue::PrivateLinkage,
  1260. CmdConstant);
  1261. GV->setSection(getSectionNameForCommandline(T));
  1262. UsedArray.push_back(
  1263. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  1264. if (llvm::GlobalVariable *Old =
  1265. M->getGlobalVariable("llvm.cmdline", true)) {
  1266. assert(Old->hasOneUse() &&
  1267. "llvm.cmdline can only be used once in llvm.compiler.used");
  1268. GV->takeName(Old);
  1269. Old->eraseFromParent();
  1270. } else {
  1271. GV->setName("llvm.cmdline");
  1272. }
  1273. }
  1274. if (UsedArray.empty())
  1275. return;
  1276. // Recreate llvm.compiler.used.
  1277. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  1278. auto *NewUsed = new GlobalVariable(
  1279. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1280. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1281. NewUsed->setSection("llvm.metadata");
  1282. }