BackendUtil.cpp 64 KB

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