BackendUtil.cpp 20 KB

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