BackendUtil.cpp 66 KB

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