BackendUtil.cpp 47 KB

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