BackendUtil.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/CodeGen/BackendUtil.h"
  10. #include "clang/Basic/Diagnostic.h"
  11. #include "clang/Basic/LangOptions.h"
  12. #include "clang/Basic/TargetOptions.h"
  13. #include "clang/Frontend/CodeGenOptions.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/Utils.h"
  16. #include "clang/Lex/HeaderSearchOptions.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringSwitch.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Analysis/TargetLibraryInfo.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Bitcode/BitcodeReader.h"
  24. #include "llvm/Bitcode/BitcodeWriter.h"
  25. #include "llvm/Bitcode/BitcodeWriterPass.h"
  26. #include "llvm/CodeGen/RegAllocRegistry.h"
  27. #include "llvm/CodeGen/SchedulerRegistry.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/Object/ModuleSummaryIndexObjectFile.h"
  38. #include "llvm/Passes/PassBuilder.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/MemoryBuffer.h"
  41. #include "llvm/Support/PrettyStackTrace.h"
  42. #include "llvm/Support/TargetRegistry.h"
  43. #include "llvm/Support/Timer.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. #include "llvm/Target/TargetOptions.h"
  47. #include "llvm/Target/TargetSubtargetInfo.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/Instrumentation.h"
  53. #include "llvm/Transforms/ObjCARC.h"
  54. #include "llvm/Transforms/Scalar.h"
  55. #include "llvm/Transforms/Scalar/GVN.h"
  56. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  57. #include <memory>
  58. using namespace clang;
  59. using namespace llvm;
  60. namespace {
  61. // Default filename used for profile generation.
  62. static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
  63. class EmitAssemblyHelper {
  64. DiagnosticsEngine &Diags;
  65. const HeaderSearchOptions &HSOpts;
  66. const CodeGenOptions &CodeGenOpts;
  67. const clang::TargetOptions &TargetOpts;
  68. const LangOptions &LangOpts;
  69. Module *TheModule;
  70. Timer CodeGenerationTime;
  71. std::unique_ptr<raw_pwrite_stream> OS;
  72. TargetIRAnalysis getTargetIRAnalysis() const {
  73. if (TM)
  74. return TM->getTargetIRAnalysis();
  75. return TargetIRAnalysis();
  76. }
  77. /// Set LLVM command line options passed through -backend-option.
  78. void setCommandLineOpts();
  79. void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
  80. /// Generates the TargetMachine.
  81. /// Leaves TM unchanged if it is unable to create the target machine.
  82. /// Some of our clang tests specify triples which are not built
  83. /// into clang. This is okay because these tests check the generated
  84. /// IR, and they require DataLayout which depends on the triple.
  85. /// In this case, we allow this method to fail and not report an error.
  86. /// When MustCreateTM is used, we print an error if we are unable to load
  87. /// the requested target.
  88. void CreateTargetMachine(bool MustCreateTM);
  89. /// Add passes necessary to emit assembly or LLVM IR.
  90. ///
  91. /// \return True on success.
  92. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
  93. raw_pwrite_stream &OS);
  94. public:
  95. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  96. const HeaderSearchOptions &HeaderSearchOpts,
  97. const CodeGenOptions &CGOpts,
  98. const clang::TargetOptions &TOpts,
  99. const LangOptions &LOpts, Module *M)
  100. : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
  101. TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
  102. CodeGenerationTime("codegen", "Code Generation Time") {}
  103. ~EmitAssemblyHelper() {
  104. if (CodeGenOpts.DisableFree)
  105. BuryPointer(std::move(TM));
  106. }
  107. std::unique_ptr<TargetMachine> TM;
  108. void EmitAssembly(BackendAction Action,
  109. std::unique_ptr<raw_pwrite_stream> OS);
  110. void EmitAssemblyWithNewPassManager(BackendAction Action,
  111. std::unique_ptr<raw_pwrite_stream> OS);
  112. };
  113. // We need this wrapper to access LangOpts and CGOpts from extension functions
  114. // that we add to the PassManagerBuilder.
  115. class PassManagerBuilderWrapper : public PassManagerBuilder {
  116. public:
  117. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  118. const LangOptions &LangOpts)
  119. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  120. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  121. const LangOptions &getLangOpts() const { return LangOpts; }
  122. private:
  123. const CodeGenOptions &CGOpts;
  124. const LangOptions &LangOpts;
  125. };
  126. }
  127. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  128. if (Builder.OptLevel > 0)
  129. PM.add(createObjCARCAPElimPass());
  130. }
  131. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  132. if (Builder.OptLevel > 0)
  133. PM.add(createObjCARCExpandPass());
  134. }
  135. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  136. if (Builder.OptLevel > 0)
  137. PM.add(createObjCARCOptPass());
  138. }
  139. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  140. legacy::PassManagerBase &PM) {
  141. PM.add(createAddDiscriminatorsPass());
  142. }
  143. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  144. legacy::PassManagerBase &PM) {
  145. PM.add(createBoundsCheckingPass());
  146. }
  147. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  148. legacy::PassManagerBase &PM) {
  149. const PassManagerBuilderWrapper &BuilderWrapper =
  150. static_cast<const PassManagerBuilderWrapper&>(Builder);
  151. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  152. SanitizerCoverageOptions Opts;
  153. Opts.CoverageType =
  154. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  155. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  156. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  157. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  158. Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
  159. Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
  160. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  161. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  162. Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
  163. PM.add(createSanitizerCoverageModulePass(Opts));
  164. }
  165. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  166. legacy::PassManagerBase &PM) {
  167. const PassManagerBuilderWrapper &BuilderWrapper =
  168. static_cast<const PassManagerBuilderWrapper&>(Builder);
  169. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  170. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  171. bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
  172. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
  173. UseAfterScope));
  174. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
  175. }
  176. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  177. legacy::PassManagerBase &PM) {
  178. PM.add(createAddressSanitizerFunctionPass(
  179. /*CompileKernel*/ true,
  180. /*Recover*/ true, /*UseAfterScope*/ false));
  181. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
  182. /*Recover*/true));
  183. }
  184. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  185. legacy::PassManagerBase &PM) {
  186. const PassManagerBuilderWrapper &BuilderWrapper =
  187. static_cast<const PassManagerBuilderWrapper&>(Builder);
  188. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  189. int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
  190. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
  191. PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
  192. // MemorySanitizer inserts complex instrumentation that mostly follows
  193. // the logic of the original code, but operates on "shadow" values.
  194. // It can benefit from re-running some general purpose optimization passes.
  195. if (Builder.OptLevel > 0) {
  196. PM.add(createEarlyCSEPass());
  197. PM.add(createReassociatePass());
  198. PM.add(createLICMPass());
  199. PM.add(createGVNPass());
  200. PM.add(createInstructionCombiningPass());
  201. PM.add(createDeadStoreEliminationPass());
  202. }
  203. }
  204. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  205. legacy::PassManagerBase &PM) {
  206. PM.add(createThreadSanitizerPass());
  207. }
  208. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  209. legacy::PassManagerBase &PM) {
  210. const PassManagerBuilderWrapper &BuilderWrapper =
  211. static_cast<const PassManagerBuilderWrapper&>(Builder);
  212. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  213. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  214. }
  215. static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
  216. legacy::PassManagerBase &PM) {
  217. const PassManagerBuilderWrapper &BuilderWrapper =
  218. static_cast<const PassManagerBuilderWrapper&>(Builder);
  219. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  220. EfficiencySanitizerOptions Opts;
  221. if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
  222. Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
  223. else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
  224. Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
  225. PM.add(createEfficiencySanitizerPass(Opts));
  226. }
  227. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  228. const CodeGenOptions &CodeGenOpts) {
  229. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  230. if (!CodeGenOpts.SimplifyLibCalls)
  231. TLII->disableAllFunctions();
  232. else {
  233. // Disable individual libc/libm calls in TargetLibraryInfo.
  234. LibFunc F;
  235. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  236. if (TLII->getLibFunc(FuncName, F))
  237. TLII->setUnavailable(F);
  238. }
  239. switch (CodeGenOpts.getVecLib()) {
  240. case CodeGenOptions::Accelerate:
  241. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  242. break;
  243. case CodeGenOptions::SVML:
  244. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
  245. break;
  246. default:
  247. break;
  248. }
  249. return TLII;
  250. }
  251. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  252. legacy::PassManager *MPM) {
  253. llvm::SymbolRewriter::RewriteDescriptorList DL;
  254. llvm::SymbolRewriter::RewriteMapParser MapParser;
  255. for (const auto &MapFile : Opts.RewriteMapFiles)
  256. MapParser.parse(MapFile, &DL);
  257. MPM->add(createRewriteSymbolsPass(DL));
  258. }
  259. void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
  260. legacy::FunctionPassManager &FPM) {
  261. // Handle disabling of all LLVM passes, where we want to preserve the
  262. // internal module before any optimization.
  263. if (CodeGenOpts.DisableLLVMPasses)
  264. return;
  265. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  266. // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
  267. // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
  268. // are inserted before PMBuilder ones - they'd get the default-constructed
  269. // TLI with an unknown target otherwise.
  270. Triple TargetTriple(TheModule->getTargetTriple());
  271. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  272. createTLII(TargetTriple, CodeGenOpts));
  273. // At O0 and O1 we only run the always inliner which is more efficient. At
  274. // higher optimization levels we run the normal inliner.
  275. if (CodeGenOpts.OptimizationLevel <= 1) {
  276. bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
  277. !CodeGenOpts.DisableLifetimeMarkers);
  278. PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
  279. } else {
  280. // We do not want to inline hot callsites for SamplePGO module-summary build
  281. // because profile annotation will happen again in ThinLTO backend, and we
  282. // want the IR of the hot path to match the profile.
  283. PMBuilder.Inliner = createFunctionInliningPass(
  284. CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
  285. (!CodeGenOpts.SampleProfileFile.empty() &&
  286. CodeGenOpts.EmitSummaryIndex));
  287. }
  288. PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
  289. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  290. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  291. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  292. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  293. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  294. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  295. PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
  296. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  297. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  298. MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  299. if (TM)
  300. TM->adjustPassManager(PMBuilder);
  301. if (CodeGenOpts.DebugInfoForProfiling ||
  302. !CodeGenOpts.SampleProfileFile.empty())
  303. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  304. addAddDiscriminatorsPass);
  305. // In ObjC ARC mode, add the main ARC optimization passes.
  306. if (LangOpts.ObjCAutoRefCount) {
  307. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  308. addObjCARCExpandPass);
  309. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  310. addObjCARCAPElimPass);
  311. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  312. addObjCARCOptPass);
  313. }
  314. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  315. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  316. addBoundsCheckingPass);
  317. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  318. addBoundsCheckingPass);
  319. }
  320. if (CodeGenOpts.SanitizeCoverageType ||
  321. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  322. CodeGenOpts.SanitizeCoverageTraceCmp) {
  323. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  324. addSanitizerCoveragePass);
  325. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  326. addSanitizerCoveragePass);
  327. }
  328. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  329. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  330. addAddressSanitizerPasses);
  331. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  332. addAddressSanitizerPasses);
  333. }
  334. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  335. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  336. addKernelAddressSanitizerPasses);
  337. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  338. addKernelAddressSanitizerPasses);
  339. }
  340. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  341. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  342. addMemorySanitizerPass);
  343. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  344. addMemorySanitizerPass);
  345. }
  346. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  347. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  348. addThreadSanitizerPass);
  349. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  350. addThreadSanitizerPass);
  351. }
  352. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  353. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  354. addDataFlowSanitizerPass);
  355. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  356. addDataFlowSanitizerPass);
  357. }
  358. if (LangOpts.CoroutinesTS)
  359. addCoroutinePassesToExtensionPoints(PMBuilder);
  360. if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
  361. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  362. addEfficiencySanitizerPass);
  363. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  364. addEfficiencySanitizerPass);
  365. }
  366. // Set up the per-function pass manager.
  367. FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
  368. if (CodeGenOpts.VerifyModule)
  369. FPM.add(createVerifierPass());
  370. // Set up the per-module pass manager.
  371. if (!CodeGenOpts.RewriteMapFiles.empty())
  372. addSymbolRewriterPass(CodeGenOpts, &MPM);
  373. if (!CodeGenOpts.DisableGCov &&
  374. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  375. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  376. // LLVM's -default-gcov-version flag is set to something invalid.
  377. GCOVOptions Options;
  378. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  379. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  380. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  381. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  382. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  383. Options.FunctionNamesInData =
  384. !CodeGenOpts.CoverageNoFunctionNamesInData;
  385. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  386. MPM.add(createGCOVProfilerPass(Options));
  387. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  388. MPM.add(createStripSymbolsPass(true));
  389. }
  390. if (CodeGenOpts.hasProfileClangInstr()) {
  391. InstrProfOptions Options;
  392. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  393. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  394. MPM.add(createInstrProfilingLegacyPass(Options));
  395. }
  396. if (CodeGenOpts.hasProfileIRInstr()) {
  397. PMBuilder.EnablePGOInstrGen = true;
  398. if (!CodeGenOpts.InstrProfileOutput.empty())
  399. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  400. else
  401. PMBuilder.PGOInstrGen = DefaultProfileGenName;
  402. }
  403. if (CodeGenOpts.hasProfileIRUse())
  404. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  405. if (!CodeGenOpts.SampleProfileFile.empty())
  406. PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
  407. PMBuilder.populateFunctionPassManager(FPM);
  408. PMBuilder.populateModulePassManager(MPM);
  409. }
  410. void EmitAssemblyHelper::setCommandLineOpts() {
  411. SmallVector<const char *, 16> BackendArgs;
  412. BackendArgs.push_back("clang"); // Fake program name.
  413. if (!CodeGenOpts.DebugPass.empty()) {
  414. BackendArgs.push_back("-debug-pass");
  415. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  416. }
  417. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  418. BackendArgs.push_back("-limit-float-precision");
  419. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  420. }
  421. for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
  422. BackendArgs.push_back(BackendOption.c_str());
  423. BackendArgs.push_back(nullptr);
  424. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  425. BackendArgs.data());
  426. }
  427. void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  428. // Create the TargetMachine for generating code.
  429. std::string Error;
  430. std::string Triple = TheModule->getTargetTriple();
  431. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  432. if (!TheTarget) {
  433. if (MustCreateTM)
  434. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  435. return;
  436. }
  437. unsigned CodeModel =
  438. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  439. .Case("small", llvm::CodeModel::Small)
  440. .Case("kernel", llvm::CodeModel::Kernel)
  441. .Case("medium", llvm::CodeModel::Medium)
  442. .Case("large", llvm::CodeModel::Large)
  443. .Case("default", llvm::CodeModel::Default)
  444. .Default(~0u);
  445. assert(CodeModel != ~0u && "invalid code model!");
  446. llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
  447. std::string FeaturesStr =
  448. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  449. // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
  450. llvm::Optional<llvm::Reloc::Model> RM;
  451. RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
  452. .Case("static", llvm::Reloc::Static)
  453. .Case("pic", llvm::Reloc::PIC_)
  454. .Case("ropi", llvm::Reloc::ROPI)
  455. .Case("rwpi", llvm::Reloc::RWPI)
  456. .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
  457. .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
  458. assert(RM.hasValue() && "invalid PIC model!");
  459. CodeGenOpt::Level OptLevel;
  460. switch (CodeGenOpts.OptimizationLevel) {
  461. default:
  462. llvm_unreachable("Invalid optimization level!");
  463. case 0:
  464. OptLevel = CodeGenOpt::None;
  465. break;
  466. case 1:
  467. OptLevel = CodeGenOpt::Less;
  468. break;
  469. case 2:
  470. OptLevel = CodeGenOpt::Default;
  471. break; // O2/Os/Oz
  472. case 3:
  473. OptLevel = CodeGenOpt::Aggressive;
  474. break;
  475. }
  476. llvm::TargetOptions Options;
  477. Options.ThreadModel =
  478. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  479. .Case("posix", llvm::ThreadModel::POSIX)
  480. .Case("single", llvm::ThreadModel::Single);
  481. // Set float ABI type.
  482. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  483. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  484. "Invalid Floating Point ABI!");
  485. Options.FloatABIType =
  486. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  487. .Case("soft", llvm::FloatABI::Soft)
  488. .Case("softfp", llvm::FloatABI::Soft)
  489. .Case("hard", llvm::FloatABI::Hard)
  490. .Default(llvm::FloatABI::Default);
  491. // Set FP fusion mode.
  492. switch (LangOpts.getDefaultFPContractMode()) {
  493. case LangOptions::FPC_Off:
  494. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  495. break;
  496. case LangOptions::FPC_On:
  497. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  498. break;
  499. case LangOptions::FPC_Fast:
  500. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  501. break;
  502. }
  503. Options.UseInitArray = CodeGenOpts.UseInitArray;
  504. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  505. Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
  506. Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
  507. // Set EABI version.
  508. Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
  509. .Case("4", llvm::EABI::EABI4)
  510. .Case("5", llvm::EABI::EABI5)
  511. .Case("gnu", llvm::EABI::GNU)
  512. .Default(llvm::EABI::Default);
  513. if (LangOpts.SjLjExceptions)
  514. Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
  515. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  516. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  517. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  518. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  519. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  520. Options.FunctionSections = CodeGenOpts.FunctionSections;
  521. Options.DataSections = CodeGenOpts.DataSections;
  522. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  523. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  524. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  525. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  526. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  527. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  528. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  529. Options.MCOptions.MCIncrementalLinkerCompatible =
  530. CodeGenOpts.IncrementalLinkerCompatible;
  531. Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
  532. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  533. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  534. Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
  535. Options.MCOptions.ABIName = TargetOpts.ABI;
  536. for (const auto &Entry : HSOpts.UserEntries)
  537. if (!Entry.IsFramework &&
  538. (Entry.Group == frontend::IncludeDirGroup::Quoted ||
  539. Entry.Group == frontend::IncludeDirGroup::Angled ||
  540. Entry.Group == frontend::IncludeDirGroup::System))
  541. Options.MCOptions.IASSearchPaths.push_back(
  542. Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
  543. TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
  544. Options, RM, CM, OptLevel));
  545. }
  546. bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
  547. BackendAction Action,
  548. raw_pwrite_stream &OS) {
  549. // Add LibraryInfo.
  550. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  551. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  552. createTLII(TargetTriple, CodeGenOpts));
  553. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
  554. // Normal mode, emit a .s or .o file by running the code generator. Note,
  555. // this also adds codegenerator level optimization passes.
  556. TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
  557. if (Action == Backend_EmitObj)
  558. CGFT = TargetMachine::CGFT_ObjectFile;
  559. else if (Action == Backend_EmitMCNull)
  560. CGFT = TargetMachine::CGFT_Null;
  561. else
  562. assert(Action == Backend_EmitAssembly && "Invalid action!");
  563. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  564. // "codegen" passes so that it isn't run multiple times when there is
  565. // inlining happening.
  566. if (CodeGenOpts.OptimizationLevel > 0)
  567. CodeGenPasses.add(createObjCARCContractPass());
  568. if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
  569. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  570. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  571. return false;
  572. }
  573. return true;
  574. }
  575. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  576. std::unique_ptr<raw_pwrite_stream> OS) {
  577. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  578. setCommandLineOpts();
  579. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  580. Action != Backend_EmitBC &&
  581. Action != Backend_EmitLL);
  582. CreateTargetMachine(UsesCodeGen);
  583. if (UsesCodeGen && !TM)
  584. return;
  585. if (TM)
  586. TheModule->setDataLayout(TM->createDataLayout());
  587. legacy::PassManager PerModulePasses;
  588. PerModulePasses.add(
  589. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  590. legacy::FunctionPassManager PerFunctionPasses(TheModule);
  591. PerFunctionPasses.add(
  592. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  593. CreatePasses(PerModulePasses, PerFunctionPasses);
  594. legacy::PassManager CodeGenPasses;
  595. CodeGenPasses.add(
  596. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  597. std::unique_ptr<raw_fd_ostream> ThinLinkOS;
  598. switch (Action) {
  599. case Backend_EmitNothing:
  600. break;
  601. case Backend_EmitBC:
  602. if (CodeGenOpts.EmitSummaryIndex) {
  603. if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
  604. std::error_code EC;
  605. ThinLinkOS.reset(new llvm::raw_fd_ostream(
  606. CodeGenOpts.ThinLinkBitcodeFile, EC,
  607. llvm::sys::fs::F_None));
  608. if (EC) {
  609. Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
  610. << EC.message();
  611. return;
  612. }
  613. }
  614. PerModulePasses.add(
  615. createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
  616. }
  617. else
  618. PerModulePasses.add(
  619. createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
  620. break;
  621. case Backend_EmitLL:
  622. PerModulePasses.add(
  623. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  624. break;
  625. default:
  626. if (!AddEmitPasses(CodeGenPasses, Action, *OS))
  627. return;
  628. }
  629. // Before executing passes, print the final values of the LLVM options.
  630. cl::PrintOptionValues();
  631. // Run passes. For now we do all passes at once, but eventually we
  632. // would like to have the option of streaming code generation.
  633. {
  634. PrettyStackTraceString CrashInfo("Per-function optimization");
  635. PerFunctionPasses.doInitialization();
  636. for (Function &F : *TheModule)
  637. if (!F.isDeclaration())
  638. PerFunctionPasses.run(F);
  639. PerFunctionPasses.doFinalization();
  640. }
  641. {
  642. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  643. PerModulePasses.run(*TheModule);
  644. }
  645. {
  646. PrettyStackTraceString CrashInfo("Code generation");
  647. CodeGenPasses.run(*TheModule);
  648. }
  649. }
  650. static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
  651. switch (Opts.OptimizationLevel) {
  652. default:
  653. llvm_unreachable("Invalid optimization level!");
  654. case 1:
  655. return PassBuilder::O1;
  656. case 2:
  657. switch (Opts.OptimizeSize) {
  658. default:
  659. llvm_unreachable("Invalide optimization level for size!");
  660. case 0:
  661. return PassBuilder::O2;
  662. case 1:
  663. return PassBuilder::Os;
  664. case 2:
  665. return PassBuilder::Oz;
  666. }
  667. case 3:
  668. return PassBuilder::O3;
  669. }
  670. }
  671. /// A clean version of `EmitAssembly` that uses the new pass manager.
  672. ///
  673. /// Not all features are currently supported in this system, but where
  674. /// necessary it falls back to the legacy pass manager to at least provide
  675. /// basic functionality.
  676. ///
  677. /// This API is planned to have its functionality finished and then to replace
  678. /// `EmitAssembly` at some point in the future when the default switches.
  679. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
  680. BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
  681. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  682. setCommandLineOpts();
  683. // The new pass manager always makes a target machine available to passes
  684. // during construction.
  685. CreateTargetMachine(/*MustCreateTM*/ true);
  686. if (!TM)
  687. // This will already be diagnosed, just bail.
  688. return;
  689. TheModule->setDataLayout(TM->createDataLayout());
  690. PGOOptions PGOOpt;
  691. // -fprofile-generate.
  692. PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
  693. if (PGOOpt.RunProfileGen)
  694. PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
  695. DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
  696. // -fprofile-use.
  697. if (CodeGenOpts.hasProfileIRUse())
  698. PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
  699. // Only pass a PGO options struct if -fprofile-generate or
  700. // -fprofile-use were passed on the cmdline.
  701. PassBuilder PB(TM.get(),
  702. (PGOOpt.RunProfileGen ||
  703. !PGOOpt.ProfileUseFile.empty()) ?
  704. Optional<PGOOptions>(PGOOpt) : None);
  705. LoopAnalysisManager LAM;
  706. FunctionAnalysisManager FAM;
  707. CGSCCAnalysisManager CGAM;
  708. ModuleAnalysisManager MAM;
  709. // Register the AA manager first so that our version is the one used.
  710. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
  711. // Register all the basic analyses with the managers.
  712. PB.registerModuleAnalyses(MAM);
  713. PB.registerCGSCCAnalyses(CGAM);
  714. PB.registerFunctionAnalyses(FAM);
  715. PB.registerLoopAnalyses(LAM);
  716. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  717. ModulePassManager MPM;
  718. if (!CodeGenOpts.DisableLLVMPasses) {
  719. if (CodeGenOpts.OptimizationLevel == 0) {
  720. // Build a minimal pipeline based on the semantics required by Clang,
  721. // which is just that always inlining occurs.
  722. MPM.addPass(AlwaysInlinerPass());
  723. } else {
  724. // Otherwise, use the default pass pipeline. We also have to map our
  725. // optimization levels into one of the distinct levels used to configure
  726. // the pipeline.
  727. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
  728. MPM = PB.buildPerModuleDefaultPipeline(Level);
  729. }
  730. }
  731. // FIXME: We still use the legacy pass manager to do code generation. We
  732. // create that pass manager here and use it as needed below.
  733. legacy::PassManager CodeGenPasses;
  734. bool NeedCodeGen = false;
  735. // Append any output we need to the pass manager.
  736. switch (Action) {
  737. case Backend_EmitNothing:
  738. break;
  739. case Backend_EmitBC:
  740. MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
  741. CodeGenOpts.EmitSummaryIndex,
  742. CodeGenOpts.EmitSummaryIndex));
  743. break;
  744. case Backend_EmitLL:
  745. MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  746. break;
  747. case Backend_EmitAssembly:
  748. case Backend_EmitMCNull:
  749. case Backend_EmitObj:
  750. NeedCodeGen = true;
  751. CodeGenPasses.add(
  752. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  753. if (!AddEmitPasses(CodeGenPasses, Action, *OS))
  754. // FIXME: Should we handle this error differently?
  755. return;
  756. break;
  757. }
  758. // Before executing passes, print the final values of the LLVM options.
  759. cl::PrintOptionValues();
  760. // Now that we have all of the passes ready, run them.
  761. {
  762. PrettyStackTraceString CrashInfo("Optimizer");
  763. MPM.run(*TheModule, MAM);
  764. }
  765. // Now if needed, run the legacy PM for codegen.
  766. if (NeedCodeGen) {
  767. PrettyStackTraceString CrashInfo("Code generation");
  768. CodeGenPasses.run(*TheModule);
  769. }
  770. }
  771. Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
  772. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  773. if (!BMsOrErr)
  774. return BMsOrErr.takeError();
  775. // The bitcode file may contain multiple modules, we want the one with a
  776. // summary.
  777. for (BitcodeModule &BM : *BMsOrErr) {
  778. Expected<bool> HasSummary = BM.hasSummary();
  779. if (HasSummary && *HasSummary)
  780. return BM;
  781. }
  782. return make_error<StringError>("Could not find module summary",
  783. inconvertibleErrorCode());
  784. }
  785. static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
  786. std::unique_ptr<raw_pwrite_stream> OS,
  787. std::string SampleProfile) {
  788. StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
  789. ModuleToDefinedGVSummaries;
  790. CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
  791. // We can simply import the values mentioned in the combined index, since
  792. // we should only invoke this using the individual indexes written out
  793. // via a WriteIndexesThinBackend.
  794. FunctionImporter::ImportMapTy ImportList;
  795. for (auto &GlobalList : *CombinedIndex) {
  796. auto GUID = GlobalList.first;
  797. assert(GlobalList.second.size() == 1 &&
  798. "Expected individual combined index to have one summary per GUID");
  799. auto &Summary = GlobalList.second[0];
  800. // Skip the summaries for the importing module. These are included to
  801. // e.g. record required linkage changes.
  802. if (Summary->modulePath() == M->getModuleIdentifier())
  803. continue;
  804. // Doesn't matter what value we plug in to the map, just needs an entry
  805. // to provoke importing by thinBackend.
  806. ImportList[Summary->modulePath()][GUID] = 1;
  807. }
  808. std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
  809. MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
  810. for (auto &I : ImportList) {
  811. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  812. llvm::MemoryBuffer::getFile(I.first());
  813. if (!MBOrErr) {
  814. errs() << "Error loading imported file '" << I.first()
  815. << "': " << MBOrErr.getError().message() << "\n";
  816. return;
  817. }
  818. Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
  819. if (!BMOrErr) {
  820. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  821. errs() << "Error loading imported file '" << I.first()
  822. << "': " << EIB.message() << '\n';
  823. });
  824. return;
  825. }
  826. ModuleMap.insert({I.first(), *BMOrErr});
  827. OwnedImports.push_back(std::move(*MBOrErr));
  828. }
  829. auto AddStream = [&](size_t Task) {
  830. return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
  831. };
  832. lto::Config Conf;
  833. Conf.SampleProfile = std::move(SampleProfile);
  834. if (Error E = thinBackend(
  835. Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
  836. ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
  837. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  838. errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
  839. });
  840. }
  841. }
  842. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  843. const HeaderSearchOptions &HeaderOpts,
  844. const CodeGenOptions &CGOpts,
  845. const clang::TargetOptions &TOpts,
  846. const LangOptions &LOpts,
  847. const llvm::DataLayout &TDesc, Module *M,
  848. BackendAction Action,
  849. std::unique_ptr<raw_pwrite_stream> OS) {
  850. if (!CGOpts.ThinLTOIndexFile.empty()) {
  851. // If we are performing a ThinLTO importing compile, load the function index
  852. // into memory and pass it into runThinLTOBackend, which will run the
  853. // function importer and invoke LTO passes.
  854. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  855. llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
  856. if (!IndexOrErr) {
  857. logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
  858. "Error loading index file '" +
  859. CGOpts.ThinLTOIndexFile + "': ");
  860. return;
  861. }
  862. std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
  863. // A null CombinedIndex means we should skip ThinLTO compilation
  864. // (LLVM will optionally ignore empty index files, returning null instead
  865. // of an error).
  866. bool DoThinLTOBackend = CombinedIndex != nullptr;
  867. if (DoThinLTOBackend) {
  868. runThinLTOBackend(CombinedIndex.get(), M, std::move(OS),
  869. CGOpts.SampleProfileFile);
  870. return;
  871. }
  872. }
  873. EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
  874. if (CGOpts.ExperimentalNewPassManager)
  875. AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
  876. else
  877. AsmHelper.EmitAssembly(Action, std::move(OS));
  878. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  879. // DataLayout.
  880. if (AsmHelper.TM) {
  881. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  882. if (DLDesc != TDesc.getStringRepresentation()) {
  883. unsigned DiagID = Diags.getCustomDiagID(
  884. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  885. "expected target description '%1'");
  886. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  887. }
  888. }
  889. }
  890. static const char* getSectionNameForBitcode(const Triple &T) {
  891. switch (T.getObjectFormat()) {
  892. case Triple::MachO:
  893. return "__LLVM,__bitcode";
  894. case Triple::COFF:
  895. case Triple::ELF:
  896. case Triple::Wasm:
  897. case Triple::UnknownObjectFormat:
  898. return ".llvmbc";
  899. }
  900. llvm_unreachable("Unimplemented ObjectFormatType");
  901. }
  902. static const char* getSectionNameForCommandline(const Triple &T) {
  903. switch (T.getObjectFormat()) {
  904. case Triple::MachO:
  905. return "__LLVM,__cmdline";
  906. case Triple::COFF:
  907. case Triple::ELF:
  908. case Triple::Wasm:
  909. case Triple::UnknownObjectFormat:
  910. return ".llvmcmd";
  911. }
  912. llvm_unreachable("Unimplemented ObjectFormatType");
  913. }
  914. // With -fembed-bitcode, save a copy of the llvm IR as data in the
  915. // __LLVM,__bitcode section.
  916. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
  917. llvm::MemoryBufferRef Buf) {
  918. if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
  919. return;
  920. // Save llvm.compiler.used and remote it.
  921. SmallVector<Constant*, 2> UsedArray;
  922. SmallSet<GlobalValue*, 4> UsedGlobals;
  923. Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
  924. GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
  925. for (auto *GV : UsedGlobals) {
  926. if (GV->getName() != "llvm.embedded.module" &&
  927. GV->getName() != "llvm.cmdline")
  928. UsedArray.push_back(
  929. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  930. }
  931. if (Used)
  932. Used->eraseFromParent();
  933. // Embed the bitcode for the llvm module.
  934. std::string Data;
  935. ArrayRef<uint8_t> ModuleData;
  936. Triple T(M->getTargetTriple());
  937. // Create a constant that contains the bitcode.
  938. // In case of embedding a marker, ignore the input Buf and use the empty
  939. // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
  940. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
  941. if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
  942. (const unsigned char *)Buf.getBufferEnd())) {
  943. // If the input is LLVM Assembly, bitcode is produced by serializing
  944. // the module. Use-lists order need to be perserved in this case.
  945. llvm::raw_string_ostream OS(Data);
  946. llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
  947. ModuleData =
  948. ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
  949. } else
  950. // If the input is LLVM bitcode, write the input byte stream directly.
  951. ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
  952. Buf.getBufferSize());
  953. }
  954. llvm::Constant *ModuleConstant =
  955. llvm::ConstantDataArray::get(M->getContext(), ModuleData);
  956. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  957. *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
  958. ModuleConstant);
  959. GV->setSection(getSectionNameForBitcode(T));
  960. UsedArray.push_back(
  961. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  962. if (llvm::GlobalVariable *Old =
  963. M->getGlobalVariable("llvm.embedded.module", true)) {
  964. assert(Old->hasOneUse() &&
  965. "llvm.embedded.module can only be used once in llvm.compiler.used");
  966. GV->takeName(Old);
  967. Old->eraseFromParent();
  968. } else {
  969. GV->setName("llvm.embedded.module");
  970. }
  971. // Skip if only bitcode needs to be embedded.
  972. if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
  973. // Embed command-line options.
  974. ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
  975. CGOpts.CmdArgs.size());
  976. llvm::Constant *CmdConstant =
  977. llvm::ConstantDataArray::get(M->getContext(), CmdData);
  978. GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
  979. llvm::GlobalValue::PrivateLinkage,
  980. CmdConstant);
  981. GV->setSection(getSectionNameForCommandline(T));
  982. UsedArray.push_back(
  983. ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
  984. if (llvm::GlobalVariable *Old =
  985. M->getGlobalVariable("llvm.cmdline", true)) {
  986. assert(Old->hasOneUse() &&
  987. "llvm.cmdline can only be used once in llvm.compiler.used");
  988. GV->takeName(Old);
  989. Old->eraseFromParent();
  990. } else {
  991. GV->setName("llvm.cmdline");
  992. }
  993. }
  994. if (UsedArray.empty())
  995. return;
  996. // Recreate llvm.compiler.used.
  997. ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
  998. auto *NewUsed = new GlobalVariable(
  999. *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
  1000. llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
  1001. NewUsed->setSection("llvm.metadata");
  1002. }