1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/Bitcode/BitcodeWriterPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetLibraryInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/IPO.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/ObjCARC.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Utils/SymbolRewriter.h"
44 using namespace clang;
49 class EmitAssemblyHelper {
50 DiagnosticsEngine &Diags;
51 const CodeGenOptions &CodeGenOpts;
52 const clang::TargetOptions &TargetOpts;
53 const LangOptions &LangOpts;
56 Timer CodeGenerationTime;
58 mutable PassManager *CodeGenPasses;
59 mutable PassManager *PerModulePasses;
60 mutable FunctionPassManager *PerFunctionPasses;
63 PassManager *getCodeGenPasses() const {
65 CodeGenPasses = new PassManager();
66 CodeGenPasses->add(new DataLayoutPass());
68 TM->addAnalysisPasses(*CodeGenPasses);
73 PassManager *getPerModulePasses() const {
74 if (!PerModulePasses) {
75 PerModulePasses = new PassManager();
76 PerModulePasses->add(new DataLayoutPass());
78 TM->addAnalysisPasses(*PerModulePasses);
80 return PerModulePasses;
83 FunctionPassManager *getPerFunctionPasses() const {
84 if (!PerFunctionPasses) {
85 PerFunctionPasses = new FunctionPassManager(TheModule);
86 PerFunctionPasses->add(new DataLayoutPass());
88 TM->addAnalysisPasses(*PerFunctionPasses);
90 return PerFunctionPasses;
95 /// CreateTargetMachine - Generates the TargetMachine.
96 /// Returns Null if it is unable to create the target machine.
97 /// Some of our clang tests specify triples which are not built
98 /// into clang. This is okay because these tests check the generated
99 /// IR, and they require DataLayout which depends on the triple.
100 /// In this case, we allow this method to fail and not report an error.
101 /// When MustCreateTM is used, we print an error if we are unable to load
102 /// the requested target.
103 TargetMachine *CreateTargetMachine(bool MustCreateTM);
105 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
107 /// \return True on success.
108 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
111 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
112 const CodeGenOptions &CGOpts,
113 const clang::TargetOptions &TOpts,
114 const LangOptions &LOpts,
116 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
117 TheModule(M), CodeGenerationTime("Code Generation Time"),
118 CodeGenPasses(nullptr), PerModulePasses(nullptr),
119 PerFunctionPasses(nullptr) {}
121 ~EmitAssemblyHelper() {
122 delete CodeGenPasses;
123 delete PerModulePasses;
124 delete PerFunctionPasses;
125 if (CodeGenOpts.DisableFree)
126 BuryPointer(std::move(TM));
129 std::unique_ptr<TargetMachine> TM;
131 void EmitAssembly(BackendAction Action, raw_ostream *OS);
134 // We need this wrapper to access LangOpts and CGOpts from extension functions
135 // that we add to the PassManagerBuilder.
136 class PassManagerBuilderWrapper : public PassManagerBuilder {
138 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
139 const LangOptions &LangOpts)
140 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
141 const CodeGenOptions &getCGOpts() const { return CGOpts; }
142 const LangOptions &getLangOpts() const { return LangOpts; }
144 const CodeGenOptions &CGOpts;
145 const LangOptions &LangOpts;
150 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
151 if (Builder.OptLevel > 0)
152 PM.add(createObjCARCAPElimPass());
155 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
156 if (Builder.OptLevel > 0)
157 PM.add(createObjCARCExpandPass());
160 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
161 if (Builder.OptLevel > 0)
162 PM.add(createObjCARCOptPass());
165 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
166 PassManagerBase &PM) {
167 const PassManagerBuilderWrapper &BuilderWrapper =
168 static_cast<const PassManagerBuilderWrapper &>(Builder);
169 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
170 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
173 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
174 PassManagerBase &PM) {
175 PM.add(createAddDiscriminatorsPass());
178 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
179 PassManagerBase &PM) {
180 PM.add(createBoundsCheckingPass());
183 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
184 PassManagerBase &PM) {
185 const PassManagerBuilderWrapper &BuilderWrapper =
186 static_cast<const PassManagerBuilderWrapper&>(Builder);
187 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
188 PM.add(createSanitizerCoverageModulePass(CGOpts.SanitizeCoverage));
191 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
192 PassManagerBase &PM) {
193 PM.add(createAddressSanitizerFunctionPass());
194 PM.add(createAddressSanitizerModulePass());
197 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
198 PassManagerBase &PM) {
199 const PassManagerBuilderWrapper &BuilderWrapper =
200 static_cast<const PassManagerBuilderWrapper&>(Builder);
201 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
202 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
204 // MemorySanitizer inserts complex instrumentation that mostly follows
205 // the logic of the original code, but operates on "shadow" values.
206 // It can benefit from re-running some general purpose optimization passes.
207 if (Builder.OptLevel > 0) {
208 PM.add(createEarlyCSEPass());
209 PM.add(createReassociatePass());
210 PM.add(createLICMPass());
211 PM.add(createGVNPass());
212 PM.add(createInstructionCombiningPass());
213 PM.add(createDeadStoreEliminationPass());
217 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
218 PassManagerBase &PM) {
219 PM.add(createThreadSanitizerPass());
222 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
223 PassManagerBase &PM) {
224 const PassManagerBuilderWrapper &BuilderWrapper =
225 static_cast<const PassManagerBuilderWrapper&>(Builder);
226 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
227 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFile));
230 static TargetLibraryInfo *createTLI(llvm::Triple &TargetTriple,
231 const CodeGenOptions &CodeGenOpts) {
232 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
233 if (!CodeGenOpts.SimplifyLibCalls)
234 TLI->disableAllFunctions();
238 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
240 llvm::SymbolRewriter::RewriteDescriptorList DL;
242 llvm::SymbolRewriter::RewriteMapParser MapParser;
243 for (const auto &MapFile : Opts.RewriteMapFiles)
244 MapParser.parse(MapFile, &DL);
246 MPM->add(createRewriteSymbolsPass(DL));
249 void EmitAssemblyHelper::CreatePasses() {
250 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
251 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
253 // Handle disabling of LLVM optimization, where we want to preserve the
254 // internal module before any optimization.
255 if (CodeGenOpts.DisableLLVMOpts) {
257 Inlining = CodeGenOpts.NoInlining;
260 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
261 PMBuilder.OptLevel = OptLevel;
262 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
263 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
264 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
265 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
267 PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
268 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
269 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
270 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
271 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
273 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
274 addAddDiscriminatorsPass);
276 if (!CodeGenOpts.SampleProfileFile.empty())
277 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
278 addSampleProfileLoaderPass);
280 // In ObjC ARC mode, add the main ARC optimization passes.
281 if (LangOpts.ObjCAutoRefCount) {
282 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
283 addObjCARCExpandPass);
284 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
285 addObjCARCAPElimPass);
286 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
290 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
291 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
292 addBoundsCheckingPass);
293 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
294 addBoundsCheckingPass);
297 if (CodeGenOpts.SanitizeCoverage) {
298 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
299 addSanitizerCoveragePass);
300 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
301 addSanitizerCoveragePass);
304 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
305 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
306 addAddressSanitizerPasses);
307 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
308 addAddressSanitizerPasses);
311 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
312 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
313 addMemorySanitizerPass);
314 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
315 addMemorySanitizerPass);
318 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
319 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
320 addThreadSanitizerPass);
321 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
322 addThreadSanitizerPass);
325 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
326 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
327 addDataFlowSanitizerPass);
328 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
329 addDataFlowSanitizerPass);
332 // Figure out TargetLibraryInfo.
333 Triple TargetTriple(TheModule->getTargetTriple());
334 PMBuilder.LibraryInfo = createTLI(TargetTriple, CodeGenOpts);
337 case CodeGenOptions::NoInlining: break;
338 case CodeGenOptions::NormalInlining: {
340 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
343 case CodeGenOptions::OnlyAlwaysInlining:
344 // Respect always_inline.
346 // Do not insert lifetime intrinsics at -O0.
347 PMBuilder.Inliner = createAlwaysInlinerPass(false);
349 PMBuilder.Inliner = createAlwaysInlinerPass();
353 // Set up the per-function pass manager.
354 FunctionPassManager *FPM = getPerFunctionPasses();
355 if (CodeGenOpts.VerifyModule)
356 FPM->add(createVerifierPass());
357 PMBuilder.populateFunctionPassManager(*FPM);
359 // Set up the per-module pass manager.
360 PassManager *MPM = getPerModulePasses();
361 if (!CodeGenOpts.RewriteMapFiles.empty())
362 addSymbolRewriterPass(CodeGenOpts, MPM);
363 if (CodeGenOpts.VerifyModule)
364 MPM->add(createDebugInfoVerifierPass());
366 if (!CodeGenOpts.DisableGCov &&
367 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
368 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
369 // LLVM's -default-gcov-version flag is set to something invalid.
371 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
372 Options.EmitData = CodeGenOpts.EmitGcovArcs;
373 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
374 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
375 Options.NoRedZone = CodeGenOpts.DisableRedZone;
376 Options.FunctionNamesInData =
377 !CodeGenOpts.CoverageNoFunctionNamesInData;
378 MPM->add(createGCOVProfilerPass(Options));
379 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
380 MPM->add(createStripSymbolsPass(true));
383 if (CodeGenOpts.ProfileInstrGenerate) {
384 InstrProfOptions Options;
385 Options.NoRedZone = CodeGenOpts.DisableRedZone;
386 MPM->add(createInstrProfilingPass(Options));
389 PMBuilder.populateModulePassManager(*MPM);
392 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
393 // Create the TargetMachine for generating code.
395 std::string Triple = TheModule->getTargetTriple();
396 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
399 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
404 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
405 .Case("small", llvm::CodeModel::Small)
406 .Case("kernel", llvm::CodeModel::Kernel)
407 .Case("medium", llvm::CodeModel::Medium)
408 .Case("large", llvm::CodeModel::Large)
409 .Case("default", llvm::CodeModel::Default)
411 assert(CodeModel != ~0u && "invalid code model!");
412 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
414 SmallVector<const char *, 16> BackendArgs;
415 BackendArgs.push_back("clang"); // Fake program name.
416 if (!CodeGenOpts.DebugPass.empty()) {
417 BackendArgs.push_back("-debug-pass");
418 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
420 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
421 BackendArgs.push_back("-limit-float-precision");
422 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
424 if (llvm::TimePassesIsEnabled)
425 BackendArgs.push_back("-time-passes");
426 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
427 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
428 if (CodeGenOpts.NoGlobalMerge)
429 BackendArgs.push_back("-enable-global-merge=false");
430 BackendArgs.push_back(nullptr);
431 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
434 std::string FeaturesStr;
435 if (TargetOpts.Features.size()) {
436 SubtargetFeatures Features;
437 for (std::vector<std::string>::const_iterator
438 it = TargetOpts.Features.begin(),
439 ie = TargetOpts.Features.end(); it != ie; ++it)
440 Features.AddFeature(*it);
441 FeaturesStr = Features.getString();
444 llvm::Reloc::Model RM = llvm::Reloc::Default;
445 if (CodeGenOpts.RelocationModel == "static") {
446 RM = llvm::Reloc::Static;
447 } else if (CodeGenOpts.RelocationModel == "pic") {
448 RM = llvm::Reloc::PIC_;
450 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
451 "Invalid PIC model!");
452 RM = llvm::Reloc::DynamicNoPIC;
455 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
456 switch (CodeGenOpts.OptimizationLevel) {
458 case 0: OptLevel = CodeGenOpt::None; break;
459 case 3: OptLevel = CodeGenOpt::Aggressive; break;
462 llvm::TargetOptions Options;
464 Options.ThreadModel =
465 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
466 .Case("posix", llvm::ThreadModel::POSIX)
467 .Case("single", llvm::ThreadModel::Single);
469 if (CodeGenOpts.DisableIntegratedAS)
470 Options.DisableIntegratedAS = true;
472 if (CodeGenOpts.CompressDebugSections)
473 Options.CompressDebugSections = true;
475 // Set frame pointer elimination mode.
476 if (!CodeGenOpts.DisableFPElim) {
477 Options.NoFramePointerElim = false;
478 } else if (CodeGenOpts.OmitLeafFramePointer) {
479 Options.NoFramePointerElim = false;
481 Options.NoFramePointerElim = true;
484 if (CodeGenOpts.UseInitArray)
485 Options.UseInitArray = true;
487 // Set float ABI type.
488 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
489 Options.FloatABIType = llvm::FloatABI::Soft;
490 else if (CodeGenOpts.FloatABI == "hard")
491 Options.FloatABIType = llvm::FloatABI::Hard;
493 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
494 Options.FloatABIType = llvm::FloatABI::Default;
497 // Set FP fusion mode.
498 switch (CodeGenOpts.getFPContractMode()) {
499 case CodeGenOptions::FPC_Off:
500 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
502 case CodeGenOptions::FPC_On:
503 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
505 case CodeGenOptions::FPC_Fast:
506 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
510 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
511 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
512 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
513 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
514 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
515 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
516 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
517 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
518 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
519 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
520 Options.FunctionSections = CodeGenOpts.FunctionSections;
521 Options.DataSections = CodeGenOpts.DataSections;
523 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
524 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
525 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
526 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
527 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
528 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
529 Options.MCOptions.ABIName = TargetOpts.ABI;
531 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
532 FeaturesStr, Options,
538 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
539 formatted_raw_ostream &OS) {
541 // Create the code generator passes.
542 PassManager *PM = getCodeGenPasses();
545 llvm::Triple TargetTriple(TheModule->getTargetTriple());
546 PM->add(createTLI(TargetTriple, CodeGenOpts));
548 // Add Target specific analysis passes.
549 TM->addAnalysisPasses(*PM);
551 // Normal mode, emit a .s or .o file by running the code generator. Note,
552 // this also adds codegenerator level optimization passes.
553 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
554 if (Action == Backend_EmitObj)
555 CGFT = TargetMachine::CGFT_ObjectFile;
556 else if (Action == Backend_EmitMCNull)
557 CGFT = TargetMachine::CGFT_Null;
559 assert(Action == Backend_EmitAssembly && "Invalid action!");
561 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
562 // "codegen" passes so that it isn't run multiple times when there is
563 // inlining happening.
564 if (LangOpts.ObjCAutoRefCount &&
565 CodeGenOpts.OptimizationLevel > 0)
566 PM->add(createObjCARCContractPass());
568 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
569 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
570 Diags.Report(diag::err_fe_unable_to_interface_with_target);
577 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
578 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
579 llvm::formatted_raw_ostream FormattedOS;
581 bool UsesCodeGen = (Action != Backend_EmitNothing &&
582 Action != Backend_EmitBC &&
583 Action != Backend_EmitLL);
585 TM.reset(CreateTargetMachine(UsesCodeGen));
587 if (UsesCodeGen && !TM) return;
591 case Backend_EmitNothing:
595 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
599 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
600 getPerModulePasses()->add(createPrintModulePass(FormattedOS));
604 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
605 if (!AddEmitPasses(Action, FormattedOS))
609 // Before executing passes, print the final values of the LLVM options.
610 cl::PrintOptionValues();
612 // Run passes. For now we do all passes at once, but eventually we
613 // would like to have the option of streaming code generation.
615 if (PerFunctionPasses) {
616 PrettyStackTraceString CrashInfo("Per-function optimization");
618 PerFunctionPasses->doInitialization();
619 for (Module::iterator I = TheModule->begin(),
620 E = TheModule->end(); I != E; ++I)
621 if (!I->isDeclaration())
622 PerFunctionPasses->run(*I);
623 PerFunctionPasses->doFinalization();
626 if (PerModulePasses) {
627 PrettyStackTraceString CrashInfo("Per-module optimization passes");
628 PerModulePasses->run(*TheModule);
632 PrettyStackTraceString CrashInfo("Code generation");
633 CodeGenPasses->run(*TheModule);
637 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
638 const CodeGenOptions &CGOpts,
639 const clang::TargetOptions &TOpts,
640 const LangOptions &LOpts, StringRef TDesc,
641 Module *M, BackendAction Action,
643 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
645 AsmHelper.EmitAssembly(Action, OS);
647 // If an optional clang TargetInfo description string was passed in, use it to
648 // verify the LLVM TargetMachine's DataLayout.
649 if (AsmHelper.TM && !TDesc.empty()) {
650 std::string DLDesc = AsmHelper.TM->getSubtargetImpl()
652 ->getStringRepresentation();
653 if (DLDesc != TDesc) {
654 unsigned DiagID = Diags.getCustomDiagID(
655 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
656 "expected target description '%1'");
657 Diags.Report(DiagID) << DLDesc << TDesc;