BackendUtil.cpp 48 KB

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