BackendUtil.cpp 50 KB

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