BackendUtil.cpp 48 KB

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