BackendUtil.cpp 21 KB

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