clang API Documentation

BackendUtil.cpp
Go to the documentation of this file.
00001 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/CodeGen/BackendUtil.h"
00011 #include "clang/Basic/Diagnostic.h"
00012 #include "clang/Basic/LangOptions.h"
00013 #include "clang/Basic/TargetOptions.h"
00014 #include "clang/Frontend/CodeGenOptions.h"
00015 #include "clang/Frontend/FrontendDiagnostic.h"
00016 #include "clang/Frontend/Utils.h"
00017 #include "llvm/ADT/StringSwitch.h"
00018 #include "llvm/Bitcode/BitcodeWriterPass.h"
00019 #include "llvm/CodeGen/RegAllocRegistry.h"
00020 #include "llvm/CodeGen/SchedulerRegistry.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/IRPrintingPasses.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Verifier.h"
00025 #include "llvm/MC/SubtargetFeature.h"
00026 #include "llvm/PassManager.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/FormattedStream.h"
00029 #include "llvm/Support/PrettyStackTrace.h"
00030 #include "llvm/Support/TargetRegistry.h"
00031 #include "llvm/Support/Timer.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include "llvm/Target/TargetLibraryInfo.h"
00034 #include "llvm/Target/TargetMachine.h"
00035 #include "llvm/Target/TargetOptions.h"
00036 #include "llvm/Target/TargetSubtargetInfo.h"
00037 #include "llvm/Transforms/IPO.h"
00038 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
00039 #include "llvm/Transforms/Instrumentation.h"
00040 #include "llvm/Transforms/ObjCARC.h"
00041 #include "llvm/Transforms/Scalar.h"
00042 #include <memory>
00043 using namespace clang;
00044 using namespace llvm;
00045 
00046 namespace {
00047 
00048 class EmitAssemblyHelper {
00049   DiagnosticsEngine &Diags;
00050   const CodeGenOptions &CodeGenOpts;
00051   const clang::TargetOptions &TargetOpts;
00052   const LangOptions &LangOpts;
00053   Module *TheModule;
00054 
00055   Timer CodeGenerationTime;
00056 
00057   mutable PassManager *CodeGenPasses;
00058   mutable PassManager *PerModulePasses;
00059   mutable FunctionPassManager *PerFunctionPasses;
00060 
00061 private:
00062   PassManager *getCodeGenPasses() const {
00063     if (!CodeGenPasses) {
00064       CodeGenPasses = new PassManager();
00065       CodeGenPasses->add(new DataLayoutPass());
00066       if (TM)
00067         TM->addAnalysisPasses(*CodeGenPasses);
00068     }
00069     return CodeGenPasses;
00070   }
00071 
00072   PassManager *getPerModulePasses() const {
00073     if (!PerModulePasses) {
00074       PerModulePasses = new PassManager();
00075       PerModulePasses->add(new DataLayoutPass());
00076       if (TM)
00077         TM->addAnalysisPasses(*PerModulePasses);
00078     }
00079     return PerModulePasses;
00080   }
00081 
00082   FunctionPassManager *getPerFunctionPasses() const {
00083     if (!PerFunctionPasses) {
00084       PerFunctionPasses = new FunctionPassManager(TheModule);
00085       PerFunctionPasses->add(new DataLayoutPass());
00086       if (TM)
00087         TM->addAnalysisPasses(*PerFunctionPasses);
00088     }
00089     return PerFunctionPasses;
00090   }
00091 
00092   void CreatePasses();
00093 
00094   /// CreateTargetMachine - Generates the TargetMachine.
00095   /// Returns Null if it is unable to create the target machine.
00096   /// Some of our clang tests specify triples which are not built
00097   /// into clang. This is okay because these tests check the generated
00098   /// IR, and they require DataLayout which depends on the triple.
00099   /// In this case, we allow this method to fail and not report an error.
00100   /// When MustCreateTM is used, we print an error if we are unable to load
00101   /// the requested target.
00102   TargetMachine *CreateTargetMachine(bool MustCreateTM);
00103 
00104   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
00105   ///
00106   /// \return True on success.
00107   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
00108 
00109 public:
00110   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
00111                      const CodeGenOptions &CGOpts,
00112                      const clang::TargetOptions &TOpts,
00113                      const LangOptions &LOpts,
00114                      Module *M)
00115     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
00116       TheModule(M), CodeGenerationTime("Code Generation Time"),
00117       CodeGenPasses(nullptr), PerModulePasses(nullptr),
00118       PerFunctionPasses(nullptr) {}
00119 
00120   ~EmitAssemblyHelper() {
00121     delete CodeGenPasses;
00122     delete PerModulePasses;
00123     delete PerFunctionPasses;
00124     if (CodeGenOpts.DisableFree)
00125       BuryPointer(std::move(TM));
00126   }
00127 
00128   std::unique_ptr<TargetMachine> TM;
00129 
00130   void EmitAssembly(BackendAction Action, raw_ostream *OS);
00131 };
00132 
00133 // We need this wrapper to access LangOpts and CGOpts from extension functions
00134 // that we add to the PassManagerBuilder.
00135 class PassManagerBuilderWrapper : public PassManagerBuilder {
00136 public:
00137   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
00138                             const LangOptions &LangOpts)
00139       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
00140   const CodeGenOptions &getCGOpts() const { return CGOpts; }
00141   const LangOptions &getLangOpts() const { return LangOpts; }
00142 private:
00143   const CodeGenOptions &CGOpts;
00144   const LangOptions &LangOpts;
00145 };
00146 
00147 }
00148 
00149 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
00150   if (Builder.OptLevel > 0)
00151     PM.add(createObjCARCAPElimPass());
00152 }
00153 
00154 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
00155   if (Builder.OptLevel > 0)
00156     PM.add(createObjCARCExpandPass());
00157 }
00158 
00159 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
00160   if (Builder.OptLevel > 0)
00161     PM.add(createObjCARCOptPass());
00162 }
00163 
00164 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
00165                                        PassManagerBase &PM) {
00166   const PassManagerBuilderWrapper &BuilderWrapper =
00167       static_cast<const PassManagerBuilderWrapper &>(Builder);
00168   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
00169   PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
00170 }
00171 
00172 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
00173                                      PassManagerBase &PM) {
00174   PM.add(createAddDiscriminatorsPass());
00175 }
00176 
00177 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
00178                                     PassManagerBase &PM) {
00179   PM.add(createBoundsCheckingPass());
00180 }
00181 
00182 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
00183                                      PassManagerBase &PM) {
00184   const PassManagerBuilderWrapper &BuilderWrapper =
00185       static_cast<const PassManagerBuilderWrapper&>(Builder);
00186   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
00187   PM.add(createSanitizerCoverageModulePass(CGOpts.SanitizeCoverage));
00188 }
00189 
00190 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
00191                                       PassManagerBase &PM) {
00192   PM.add(createAddressSanitizerFunctionPass());
00193   PM.add(createAddressSanitizerModulePass());
00194 }
00195 
00196 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
00197                                    PassManagerBase &PM) {
00198   const PassManagerBuilderWrapper &BuilderWrapper =
00199       static_cast<const PassManagerBuilderWrapper&>(Builder);
00200   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
00201   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
00202 
00203   // MemorySanitizer inserts complex instrumentation that mostly follows
00204   // the logic of the original code, but operates on "shadow" values.
00205   // It can benefit from re-running some general purpose optimization passes.
00206   if (Builder.OptLevel > 0) {
00207     PM.add(createEarlyCSEPass());
00208     PM.add(createReassociatePass());
00209     PM.add(createLICMPass());
00210     PM.add(createGVNPass());
00211     PM.add(createInstructionCombiningPass());
00212     PM.add(createDeadStoreEliminationPass());
00213   }
00214 }
00215 
00216 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
00217                                    PassManagerBase &PM) {
00218   PM.add(createThreadSanitizerPass());
00219 }
00220 
00221 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
00222                                      PassManagerBase &PM) {
00223   const PassManagerBuilderWrapper &BuilderWrapper =
00224       static_cast<const PassManagerBuilderWrapper&>(Builder);
00225   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
00226   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFile));
00227 }
00228 
00229 static TargetLibraryInfo *createTLI(llvm::Triple &TargetTriple,
00230                                     const CodeGenOptions &CodeGenOpts) {
00231   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
00232   if (!CodeGenOpts.SimplifyLibCalls)
00233     TLI->disableAllFunctions();
00234   return TLI;
00235 }
00236 
00237 void EmitAssemblyHelper::CreatePasses() {
00238   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
00239   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
00240 
00241   // Handle disabling of LLVM optimization, where we want to preserve the
00242   // internal module before any optimization.
00243   if (CodeGenOpts.DisableLLVMOpts) {
00244     OptLevel = 0;
00245     Inlining = CodeGenOpts.NoInlining;
00246   }
00247 
00248   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
00249   PMBuilder.OptLevel = OptLevel;
00250   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
00251   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
00252   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
00253   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
00254 
00255   PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
00256   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
00257   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
00258   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
00259   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
00260 
00261   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
00262                          addAddDiscriminatorsPass);
00263 
00264   if (!CodeGenOpts.SampleProfileFile.empty())
00265     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
00266                            addSampleProfileLoaderPass);
00267 
00268   // In ObjC ARC mode, add the main ARC optimization passes.
00269   if (LangOpts.ObjCAutoRefCount) {
00270     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
00271                            addObjCARCExpandPass);
00272     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
00273                            addObjCARCAPElimPass);
00274     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
00275                            addObjCARCOptPass);
00276   }
00277 
00278   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
00279     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
00280                            addBoundsCheckingPass);
00281     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00282                            addBoundsCheckingPass);
00283   }
00284 
00285   if (CodeGenOpts.SanitizeCoverage) {
00286     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
00287                            addSanitizerCoveragePass);
00288     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00289                            addSanitizerCoveragePass);
00290   }
00291 
00292   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
00293     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
00294                            addAddressSanitizerPasses);
00295     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00296                            addAddressSanitizerPasses);
00297   }
00298 
00299   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
00300     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
00301                            addMemorySanitizerPass);
00302     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00303                            addMemorySanitizerPass);
00304   }
00305 
00306   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
00307     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
00308                            addThreadSanitizerPass);
00309     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00310                            addThreadSanitizerPass);
00311   }
00312 
00313   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
00314     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
00315                            addDataFlowSanitizerPass);
00316     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
00317                            addDataFlowSanitizerPass);
00318   }
00319 
00320   // Figure out TargetLibraryInfo.
00321   Triple TargetTriple(TheModule->getTargetTriple());
00322   PMBuilder.LibraryInfo = createTLI(TargetTriple, CodeGenOpts);
00323 
00324   switch (Inlining) {
00325   case CodeGenOptions::NoInlining: break;
00326   case CodeGenOptions::NormalInlining: {
00327     PMBuilder.Inliner =
00328         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
00329     break;
00330   }
00331   case CodeGenOptions::OnlyAlwaysInlining:
00332     // Respect always_inline.
00333     if (OptLevel == 0)
00334       // Do not insert lifetime intrinsics at -O0.
00335       PMBuilder.Inliner = createAlwaysInlinerPass(false);
00336     else
00337       PMBuilder.Inliner = createAlwaysInlinerPass();
00338     break;
00339   }
00340 
00341   // Set up the per-function pass manager.
00342   FunctionPassManager *FPM = getPerFunctionPasses();
00343   if (CodeGenOpts.VerifyModule)
00344     FPM->add(createVerifierPass());
00345   PMBuilder.populateFunctionPassManager(*FPM);
00346 
00347   // Set up the per-module pass manager.
00348   PassManager *MPM = getPerModulePasses();
00349   if (CodeGenOpts.VerifyModule)
00350     MPM->add(createDebugInfoVerifierPass());
00351 
00352   if (!CodeGenOpts.DisableGCov &&
00353       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
00354     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
00355     // LLVM's -default-gcov-version flag is set to something invalid.
00356     GCOVOptions Options;
00357     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
00358     Options.EmitData = CodeGenOpts.EmitGcovArcs;
00359     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
00360     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
00361     Options.NoRedZone = CodeGenOpts.DisableRedZone;
00362     Options.FunctionNamesInData =
00363         !CodeGenOpts.CoverageNoFunctionNamesInData;
00364     MPM->add(createGCOVProfilerPass(Options));
00365     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
00366       MPM->add(createStripSymbolsPass(true));
00367   }
00368 
00369   PMBuilder.populateModulePassManager(*MPM);
00370 }
00371 
00372 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
00373   // Create the TargetMachine for generating code.
00374   std::string Error;
00375   std::string Triple = TheModule->getTargetTriple();
00376   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
00377   if (!TheTarget) {
00378     if (MustCreateTM)
00379       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
00380     return nullptr;
00381   }
00382 
00383   unsigned CodeModel =
00384     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
00385       .Case("small", llvm::CodeModel::Small)
00386       .Case("kernel", llvm::CodeModel::Kernel)
00387       .Case("medium", llvm::CodeModel::Medium)
00388       .Case("large", llvm::CodeModel::Large)
00389       .Case("default", llvm::CodeModel::Default)
00390       .Default(~0u);
00391   assert(CodeModel != ~0u && "invalid code model!");
00392   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
00393 
00394   SmallVector<const char *, 16> BackendArgs;
00395   BackendArgs.push_back("clang"); // Fake program name.
00396   if (!CodeGenOpts.DebugPass.empty()) {
00397     BackendArgs.push_back("-debug-pass");
00398     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
00399   }
00400   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
00401     BackendArgs.push_back("-limit-float-precision");
00402     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
00403   }
00404   if (llvm::TimePassesIsEnabled)
00405     BackendArgs.push_back("-time-passes");
00406   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
00407     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
00408   if (CodeGenOpts.NoGlobalMerge)
00409     BackendArgs.push_back("-enable-global-merge=false");
00410   BackendArgs.push_back(nullptr);
00411   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
00412                                     BackendArgs.data());
00413 
00414   std::string FeaturesStr;
00415   if (TargetOpts.Features.size()) {
00416     SubtargetFeatures Features;
00417     for (std::vector<std::string>::const_iterator
00418            it = TargetOpts.Features.begin(),
00419            ie = TargetOpts.Features.end(); it != ie; ++it)
00420       Features.AddFeature(*it);
00421     FeaturesStr = Features.getString();
00422   }
00423 
00424   llvm::Reloc::Model RM = llvm::Reloc::Default;
00425   if (CodeGenOpts.RelocationModel == "static") {
00426     RM = llvm::Reloc::Static;
00427   } else if (CodeGenOpts.RelocationModel == "pic") {
00428     RM = llvm::Reloc::PIC_;
00429   } else {
00430     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
00431            "Invalid PIC model!");
00432     RM = llvm::Reloc::DynamicNoPIC;
00433   }
00434 
00435   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
00436   switch (CodeGenOpts.OptimizationLevel) {
00437   default: break;
00438   case 0: OptLevel = CodeGenOpt::None; break;
00439   case 3: OptLevel = CodeGenOpt::Aggressive; break;
00440   }
00441 
00442   llvm::TargetOptions Options;
00443 
00444   Options.ThreadModel =
00445     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
00446       .Case("posix", llvm::ThreadModel::POSIX)
00447       .Case("single", llvm::ThreadModel::Single);
00448 
00449   if (CodeGenOpts.DisableIntegratedAS)
00450     Options.DisableIntegratedAS = true;
00451 
00452   if (CodeGenOpts.CompressDebugSections)
00453     Options.CompressDebugSections = true;
00454 
00455   // Set frame pointer elimination mode.
00456   if (!CodeGenOpts.DisableFPElim) {
00457     Options.NoFramePointerElim = false;
00458   } else if (CodeGenOpts.OmitLeafFramePointer) {
00459     Options.NoFramePointerElim = false;
00460   } else {
00461     Options.NoFramePointerElim = true;
00462   }
00463 
00464   if (CodeGenOpts.UseInitArray)
00465     Options.UseInitArray = true;
00466 
00467   // Set float ABI type.
00468   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
00469     Options.FloatABIType = llvm::FloatABI::Soft;
00470   else if (CodeGenOpts.FloatABI == "hard")
00471     Options.FloatABIType = llvm::FloatABI::Hard;
00472   else {
00473     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
00474     Options.FloatABIType = llvm::FloatABI::Default;
00475   }
00476 
00477   // Set FP fusion mode.
00478   switch (CodeGenOpts.getFPContractMode()) {
00479   case CodeGenOptions::FPC_Off:
00480     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
00481     break;
00482   case CodeGenOptions::FPC_On:
00483     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
00484     break;
00485   case CodeGenOptions::FPC_Fast:
00486     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
00487     break;
00488   }
00489 
00490   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
00491   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
00492   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
00493   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
00494   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
00495   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
00496   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
00497   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
00498   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
00499   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
00500   Options.FunctionSections = CodeGenOpts.FunctionSections;
00501   Options.DataSections = CodeGenOpts.DataSections;
00502 
00503   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
00504   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
00505   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
00506   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
00507   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
00508   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
00509 
00510   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
00511                                                      FeaturesStr, Options,
00512                                                      RM, CM, OptLevel);
00513 
00514   return TM;
00515 }
00516 
00517 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
00518                                        formatted_raw_ostream &OS) {
00519 
00520   // Create the code generator passes.
00521   PassManager *PM = getCodeGenPasses();
00522 
00523   // Add LibraryInfo.
00524   llvm::Triple TargetTriple(TheModule->getTargetTriple());
00525   PM->add(createTLI(TargetTriple, CodeGenOpts));
00526 
00527   // Add Target specific analysis passes.
00528   TM->addAnalysisPasses(*PM);
00529 
00530   // Normal mode, emit a .s or .o file by running the code generator. Note,
00531   // this also adds codegenerator level optimization passes.
00532   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
00533   if (Action == Backend_EmitObj)
00534     CGFT = TargetMachine::CGFT_ObjectFile;
00535   else if (Action == Backend_EmitMCNull)
00536     CGFT = TargetMachine::CGFT_Null;
00537   else
00538     assert(Action == Backend_EmitAssembly && "Invalid action!");
00539 
00540   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
00541   // "codegen" passes so that it isn't run multiple times when there is
00542   // inlining happening.
00543   if (LangOpts.ObjCAutoRefCount &&
00544       CodeGenOpts.OptimizationLevel > 0)
00545     PM->add(createObjCARCContractPass());
00546 
00547   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
00548                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
00549     Diags.Report(diag::err_fe_unable_to_interface_with_target);
00550     return false;
00551   }
00552 
00553   return true;
00554 }
00555 
00556 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
00557   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
00558   llvm::formatted_raw_ostream FormattedOS;
00559 
00560   bool UsesCodeGen = (Action != Backend_EmitNothing &&
00561                       Action != Backend_EmitBC &&
00562                       Action != Backend_EmitLL);
00563   if (!TM)
00564     TM.reset(CreateTargetMachine(UsesCodeGen));
00565 
00566   if (UsesCodeGen && !TM) return;
00567   CreatePasses();
00568 
00569   switch (Action) {
00570   case Backend_EmitNothing:
00571     break;
00572 
00573   case Backend_EmitBC:
00574     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
00575     break;
00576 
00577   case Backend_EmitLL:
00578     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
00579     getPerModulePasses()->add(createPrintModulePass(FormattedOS));
00580     break;
00581 
00582   default:
00583     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
00584     if (!AddEmitPasses(Action, FormattedOS))
00585       return;
00586   }
00587 
00588   // Before executing passes, print the final values of the LLVM options.
00589   cl::PrintOptionValues();
00590 
00591   // Run passes. For now we do all passes at once, but eventually we
00592   // would like to have the option of streaming code generation.
00593 
00594   if (PerFunctionPasses) {
00595     PrettyStackTraceString CrashInfo("Per-function optimization");
00596 
00597     PerFunctionPasses->doInitialization();
00598     for (Module::iterator I = TheModule->begin(),
00599            E = TheModule->end(); I != E; ++I)
00600       if (!I->isDeclaration())
00601         PerFunctionPasses->run(*I);
00602     PerFunctionPasses->doFinalization();
00603   }
00604 
00605   if (PerModulePasses) {
00606     PrettyStackTraceString CrashInfo("Per-module optimization passes");
00607     PerModulePasses->run(*TheModule);
00608   }
00609 
00610   if (CodeGenPasses) {
00611     PrettyStackTraceString CrashInfo("Code generation");
00612     CodeGenPasses->run(*TheModule);
00613   }
00614 }
00615 
00616 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
00617                               const CodeGenOptions &CGOpts,
00618                               const clang::TargetOptions &TOpts,
00619                               const LangOptions &LOpts, StringRef TDesc,
00620                               Module *M, BackendAction Action,
00621                               raw_ostream *OS) {
00622   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
00623 
00624   AsmHelper.EmitAssembly(Action, OS);
00625 
00626   // If an optional clang TargetInfo description string was passed in, use it to
00627   // verify the LLVM TargetMachine's DataLayout.
00628   if (AsmHelper.TM && !TDesc.empty()) {
00629     std::string DLDesc = AsmHelper.TM->getSubtargetImpl()
00630                              ->getDataLayout()
00631                              ->getStringRepresentation();
00632     if (DLDesc != TDesc) {
00633       unsigned DiagID = Diags.getCustomDiagID(
00634           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
00635                                     "expected target description '%1'");
00636       Diags.Report(DiagID) << DLDesc << TDesc;
00637     }
00638   }
00639 }