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