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