BackendUtil.cpp 52 KB

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