BackendUtil.cpp 65 KB

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