BackendUtil.cpp 71 KB

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