BackendUtil.cpp 23 KB

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