BackendUtil.cpp 46 KB

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