BackendUtil.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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/StringSwitch.h"
  17. #include "llvm/Analysis/TargetLibraryInfo.h"
  18. #include "llvm/Analysis/TargetTransformInfo.h"
  19. #include "llvm/Bitcode/BitcodeWriterPass.h"
  20. #include "llvm/CodeGen/RegAllocRegistry.h"
  21. #include "llvm/CodeGen/SchedulerRegistry.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/IRPrintingPasses.h"
  24. #include "llvm/IR/LegacyPassManager.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/Verifier.h"
  27. #include "llvm/MC/SubtargetFeature.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/PrettyStackTrace.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include "llvm/Support/Timer.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Target/TargetMachine.h"
  34. #include "llvm/Target/TargetOptions.h"
  35. #include "llvm/Target/TargetSubtargetInfo.h"
  36. #include "llvm/Transforms/IPO.h"
  37. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  38. #include "llvm/Transforms/Instrumentation.h"
  39. #include "llvm/Transforms/ObjCARC.h"
  40. #include "llvm/Transforms/Scalar.h"
  41. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  42. #include <memory>
  43. using namespace clang;
  44. using namespace llvm;
  45. namespace {
  46. class EmitAssemblyHelper {
  47. DiagnosticsEngine &Diags;
  48. const CodeGenOptions &CodeGenOpts;
  49. const clang::TargetOptions &TargetOpts;
  50. const LangOptions &LangOpts;
  51. Module *TheModule;
  52. Timer CodeGenerationTime;
  53. mutable legacy::PassManager *CodeGenPasses;
  54. mutable legacy::PassManager *PerModulePasses;
  55. mutable legacy::FunctionPassManager *PerFunctionPasses;
  56. private:
  57. TargetIRAnalysis getTargetIRAnalysis() const {
  58. if (TM)
  59. return TM->getTargetIRAnalysis();
  60. return TargetIRAnalysis();
  61. }
  62. legacy::PassManager *getCodeGenPasses() const {
  63. if (!CodeGenPasses) {
  64. CodeGenPasses = new legacy::PassManager();
  65. CodeGenPasses->add(
  66. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  67. }
  68. return CodeGenPasses;
  69. }
  70. legacy::PassManager *getPerModulePasses() const {
  71. if (!PerModulePasses) {
  72. PerModulePasses = new legacy::PassManager();
  73. PerModulePasses->add(
  74. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  75. }
  76. return PerModulePasses;
  77. }
  78. legacy::FunctionPassManager *getPerFunctionPasses() const {
  79. if (!PerFunctionPasses) {
  80. PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
  81. PerFunctionPasses->add(
  82. createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
  83. }
  84. return PerFunctionPasses;
  85. }
  86. void CreatePasses();
  87. /// Generates the TargetMachine.
  88. /// Returns Null if it is unable to create the target machine.
  89. /// Some of our clang tests specify triples which are not built
  90. /// into clang. This is okay because these tests check the generated
  91. /// IR, and they require DataLayout which depends on the triple.
  92. /// In this case, we allow this method to fail and not report an error.
  93. /// When MustCreateTM is used, we print an error if we are unable to load
  94. /// the requested target.
  95. TargetMachine *CreateTargetMachine(bool MustCreateTM);
  96. /// Add passes necessary to emit assembly or LLVM IR.
  97. ///
  98. /// \return True on success.
  99. bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
  100. public:
  101. EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  102. const CodeGenOptions &CGOpts,
  103. const clang::TargetOptions &TOpts,
  104. const LangOptions &LOpts,
  105. Module *M)
  106. : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
  107. TheModule(M), CodeGenerationTime("Code Generation Time"),
  108. CodeGenPasses(nullptr), PerModulePasses(nullptr),
  109. PerFunctionPasses(nullptr) {}
  110. ~EmitAssemblyHelper() {
  111. delete CodeGenPasses;
  112. delete PerModulePasses;
  113. delete PerFunctionPasses;
  114. if (CodeGenOpts.DisableFree)
  115. BuryPointer(std::move(TM));
  116. }
  117. std::unique_ptr<TargetMachine> TM;
  118. void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
  119. };
  120. // We need this wrapper to access LangOpts and CGOpts from extension functions
  121. // that we add to the PassManagerBuilder.
  122. class PassManagerBuilderWrapper : public PassManagerBuilder {
  123. public:
  124. PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
  125. const LangOptions &LangOpts)
  126. : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
  127. const CodeGenOptions &getCGOpts() const { return CGOpts; }
  128. const LangOptions &getLangOpts() const { return LangOpts; }
  129. private:
  130. const CodeGenOptions &CGOpts;
  131. const LangOptions &LangOpts;
  132. };
  133. }
  134. static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  135. if (Builder.OptLevel > 0)
  136. PM.add(createObjCARCAPElimPass());
  137. }
  138. static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  139. if (Builder.OptLevel > 0)
  140. PM.add(createObjCARCExpandPass());
  141. }
  142. static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
  143. if (Builder.OptLevel > 0)
  144. PM.add(createObjCARCOptPass());
  145. }
  146. static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
  147. legacy::PassManagerBase &PM) {
  148. const PassManagerBuilderWrapper &BuilderWrapper =
  149. static_cast<const PassManagerBuilderWrapper &>(Builder);
  150. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  151. PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
  152. }
  153. static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
  154. legacy::PassManagerBase &PM) {
  155. PM.add(createAddDiscriminatorsPass());
  156. }
  157. static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
  158. legacy::PassManagerBase &PM) {
  159. PM.add(createBoundsCheckingPass());
  160. }
  161. static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
  162. legacy::PassManagerBase &PM) {
  163. const PassManagerBuilderWrapper &BuilderWrapper =
  164. static_cast<const PassManagerBuilderWrapper&>(Builder);
  165. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  166. PM.add(createSanitizerCoverageModulePass(CGOpts.SanitizeCoverage));
  167. }
  168. static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
  169. legacy::PassManagerBase &PM) {
  170. PM.add(createAddressSanitizerFunctionPass());
  171. PM.add(createAddressSanitizerModulePass());
  172. }
  173. static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
  174. legacy::PassManagerBase &PM) {
  175. const PassManagerBuilderWrapper &BuilderWrapper =
  176. static_cast<const PassManagerBuilderWrapper&>(Builder);
  177. const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
  178. PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
  179. // MemorySanitizer inserts complex instrumentation that mostly follows
  180. // the logic of the original code, but operates on "shadow" values.
  181. // It can benefit from re-running some general purpose optimization passes.
  182. if (Builder.OptLevel > 0) {
  183. PM.add(createEarlyCSEPass());
  184. PM.add(createReassociatePass());
  185. PM.add(createLICMPass());
  186. PM.add(createGVNPass());
  187. PM.add(createInstructionCombiningPass());
  188. PM.add(createDeadStoreEliminationPass());
  189. }
  190. }
  191. static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
  192. legacy::PassManagerBase &PM) {
  193. PM.add(createThreadSanitizerPass());
  194. }
  195. static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
  196. legacy::PassManagerBase &PM) {
  197. const PassManagerBuilderWrapper &BuilderWrapper =
  198. static_cast<const PassManagerBuilderWrapper&>(Builder);
  199. const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
  200. PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
  201. }
  202. static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
  203. const CodeGenOptions &CodeGenOpts) {
  204. TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
  205. if (!CodeGenOpts.SimplifyLibCalls)
  206. TLII->disableAllFunctions();
  207. switch (CodeGenOpts.getVecLib()) {
  208. case CodeGenOptions::Accelerate:
  209. TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
  210. break;
  211. default:
  212. break;
  213. }
  214. return TLII;
  215. }
  216. static void addSymbolRewriterPass(const CodeGenOptions &Opts,
  217. legacy::PassManager *MPM) {
  218. llvm::SymbolRewriter::RewriteDescriptorList DL;
  219. llvm::SymbolRewriter::RewriteMapParser MapParser;
  220. for (const auto &MapFile : Opts.RewriteMapFiles)
  221. MapParser.parse(MapFile, &DL);
  222. MPM->add(createRewriteSymbolsPass(DL));
  223. }
  224. void EmitAssemblyHelper::CreatePasses() {
  225. unsigned OptLevel = CodeGenOpts.OptimizationLevel;
  226. CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
  227. // Handle disabling of LLVM optimization, where we want to preserve the
  228. // internal module before any optimization.
  229. if (CodeGenOpts.DisableLLVMOpts) {
  230. OptLevel = 0;
  231. Inlining = CodeGenOpts.NoInlining;
  232. }
  233. PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
  234. PMBuilder.OptLevel = OptLevel;
  235. PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
  236. PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
  237. PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
  238. PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
  239. PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
  240. PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
  241. PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
  242. PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
  243. PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
  244. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  245. addAddDiscriminatorsPass);
  246. if (!CodeGenOpts.SampleProfileFile.empty())
  247. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  248. addSampleProfileLoaderPass);
  249. // In ObjC ARC mode, add the main ARC optimization passes.
  250. if (LangOpts.ObjCAutoRefCount) {
  251. PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
  252. addObjCARCExpandPass);
  253. PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
  254. addObjCARCAPElimPass);
  255. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  256. addObjCARCOptPass);
  257. }
  258. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
  259. PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
  260. addBoundsCheckingPass);
  261. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  262. addBoundsCheckingPass);
  263. }
  264. if (CodeGenOpts.SanitizeCoverage) {
  265. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  266. addSanitizerCoveragePass);
  267. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  268. addSanitizerCoveragePass);
  269. }
  270. if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
  271. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  272. addAddressSanitizerPasses);
  273. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  274. addAddressSanitizerPasses);
  275. }
  276. if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
  277. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  278. addMemorySanitizerPass);
  279. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  280. addMemorySanitizerPass);
  281. }
  282. if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
  283. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  284. addThreadSanitizerPass);
  285. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  286. addThreadSanitizerPass);
  287. }
  288. if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
  289. PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
  290. addDataFlowSanitizerPass);
  291. PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
  292. addDataFlowSanitizerPass);
  293. }
  294. // Figure out TargetLibraryInfo.
  295. Triple TargetTriple(TheModule->getTargetTriple());
  296. PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
  297. switch (Inlining) {
  298. case CodeGenOptions::NoInlining: break;
  299. case CodeGenOptions::NormalInlining: {
  300. PMBuilder.Inliner =
  301. createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
  302. break;
  303. }
  304. case CodeGenOptions::OnlyAlwaysInlining:
  305. // Respect always_inline.
  306. if (OptLevel == 0)
  307. // Do not insert lifetime intrinsics at -O0.
  308. PMBuilder.Inliner = createAlwaysInlinerPass(false);
  309. else
  310. PMBuilder.Inliner = createAlwaysInlinerPass();
  311. break;
  312. }
  313. // Set up the per-function pass manager.
  314. legacy::FunctionPassManager *FPM = getPerFunctionPasses();
  315. if (CodeGenOpts.VerifyModule)
  316. FPM->add(createVerifierPass());
  317. PMBuilder.populateFunctionPassManager(*FPM);
  318. // Set up the per-module pass manager.
  319. legacy::PassManager *MPM = getPerModulePasses();
  320. if (!CodeGenOpts.RewriteMapFiles.empty())
  321. addSymbolRewriterPass(CodeGenOpts, MPM);
  322. if (!CodeGenOpts.DisableGCov &&
  323. (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
  324. // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
  325. // LLVM's -default-gcov-version flag is set to something invalid.
  326. GCOVOptions Options;
  327. Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
  328. Options.EmitData = CodeGenOpts.EmitGcovArcs;
  329. memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
  330. Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
  331. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  332. Options.FunctionNamesInData =
  333. !CodeGenOpts.CoverageNoFunctionNamesInData;
  334. Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
  335. MPM->add(createGCOVProfilerPass(Options));
  336. if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
  337. MPM->add(createStripSymbolsPass(true));
  338. }
  339. if (CodeGenOpts.ProfileInstrGenerate) {
  340. InstrProfOptions Options;
  341. Options.NoRedZone = CodeGenOpts.DisableRedZone;
  342. MPM->add(createInstrProfilingPass(Options));
  343. }
  344. PMBuilder.populateModulePassManager(*MPM);
  345. }
  346. TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
  347. // Create the TargetMachine for generating code.
  348. std::string Error;
  349. std::string Triple = TheModule->getTargetTriple();
  350. const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
  351. if (!TheTarget) {
  352. if (MustCreateTM)
  353. Diags.Report(diag::err_fe_unable_to_create_target) << Error;
  354. return nullptr;
  355. }
  356. unsigned CodeModel =
  357. llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
  358. .Case("small", llvm::CodeModel::Small)
  359. .Case("kernel", llvm::CodeModel::Kernel)
  360. .Case("medium", llvm::CodeModel::Medium)
  361. .Case("large", llvm::CodeModel::Large)
  362. .Case("default", llvm::CodeModel::Default)
  363. .Default(~0u);
  364. assert(CodeModel != ~0u && "invalid code model!");
  365. llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
  366. SmallVector<const char *, 16> BackendArgs;
  367. BackendArgs.push_back("clang"); // Fake program name.
  368. if (!CodeGenOpts.DebugPass.empty()) {
  369. BackendArgs.push_back("-debug-pass");
  370. BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  371. }
  372. if (!CodeGenOpts.LimitFloatPrecision.empty()) {
  373. BackendArgs.push_back("-limit-float-precision");
  374. BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  375. }
  376. if (llvm::TimePassesIsEnabled)
  377. BackendArgs.push_back("-time-passes");
  378. for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
  379. BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
  380. BackendArgs.push_back(nullptr);
  381. llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
  382. BackendArgs.data());
  383. std::string FeaturesStr;
  384. if (!TargetOpts.Features.empty()) {
  385. SubtargetFeatures Features;
  386. for (std::vector<std::string>::const_iterator
  387. it = TargetOpts.Features.begin(),
  388. ie = TargetOpts.Features.end(); it != ie; ++it)
  389. Features.AddFeature(*it);
  390. FeaturesStr = Features.getString();
  391. }
  392. llvm::Reloc::Model RM = llvm::Reloc::Default;
  393. if (CodeGenOpts.RelocationModel == "static") {
  394. RM = llvm::Reloc::Static;
  395. } else if (CodeGenOpts.RelocationModel == "pic") {
  396. RM = llvm::Reloc::PIC_;
  397. } else {
  398. assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
  399. "Invalid PIC model!");
  400. RM = llvm::Reloc::DynamicNoPIC;
  401. }
  402. CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
  403. switch (CodeGenOpts.OptimizationLevel) {
  404. default: break;
  405. case 0: OptLevel = CodeGenOpt::None; break;
  406. case 3: OptLevel = CodeGenOpt::Aggressive; break;
  407. }
  408. llvm::TargetOptions Options;
  409. Options.ThreadModel =
  410. llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
  411. .Case("posix", llvm::ThreadModel::POSIX)
  412. .Case("single", llvm::ThreadModel::Single);
  413. if (CodeGenOpts.DisableIntegratedAS)
  414. Options.DisableIntegratedAS = true;
  415. if (CodeGenOpts.CompressDebugSections)
  416. Options.CompressDebugSections = true;
  417. // Set frame pointer elimination mode.
  418. if (!CodeGenOpts.DisableFPElim) {
  419. Options.NoFramePointerElim = false;
  420. } else if (CodeGenOpts.OmitLeafFramePointer) {
  421. Options.NoFramePointerElim = false;
  422. } else {
  423. Options.NoFramePointerElim = true;
  424. }
  425. if (CodeGenOpts.UseInitArray)
  426. Options.UseInitArray = true;
  427. // Set float ABI type.
  428. if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
  429. Options.FloatABIType = llvm::FloatABI::Soft;
  430. else if (CodeGenOpts.FloatABI == "hard")
  431. Options.FloatABIType = llvm::FloatABI::Hard;
  432. else {
  433. assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
  434. Options.FloatABIType = llvm::FloatABI::Default;
  435. }
  436. // Set FP fusion mode.
  437. switch (CodeGenOpts.getFPContractMode()) {
  438. case CodeGenOptions::FPC_Off:
  439. Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
  440. break;
  441. case CodeGenOptions::FPC_On:
  442. Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
  443. break;
  444. case CodeGenOptions::FPC_Fast:
  445. Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
  446. break;
  447. }
  448. Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
  449. Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
  450. Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
  451. Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
  452. Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
  453. Options.UseSoftFloat = CodeGenOpts.SoftFloat;
  454. Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
  455. Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
  456. Options.TrapFuncName = CodeGenOpts.TrapFuncName;
  457. Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
  458. Options.FunctionSections = CodeGenOpts.FunctionSections;
  459. Options.DataSections = CodeGenOpts.DataSections;
  460. Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
  461. Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
  462. Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
  463. Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
  464. Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
  465. Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
  466. Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
  467. Options.MCOptions.ABIName = TargetOpts.ABI;
  468. TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
  469. FeaturesStr, Options,
  470. RM, CM, OptLevel);
  471. return TM;
  472. }
  473. bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
  474. raw_pwrite_stream &OS) {
  475. // Create the code generator passes.
  476. legacy::PassManager *PM = getCodeGenPasses();
  477. // Add LibraryInfo.
  478. llvm::Triple TargetTriple(TheModule->getTargetTriple());
  479. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  480. createTLII(TargetTriple, CodeGenOpts));
  481. PM->add(new TargetLibraryInfoWrapperPass(*TLII));
  482. // Normal mode, emit a .s or .o file by running the code generator. Note,
  483. // this also adds codegenerator level optimization passes.
  484. TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
  485. if (Action == Backend_EmitObj)
  486. CGFT = TargetMachine::CGFT_ObjectFile;
  487. else if (Action == Backend_EmitMCNull)
  488. CGFT = TargetMachine::CGFT_Null;
  489. else
  490. assert(Action == Backend_EmitAssembly && "Invalid action!");
  491. // Add ObjC ARC final-cleanup optimizations. This is done as part of the
  492. // "codegen" passes so that it isn't run multiple times when there is
  493. // inlining happening.
  494. if (LangOpts.ObjCAutoRefCount &&
  495. CodeGenOpts.OptimizationLevel > 0)
  496. PM->add(createObjCARCContractPass());
  497. if (TM->addPassesToEmitFile(*PM, OS, CGFT,
  498. /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
  499. Diags.Report(diag::err_fe_unable_to_interface_with_target);
  500. return false;
  501. }
  502. return true;
  503. }
  504. void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
  505. raw_pwrite_stream *OS) {
  506. TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
  507. bool UsesCodeGen = (Action != Backend_EmitNothing &&
  508. Action != Backend_EmitBC &&
  509. Action != Backend_EmitLL);
  510. if (!TM)
  511. TM.reset(CreateTargetMachine(UsesCodeGen));
  512. if (UsesCodeGen && !TM) return;
  513. CreatePasses();
  514. switch (Action) {
  515. case Backend_EmitNothing:
  516. break;
  517. case Backend_EmitBC:
  518. getPerModulePasses()->add(createBitcodeWriterPass(*OS));
  519. break;
  520. case Backend_EmitLL:
  521. getPerModulePasses()->add(createPrintModulePass(*OS));
  522. break;
  523. default:
  524. if (!AddEmitPasses(Action, *OS))
  525. return;
  526. }
  527. // Before executing passes, print the final values of the LLVM options.
  528. cl::PrintOptionValues();
  529. // Run passes. For now we do all passes at once, but eventually we
  530. // would like to have the option of streaming code generation.
  531. if (PerFunctionPasses) {
  532. PrettyStackTraceString CrashInfo("Per-function optimization");
  533. PerFunctionPasses->doInitialization();
  534. for (Module::iterator I = TheModule->begin(),
  535. E = TheModule->end(); I != E; ++I)
  536. if (!I->isDeclaration())
  537. PerFunctionPasses->run(*I);
  538. PerFunctionPasses->doFinalization();
  539. }
  540. if (PerModulePasses) {
  541. PrettyStackTraceString CrashInfo("Per-module optimization passes");
  542. PerModulePasses->run(*TheModule);
  543. }
  544. if (CodeGenPasses) {
  545. PrettyStackTraceString CrashInfo("Code generation");
  546. CodeGenPasses->run(*TheModule);
  547. }
  548. }
  549. void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
  550. const CodeGenOptions &CGOpts,
  551. const clang::TargetOptions &TOpts,
  552. const LangOptions &LOpts, StringRef TDesc,
  553. Module *M, BackendAction Action,
  554. raw_pwrite_stream *OS) {
  555. EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
  556. AsmHelper.EmitAssembly(Action, OS);
  557. // If an optional clang TargetInfo description string was passed in, use it to
  558. // verify the LLVM TargetMachine's DataLayout.
  559. if (AsmHelper.TM && !TDesc.empty()) {
  560. std::string DLDesc =
  561. AsmHelper.TM->getDataLayout()->getStringRepresentation();
  562. if (DLDesc != TDesc) {
  563. unsigned DiagID = Diags.getCustomDiagID(
  564. DiagnosticsEngine::Error, "backend data layout '%0' does not match "
  565. "expected target description '%1'");
  566. Diags.Report(DiagID) << DLDesc << TDesc;
  567. }
  568. }
  569. }