BackendUtil.cpp 61 KB

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