BackendUtil.cpp 66 KB

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