BackendUtil.cpp 56 KB

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