BackendUtil.cpp 57 KB

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