BackendUtil.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/CodeGen/BackendUtil.h"
  10. #include "clang/Basic/Diagnostic.h"
  11. #include "clang/Basic/LangOptions.h"
  12. #include "clang/Basic/TargetOptions.h"
  13. #include "clang/Frontend/CodeGenOptions.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/Utils.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/StringSwitch.h"
  18. #include "llvm/Analysis/TargetLibraryInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Bitcode/BitcodeWriterPass.h"
  21. #include "llvm/CodeGen/RegAllocRegistry.h"
  22. #include "llvm/CodeGen/SchedulerRegistry.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/ModuleSummaryIndex.h"
  25. #include "llvm/IR/IRPrintingPasses.h"
  26. #include "llvm/IR/LegacyPassManager.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/Verifier.h"
  29. #include "llvm/MC/SubtargetFeature.h"
  30. #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/PrettyStackTrace.h"
  33. #include "llvm/Support/TargetRegistry.h"
  34. #include "llvm/Support/Timer.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetOptions.h"
  38. #include "llvm/Target/TargetSubtargetInfo.h"
  39. #include "llvm/Transforms/IPO.h"
  40. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  41. #include "llvm/Transforms/Instrumentation.h"
  42. #include "llvm/Transforms/ObjCARC.h"
  43. #include "llvm/Transforms/Scalar.h"
  44. #include "llvm/Transforms/Scalar/GVN.h"
  45. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  46. #include <memory>
  47. using namespace clang;
  48. using namespace llvm;
  49. namespace {
  50. class EmitAssemblyHelper {
  51. DiagnosticsEngine &Diags;
  52. const CodeGenOptions &CodeGenOpts;
  53. const clang::TargetOptions &TargetOpts;
  54. const LangOptions &LangOpts;
  55. Module *TheModule;
  56. Timer CodeGenerationTime;
  57. mutable legacy::PassManager *CodeGenPasses;
  58. mutable legacy::PassManager *PerModulePasses;
  59. mutable legacy::FunctionPassManager *PerFunctionPasses;
  60. private:
  61. TargetIRAnalysis getTargetIRAnalysis() const {
  62. if (TM)
  63. return TM->getTargetIRAnalysis();
  64. return TargetIRAnalysis();
  65. }
  66. legacy::PassManager *getCodeGenPasses() const {
  67. if (!CodeGenPasses) {
  68. CodeGenPasses = new legacy::PassManager();
  69. CodeGenPasses->add(
  70. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  71. }
  72. return CodeGenPasses;
  73. }
  74. legacy::PassManager *getPerModulePasses() const {
  75. if (!PerModulePasses) {
  76. PerModulePasses = new legacy::PassManager();
  77. PerModulePasses->add(
  78. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  79. }
  80. return PerModulePasses;
  81. }
  82. legacy::FunctionPassManager *getPerFunctionPasses() const {
  83. if (!PerFunctionPasses) {
  84. PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
  85. PerFunctionPasses->add(
  86. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  87. }
  88. return PerFunctionPasses;
  89. }
  90. /// Set LLVM command line options passed through -backend-option.
  91. void setCommandLineOpts();
  92. void CreatePasses(ModuleSummaryIndex *ModuleSummary);
  93. /// Generates the TargetMachine.
  94. /// Returns Null 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. TargetMachine *CreateTargetMachine(bool MustCreateTM);
  102. /// Add passes necessary to emit assembly or LLVM IR.
  103. ///
  104. /// \return True on success.
  105. bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
  106. public:
  107. EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
  108. const clang::TargetOptions &TOpts,
  109. const LangOptions &LOpts, Module *M)
  110. : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
  111. TheModule(M), CodeGenerationTime("Code Generation Time"),
  112. CodeGenPasses(nullptr), PerModulePasses(nullptr),
  113. PerFunctionPasses(nullptr) {}
  114. ~EmitAssemblyHelper() {
  115. delete CodeGenPasses;
  116. delete PerModulePasses;
  117. delete PerFunctionPasses;
  118. if (CodeGenOpts.DisableFree)
  119. BuryPointer(std::move(TM));
  120. }
  121. std::unique_ptr<TargetMachine> TM;
  122. void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
  123. };
  124. // We need this wrapper to access LangOpts and CGOpts from extension functions
  125. // that we add to the PassManagerBuilder.
  126. class PassManagerBuilderWrapper : public PassManagerBuilder {
  127. public:
  128. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  129. const LangOptions &LangOpts)
  130. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  131. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  132. const LangOptions &getLangOpts() const { return LangOpts; }
  133. private:
  134. const CodeGenOptions &CGOpts;
  135. const LangOptions &LangOpts;
  136. };
  137. }
  138. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  139. if (Builder.OptLevel > 0)
  140. PM.add(createObjCARCAPElimPass());
  141. }
  142. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  143. if (Builder.OptLevel > 0)
  144. PM.add(createObjCARCExpandPass());
  145. }
  146. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  147. if (Builder.OptLevel > 0)
  148. PM.add(createObjCARCOptPass());
  149. }
  150. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  151. legacy::PassManagerBase &PM) {
  152. PM.add(createAddDiscriminatorsPass());
  153. }
  154. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  155. legacy::PassManagerBase &PM) {
  156. PM.add(createBoundsCheckingPass());
  157. }
  158. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  159. legacy::PassManagerBase &PM) {
  160. const PassManagerBuilderWrapper &BuilderWrapper =
  161. static_cast<const PassManagerBuilderWrapper&>(Builder);
  162. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  163. SanitizerCoverageOptions Opts;
  164. Opts.CoverageType =
  165. static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
  166. Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
  167. Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
  168. Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
  169. Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
  170. Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
  171. PM.add(createSanitizerCoverageModulePass(Opts));
  172. }
  173. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  174. legacy::PassManagerBase &PM) {
  175. const PassManagerBuilderWrapper &BuilderWrapper =
  176. static_cast<const PassManagerBuilderWrapper&>(Builder);
  177. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  178. bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
  179. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover));
  180. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
  181. }
  182. static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
  183. legacy::PassManagerBase &PM) {
  184. PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true,
  185. /*Recover*/true));
  186. PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
  187. /*Recover*/true));
  188. }
  189. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  190. legacy::PassManagerBase &PM) {
  191. const PassManagerBuilderWrapper &BuilderWrapper =
  192. static_cast<const PassManagerBuilderWrapper&>(Builder);
  193. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  194. PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
  195. // MemorySanitizer inserts complex instrumentation that mostly follows
  196. // the logic of the original code, but operates on "shadow" values.
  197. // It can benefit from re-running some general purpose optimization passes.
  198. if (Builder.OptLevel > 0) {
  199. PM.add(createEarlyCSEPass());
  200. PM.add(createReassociatePass());
  201. PM.add(createLICMPass());
  202. PM.add(createGVNPass());
  203. PM.add(createInstructionCombiningPass());
  204. PM.add(createDeadStoreEliminationPass());
  205. }
  206. }
  207. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  208. legacy::PassManagerBase &PM) {
  209. PM.add(createThreadSanitizerPass());
  210. }
  211. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  212. legacy::PassManagerBase &PM) {
  213. const PassManagerBuilderWrapper &BuilderWrapper =
  214. static_cast<const PassManagerBuilderWrapper&>(Builder);
  215. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  216. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  217. }
  218. static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
  219. legacy::PassManagerBase &PM) {
  220. const PassManagerBuilderWrapper &BuilderWrapper =
  221. static_cast<const PassManagerBuilderWrapper&>(Builder);
  222. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  223. EfficiencySanitizerOptions Opts;
  224. if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
  225. Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
  226. PM.add(createEfficiencySanitizerPass(Opts));
  227. }
  228. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  229. const CodeGenOptions &CodeGenOpts) {
  230. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  231. if (!CodeGenOpts.SimplifyLibCalls)
  232. TLII->disableAllFunctions();
  233. else {
  234. // Disable individual libc/libm calls in TargetLibraryInfo.
  235. LibFunc::Func F;
  236. for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
  237. if (TLII->getLibFunc(FuncName, F))
  238. TLII->setUnavailable(F);
  239. }
  240. switch (CodeGenOpts.getVecLib()) {
  241. case CodeGenOptions::Accelerate:
  242. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  243. break;
  244. default:
  245. break;
  246. }
  247. return TLII;
  248. }
  249. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  250. legacy::PassManager *MPM) {
  251. llvm::SymbolRewriter::RewriteDescriptorList DL;
  252. llvm::SymbolRewriter::RewriteMapParser MapParser;
  253. for (const auto &MapFile : Opts.RewriteMapFiles)
  254. MapParser.parse(MapFile, &DL);
  255. MPM->add(createRewriteSymbolsPass(DL));
  256. }
  257. void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
  258. if (CodeGenOpts.DisableLLVMPasses)
  259. return;
  260. unsigned OptLevel = CodeGenOpts.OptimizationLevel;
  261. CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
  262. // Handle disabling of LLVM optimization, where we want to preserve the
  263. // internal module before any optimization.
  264. if (CodeGenOpts.DisableLLVMOpts) {
  265. OptLevel = 0;
  266. Inlining = CodeGenOpts.NoInlining;
  267. }
  268. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  269. // Figure out TargetLibraryInfo.
  270. Triple TargetTriple(TheModule->getTargetTriple());
  271. PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
  272. switch (Inlining) {
  273. case CodeGenOptions::NoInlining:
  274. break;
  275. case CodeGenOptions::NormalInlining: {
  276. PMBuilder.Inliner =
  277. createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
  278. break;
  279. }
  280. case CodeGenOptions::OnlyAlwaysInlining:
  281. // Respect always_inline.
  282. if (OptLevel == 0)
  283. // Do not insert lifetime intrinsics at -O0.
  284. PMBuilder.Inliner = createAlwaysInlinerPass(false);
  285. else
  286. PMBuilder.Inliner = createAlwaysInlinerPass();
  287. break;
  288. }
  289. PMBuilder.OptLevel = OptLevel;
  290. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  291. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  292. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  293. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  294. PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
  295. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  296. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  297. PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
  298. PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
  299. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  300. legacy::PassManager *MPM = getPerModulePasses();
  301. // If we are performing a ThinLTO importing compile, invoke the LTO
  302. // pipeline and pass down the in-memory module summary index.
  303. if (ModuleSummary) {
  304. PMBuilder.ModuleSummary = ModuleSummary;
  305. PMBuilder.populateThinLTOPassManager(*MPM);
  306. return;
  307. }
  308. // Add target-specific passes that need to run as early as possible.
  309. if (TM)
  310. PMBuilder.addExtension(
  311. PassManagerBuilder::EP_EarlyAsPossible,
  312. [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
  313. TM->addEarlyAsPossiblePasses(PM);
  314. });
  315. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  316. addAddDiscriminatorsPass);
  317. // In ObjC ARC mode, add the main ARC optimization passes.
  318. if (LangOpts.ObjCAutoRefCount) {
  319. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  320. addObjCARCExpandPass);
  321. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  322. addObjCARCAPElimPass);
  323. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  324. addObjCARCOptPass);
  325. }
  326. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  327. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  328. addBoundsCheckingPass);
  329. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  330. addBoundsCheckingPass);
  331. }
  332. if (CodeGenOpts.SanitizeCoverageType ||
  333. CodeGenOpts.SanitizeCoverageIndirectCalls ||
  334. CodeGenOpts.SanitizeCoverageTraceCmp) {
  335. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  336. addSanitizerCoveragePass);
  337. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  338. addSanitizerCoveragePass);
  339. }
  340. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  341. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  342. addAddressSanitizerPasses);
  343. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  344. addAddressSanitizerPasses);
  345. }
  346. if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
  347. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  348. addKernelAddressSanitizerPasses);
  349. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  350. addKernelAddressSanitizerPasses);
  351. }
  352. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  353. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  354. addMemorySanitizerPass);
  355. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  356. addMemorySanitizerPass);
  357. }
  358. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  359. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  360. addThreadSanitizerPass);
  361. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  362. addThreadSanitizerPass);
  363. }
  364. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  365. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  366. addDataFlowSanitizerPass);
  367. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  368. addDataFlowSanitizerPass);
  369. }
  370. if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
  371. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  372. addEfficiencySanitizerPass);
  373. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  374. addEfficiencySanitizerPass);
  375. }
  376. // Set up the per-function pass manager.
  377. legacy::FunctionPassManager *FPM = getPerFunctionPasses();
  378. if (CodeGenOpts.VerifyModule)
  379. FPM->add(createVerifierPass());
  380. PMBuilder.populateFunctionPassManager(*FPM);
  381. // Set up the per-module pass manager.
  382. if (!CodeGenOpts.RewriteMapFiles.empty())
  383. addSymbolRewriterPass(CodeGenOpts, MPM);
  384. if (!CodeGenOpts.DisableGCov &&
  385. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  386. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  387. // LLVM's -default-gcov-version flag is set to something invalid.
  388. GCOVOptions Options;
  389. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  390. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  391. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  392. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  393. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  394. Options.FunctionNamesInData =
  395. !CodeGenOpts.CoverageNoFunctionNamesInData;
  396. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  397. MPM->add(createGCOVProfilerPass(Options));
  398. if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
  399. MPM->add(createStripSymbolsPass(true));
  400. }
  401. if (CodeGenOpts.hasProfileClangInstr()) {
  402. InstrProfOptions Options;
  403. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  404. Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
  405. MPM->add(createInstrProfilingLegacyPass(Options));
  406. }
  407. if (CodeGenOpts.hasProfileIRInstr()) {
  408. if (!CodeGenOpts.InstrProfileOutput.empty())
  409. PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
  410. else
  411. PMBuilder.PGOInstrGen = "default.profraw";
  412. }
  413. if (CodeGenOpts.hasProfileIRUse())
  414. PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
  415. if (!CodeGenOpts.SampleProfileFile.empty())
  416. MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
  417. PMBuilder.populateModulePassManager(*MPM);
  418. }
  419. void EmitAssemblyHelper::setCommandLineOpts() {
  420. SmallVector<const char *, 16> BackendArgs;
  421. BackendArgs.push_back("clang"); // Fake program name.
  422. if (!CodeGenOpts.DebugPass.empty()) {
  423. BackendArgs.push_back("-debug-pass");
  424. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  425. }
  426. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  427. BackendArgs.push_back("-limit-float-precision");
  428. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  429. }
  430. for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
  431. BackendArgs.push_back(BackendOption.c_str());
  432. BackendArgs.push_back(nullptr);
  433. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  434. BackendArgs.data());
  435. }
  436. TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  437. // Create the TargetMachine for generating code.
  438. std::string Error;
  439. std::string Triple = TheModule->getTargetTriple();
  440. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  441. if (!TheTarget) {
  442. if (MustCreateTM)
  443. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  444. return nullptr;
  445. }
  446. unsigned CodeModel =
  447. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  448. .Case("small", llvm::CodeModel::Small)
  449. .Case("kernel", llvm::CodeModel::Kernel)
  450. .Case("medium", llvm::CodeModel::Medium)
  451. .Case("large", llvm::CodeModel::Large)
  452. .Case("default", llvm::CodeModel::Default)
  453. .Default(~0u);
  454. assert(CodeModel != ~0u && "invalid code model!");
  455. llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
  456. std::string FeaturesStr =
  457. llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
  458. // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
  459. llvm::Reloc::Model RM = llvm::Reloc::Default;
  460. if (CodeGenOpts.RelocationModel == "static") {
  461. RM = llvm::Reloc::Static;
  462. } else if (CodeGenOpts.RelocationModel == "pic") {
  463. RM = llvm::Reloc::PIC_;
  464. } else {
  465. assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
  466. "Invalid PIC model!");
  467. RM = llvm::Reloc::DynamicNoPIC;
  468. }
  469. CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
  470. switch (CodeGenOpts.OptimizationLevel) {
  471. default: break;
  472. case 0: OptLevel = CodeGenOpt::None; break;
  473. case 3: OptLevel = CodeGenOpt::Aggressive; break;
  474. }
  475. llvm::TargetOptions Options;
  476. if (!TargetOpts.Reciprocals.empty())
  477. Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
  478. Options.ThreadModel =
  479. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  480. .Case("posix", llvm::ThreadModel::POSIX)
  481. .Case("single", llvm::ThreadModel::Single);
  482. // Set float ABI type.
  483. assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
  484. CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
  485. "Invalid Floating Point ABI!");
  486. Options.FloatABIType =
  487. llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
  488. .Case("soft", llvm::FloatABI::Soft)
  489. .Case("softfp", llvm::FloatABI::Soft)
  490. .Case("hard", llvm::FloatABI::Hard)
  491. .Default(llvm::FloatABI::Default);
  492. // Set FP fusion mode.
  493. switch (CodeGenOpts.getFPContractMode()) {
  494. case CodeGenOptions::FPC_Off:
  495. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  496. break;
  497. case CodeGenOptions::FPC_On:
  498. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  499. break;
  500. case CodeGenOptions::FPC_Fast:
  501. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  502. break;
  503. }
  504. Options.UseInitArray = CodeGenOpts.UseInitArray;
  505. Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
  506. Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
  507. // Set EABI version.
  508. Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
  509. .Case("4", llvm::EABI::EABI4)
  510. .Case("5", llvm::EABI::EABI5)
  511. .Case("gnu", llvm::EABI::GNU)
  512. .Default(llvm::EABI::Default);
  513. Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
  514. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  515. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  516. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  517. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  518. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  519. Options.FunctionSections = CodeGenOpts.FunctionSections;
  520. Options.DataSections = CodeGenOpts.DataSections;
  521. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  522. Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
  523. Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
  524. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  525. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  526. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  527. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  528. Options.MCOptions.MCIncrementalLinkerCompatible =
  529. CodeGenOpts.IncrementalLinkerCompatible;
  530. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  531. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  532. Options.MCOptions.ABIName = TargetOpts.ABI;
  533. TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
  534. FeaturesStr, Options,
  535. RM, CM, OptLevel);
  536. return TM;
  537. }
  538. bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
  539. raw_pwrite_stream &OS) {
  540. // Create the code generator passes.
  541. legacy::PassManager *PM = getCodeGenPasses();
  542. // Add LibraryInfo.
  543. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  544. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  545. createTLII(TargetTriple, CodeGenOpts));
  546. PM->add(new TargetLibraryInfoWrapperPass(*TLII));
  547. // Normal mode, emit a .s or .o file by running the code generator. Note,
  548. // this also adds codegenerator level optimization passes.
  549. TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
  550. if (Action == Backend_EmitObj)
  551. CGFT = TargetMachine::CGFT_ObjectFile;
  552. else if (Action == Backend_EmitMCNull)
  553. CGFT = TargetMachine::CGFT_Null;
  554. else
  555. assert(Action == Backend_EmitAssembly && "Invalid action!");
  556. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  557. // "codegen" passes so that it isn't run multiple times when there is
  558. // inlining happening.
  559. if (CodeGenOpts.OptimizationLevel > 0)
  560. PM->add(createObjCARCContractPass());
  561. if (TM->addPassesToEmitFile(*PM, OS, CGFT,
  562. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  563. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  564. return false;
  565. }
  566. return true;
  567. }
  568. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  569. raw_pwrite_stream *OS) {
  570. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  571. setCommandLineOpts();
  572. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  573. Action != Backend_EmitBC &&
  574. Action != Backend_EmitLL);
  575. if (!TM)
  576. TM.reset(CreateTargetMachine(UsesCodeGen));
  577. if (UsesCodeGen && !TM)
  578. return;
  579. if (TM)
  580. TheModule->setDataLayout(TM->createDataLayout());
  581. // If we are performing a ThinLTO importing compile, load the function
  582. // index into memory and pass it into CreatePasses, which will add it
  583. // to the PassManagerBuilder and invoke LTO passes.
  584. std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
  585. if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
  586. ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
  587. llvm::getModuleSummaryIndexForFile(
  588. CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
  589. TheModule->getContext().diagnose(DI);
  590. });
  591. if (std::error_code EC = IndexOrErr.getError()) {
  592. std::string Error = EC.message();
  593. errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
  594. << "': " << Error << "\n";
  595. return;
  596. }
  597. ModuleSummary = std::move(IndexOrErr.get());
  598. assert(ModuleSummary && "Expected non-empty module summary index");
  599. }
  600. CreatePasses(ModuleSummary.get());
  601. switch (Action) {
  602. case Backend_EmitNothing:
  603. break;
  604. case Backend_EmitBC:
  605. getPerModulePasses()->add(createBitcodeWriterPass(
  606. *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
  607. CodeGenOpts.EmitSummaryIndex));
  608. break;
  609. case Backend_EmitLL:
  610. getPerModulePasses()->add(
  611. createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
  612. break;
  613. default:
  614. if (!AddEmitPasses(Action, *OS))
  615. return;
  616. }
  617. // Before executing passes, print the final values of the LLVM options.
  618. cl::PrintOptionValues();
  619. // Run passes. For now we do all passes at once, but eventually we
  620. // would like to have the option of streaming code generation.
  621. if (PerFunctionPasses) {
  622. PrettyStackTraceString CrashInfo("Per-function optimization");
  623. PerFunctionPasses->doInitialization();
  624. for (Function &F : *TheModule)
  625. if (!F.isDeclaration())
  626. PerFunctionPasses->run(F);
  627. PerFunctionPasses->doFinalization();
  628. }
  629. if (PerModulePasses) {
  630. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  631. PerModulePasses->run(*TheModule);
  632. }
  633. if (CodeGenPasses) {
  634. PrettyStackTraceString CrashInfo("Code generation");
  635. CodeGenPasses->run(*TheModule);
  636. }
  637. }
  638. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  639. const CodeGenOptions &CGOpts,
  640. const clang::TargetOptions &TOpts,
  641. const LangOptions &LOpts, const llvm::DataLayout &TDesc,
  642. Module *M, BackendAction Action,
  643. raw_pwrite_stream *OS) {
  644. EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
  645. AsmHelper.EmitAssembly(Action, OS);
  646. // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
  647. // DataLayout.
  648. if (AsmHelper.TM) {
  649. std::string DLDesc = M->getDataLayout().getStringRepresentation();
  650. if (DLDesc != TDesc.getStringRepresentation()) {
  651. unsigned DiagID = Diags.getCustomDiagID(
  652. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  653. "expected target description '%1'");
  654. Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
  655. }
  656. }
  657. }