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/Bitcode/BitcodeWriterPass.h" 18 #include "llvm/CodeGen/RegAllocRegistry.h" 19 #include "llvm/CodeGen/SchedulerRegistry.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/IRPrintingPasses.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/IR/Verifier.h" 24 #include "llvm/MC/SubtargetFeature.h" 25 #include "llvm/PassManager.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/FormattedStream.h" 28 #include "llvm/Support/PrettyStackTrace.h" 29 #include "llvm/Support/TargetRegistry.h" 30 #include "llvm/Support/Timer.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Target/TargetLibraryInfo.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Target/TargetOptions.h" 35 #include "llvm/Transforms/IPO.h" 36 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 37 #include "llvm/Transforms/Instrumentation.h" 38 #include "llvm/Transforms/ObjCARC.h" 39 #include "llvm/Transforms/Scalar.h" 40 using namespace clang; 41 using namespace llvm; 42 43 namespace { 44 45 class EmitAssemblyHelper { 46 DiagnosticsEngine &Diags; 47 const CodeGenOptions &CodeGenOpts; 48 const clang::TargetOptions &TargetOpts; 49 const LangOptions &LangOpts; 50 Module *TheModule; 51 52 Timer CodeGenerationTime; 53 54 mutable PassManager *CodeGenPasses; 55 mutable PassManager *PerModulePasses; 56 mutable FunctionPassManager *PerFunctionPasses; 57 58 private: 59 PassManager *getCodeGenPasses() const { 60 if (!CodeGenPasses) { 61 CodeGenPasses = new PassManager(); 62 CodeGenPasses->add(new DataLayout(TheModule)); 63 if (TM) 64 TM->addAnalysisPasses(*CodeGenPasses); 65 } 66 return CodeGenPasses; 67 } 68 69 PassManager *getPerModulePasses() const { 70 if (!PerModulePasses) { 71 PerModulePasses = new PassManager(); 72 PerModulePasses->add(new DataLayout(TheModule)); 73 if (TM) 74 TM->addAnalysisPasses(*PerModulePasses); 75 } 76 return PerModulePasses; 77 } 78 79 FunctionPassManager *getPerFunctionPasses() const { 80 if (!PerFunctionPasses) { 81 PerFunctionPasses = new FunctionPassManager(TheModule); 82 PerFunctionPasses->add(new DataLayout(TheModule)); 83 if (TM) 84 TM->addAnalysisPasses(*PerFunctionPasses); 85 } 86 return PerFunctionPasses; 87 } 88 89 void CreatePasses(); 90 91 /// CreateTargetMachine - Generates the TargetMachine. 92 /// Returns Null if it is unable to create the target machine. 93 /// Some of our clang tests specify triples which are not built 94 /// into clang. This is okay because these tests check the generated 95 /// IR, and they require DataLayout which depends on the triple. 96 /// In this case, we allow this method to fail and not report an error. 97 /// When MustCreateTM is used, we print an error if we are unable to load 98 /// the requested target. 99 TargetMachine *CreateTargetMachine(bool MustCreateTM); 100 101 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR. 102 /// 103 /// \return True on success. 104 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS); 105 106 public: 107 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 108 const CodeGenOptions &CGOpts, 109 const clang::TargetOptions &TOpts, 110 const LangOptions &LOpts, 111 Module *M) 112 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), 113 TheModule(M), CodeGenerationTime("Code Generation Time"), 114 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {} 115 116 ~EmitAssemblyHelper() { 117 delete CodeGenPasses; 118 delete PerModulePasses; 119 delete PerFunctionPasses; 120 if (CodeGenOpts.DisableFree) 121 BuryPointer(TM.take()); 122 } 123 124 llvm::OwningPtr<TargetMachine> TM; 125 126 void EmitAssembly(BackendAction Action, raw_ostream *OS); 127 }; 128 129 // We need this wrapper to access LangOpts and CGOpts from extension functions 130 // that we add to the PassManagerBuilder. 131 class PassManagerBuilderWrapper : public PassManagerBuilder { 132 public: 133 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts, 134 const LangOptions &LangOpts) 135 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {} 136 const CodeGenOptions &getCGOpts() const { return CGOpts; } 137 const LangOptions &getLangOpts() const { return LangOpts; } 138 private: 139 const CodeGenOptions &CGOpts; 140 const LangOptions &LangOpts; 141 }; 142 143 } 144 145 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 146 if (Builder.OptLevel > 0) 147 PM.add(createObjCARCAPElimPass()); 148 } 149 150 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 151 if (Builder.OptLevel > 0) 152 PM.add(createObjCARCExpandPass()); 153 } 154 155 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { 156 if (Builder.OptLevel > 0) 157 PM.add(createObjCARCOptPass()); 158 } 159 160 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder, 161 PassManagerBase &PM) { 162 const PassManagerBuilderWrapper &BuilderWrapper = 163 static_cast<const PassManagerBuilderWrapper &>(Builder); 164 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 165 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile)); 166 } 167 168 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 169 PassManagerBase &PM) { 170 PM.add(createBoundsCheckingPass()); 171 } 172 173 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 174 PassManagerBase &PM) { 175 const PassManagerBuilderWrapper &BuilderWrapper = 176 static_cast<const PassManagerBuilderWrapper&>(Builder); 177 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 178 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 179 PM.add(createAddressSanitizerFunctionPass( 180 LangOpts.Sanitize.InitOrder, 181 LangOpts.Sanitize.UseAfterReturn, 182 LangOpts.Sanitize.UseAfterScope, 183 CGOpts.SanitizerBlacklistFile)); 184 PM.add(createAddressSanitizerModulePass( 185 LangOpts.Sanitize.InitOrder, 186 CGOpts.SanitizerBlacklistFile)); 187 } 188 189 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 190 PassManagerBase &PM) { 191 const PassManagerBuilderWrapper &BuilderWrapper = 192 static_cast<const PassManagerBuilderWrapper&>(Builder); 193 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 194 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins, 195 CGOpts.SanitizerBlacklistFile)); 196 197 // MemorySanitizer inserts complex instrumentation that mostly follows 198 // the logic of the original code, but operates on "shadow" values. 199 // It can benefit from re-running some general purpose optimization passes. 200 if (Builder.OptLevel > 0) { 201 PM.add(createEarlyCSEPass()); 202 PM.add(createReassociatePass()); 203 PM.add(createLICMPass()); 204 PM.add(createGVNPass()); 205 PM.add(createInstructionCombiningPass()); 206 PM.add(createDeadStoreEliminationPass()); 207 } 208 } 209 210 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 211 PassManagerBase &PM) { 212 const PassManagerBuilderWrapper &BuilderWrapper = 213 static_cast<const PassManagerBuilderWrapper&>(Builder); 214 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 215 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile)); 216 } 217 218 static void addDataFlowSanitizerPass(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(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile)); 224 } 225 226 void EmitAssemblyHelper::CreatePasses() { 227 unsigned OptLevel = CodeGenOpts.OptimizationLevel; 228 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining(); 229 230 // Handle disabling of LLVM optimization, where we want to preserve the 231 // internal module before any optimization. 232 if (CodeGenOpts.DisableLLVMOpts) { 233 OptLevel = 0; 234 Inlining = CodeGenOpts.NoInlining; 235 } 236 237 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 238 PMBuilder.OptLevel = OptLevel; 239 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 240 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 241 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 242 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 243 244 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime; 245 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 246 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 247 248 if (!CodeGenOpts.SampleProfileFile.empty()) 249 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 250 addSampleProfileLoaderPass); 251 252 // In ObjC ARC mode, add the main ARC optimization passes. 253 if (LangOpts.ObjCAutoRefCount) { 254 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 255 addObjCARCExpandPass); 256 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 257 addObjCARCAPElimPass); 258 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 259 addObjCARCOptPass); 260 } 261 262 if (LangOpts.Sanitize.LocalBounds) { 263 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 264 addBoundsCheckingPass); 265 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 266 addBoundsCheckingPass); 267 } 268 269 if (LangOpts.Sanitize.Address) { 270 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 271 addAddressSanitizerPasses); 272 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 273 addAddressSanitizerPasses); 274 } 275 276 if (LangOpts.Sanitize.Memory) { 277 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 278 addMemorySanitizerPass); 279 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 280 addMemorySanitizerPass); 281 } 282 283 if (LangOpts.Sanitize.Thread) { 284 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 285 addThreadSanitizerPass); 286 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 287 addThreadSanitizerPass); 288 } 289 290 if (LangOpts.Sanitize.DataFlow) { 291 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 292 addDataFlowSanitizerPass); 293 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 294 addDataFlowSanitizerPass); 295 } 296 297 // Figure out TargetLibraryInfo. 298 Triple TargetTriple(TheModule->getTargetTriple()); 299 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple); 300 if (!CodeGenOpts.SimplifyLibCalls) 301 PMBuilder.LibraryInfo->disableAllFunctions(); 302 303 switch (Inlining) { 304 case CodeGenOptions::NoInlining: break; 305 case CodeGenOptions::NormalInlining: { 306 // FIXME: Derive these constants in a principled fashion. 307 unsigned Threshold = 225; 308 if (CodeGenOpts.OptimizeSize == 1) // -Os 309 Threshold = 75; 310 else if (CodeGenOpts.OptimizeSize == 2) // -Oz 311 Threshold = 25; 312 else if (OptLevel > 2) 313 Threshold = 275; 314 PMBuilder.Inliner = createFunctionInliningPass(Threshold); 315 break; 316 } 317 case CodeGenOptions::OnlyAlwaysInlining: 318 // Respect always_inline. 319 if (OptLevel == 0) 320 // Do not insert lifetime intrinsics at -O0. 321 PMBuilder.Inliner = createAlwaysInlinerPass(false); 322 else 323 PMBuilder.Inliner = createAlwaysInlinerPass(); 324 break; 325 } 326 327 // Set up the per-function pass manager. 328 FunctionPassManager *FPM = getPerFunctionPasses(); 329 if (CodeGenOpts.VerifyModule) 330 FPM->add(createVerifierPass()); 331 PMBuilder.populateFunctionPassManager(*FPM); 332 333 // Set up the per-module pass manager. 334 PassManager *MPM = getPerModulePasses(); 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 0; 365 } 366 367 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just 368 // being gross, this is also totally broken if we ever care about 369 // concurrency. 370 371 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose); 372 373 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections); 374 TargetMachine::setDataSections (CodeGenOpts.DataSections); 375 376 // FIXME: Parse this earlier. 377 llvm::CodeModel::Model CM; 378 if (CodeGenOpts.CodeModel == "small") { 379 CM = llvm::CodeModel::Small; 380 } else if (CodeGenOpts.CodeModel == "kernel") { 381 CM = llvm::CodeModel::Kernel; 382 } else if (CodeGenOpts.CodeModel == "medium") { 383 CM = llvm::CodeModel::Medium; 384 } else if (CodeGenOpts.CodeModel == "large") { 385 CM = llvm::CodeModel::Large; 386 } else { 387 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!"); 388 CM = llvm::CodeModel::Default; 389 } 390 391 SmallVector<const char *, 16> BackendArgs; 392 BackendArgs.push_back("clang"); // Fake program name. 393 if (!CodeGenOpts.DebugPass.empty()) { 394 BackendArgs.push_back("-debug-pass"); 395 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 396 } 397 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 398 BackendArgs.push_back("-limit-float-precision"); 399 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 400 } 401 if (llvm::TimePassesIsEnabled) 402 BackendArgs.push_back("-time-passes"); 403 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i) 404 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str()); 405 if (CodeGenOpts.NoGlobalMerge) 406 BackendArgs.push_back("-global-merge=false"); 407 BackendArgs.push_back(0); 408 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 409 BackendArgs.data()); 410 411 std::string FeaturesStr; 412 if (TargetOpts.Features.size()) { 413 SubtargetFeatures Features; 414 for (std::vector<std::string>::const_iterator 415 it = TargetOpts.Features.begin(), 416 ie = TargetOpts.Features.end(); it != ie; ++it) 417 Features.AddFeature(*it); 418 FeaturesStr = Features.getString(); 419 } 420 421 llvm::Reloc::Model RM = llvm::Reloc::Default; 422 if (CodeGenOpts.RelocationModel == "static") { 423 RM = llvm::Reloc::Static; 424 } else if (CodeGenOpts.RelocationModel == "pic") { 425 RM = llvm::Reloc::PIC_; 426 } else { 427 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && 428 "Invalid PIC model!"); 429 RM = llvm::Reloc::DynamicNoPIC; 430 } 431 432 CodeGenOpt::Level OptLevel = CodeGenOpt::Default; 433 switch (CodeGenOpts.OptimizationLevel) { 434 default: break; 435 case 0: OptLevel = CodeGenOpt::None; break; 436 case 3: OptLevel = CodeGenOpt::Aggressive; break; 437 } 438 439 llvm::TargetOptions Options; 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.EnableSegmentedStacks = CodeGenOpts.EnableSegmentedStacks; 487 488 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU, 489 FeaturesStr, Options, 490 RM, CM, OptLevel); 491 492 if (CodeGenOpts.RelaxAll) 493 TM->setMCRelaxAll(true); 494 if (CodeGenOpts.SaveTempLabels) 495 TM->setMCSaveTempLabels(true); 496 if (CodeGenOpts.NoDwarf2CFIAsm) 497 TM->setMCUseCFI(false); 498 if (!CodeGenOpts.NoDwarfDirectoryAsm) 499 TM->setMCUseDwarfDirectory(true); 500 if (CodeGenOpts.NoExecStack) 501 TM->setMCNoExecStack(true); 502 503 return TM; 504 } 505 506 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action, 507 formatted_raw_ostream &OS) { 508 509 // Create the code generator passes. 510 PassManager *PM = getCodeGenPasses(); 511 512 // Add LibraryInfo. 513 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 514 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple); 515 if (!CodeGenOpts.SimplifyLibCalls) 516 TLI->disableAllFunctions(); 517 PM->add(TLI); 518 519 // Add Target specific analysis passes. 520 TM->addAnalysisPasses(*PM); 521 522 // Normal mode, emit a .s or .o file by running the code generator. Note, 523 // this also adds codegenerator level optimization passes. 524 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 525 if (Action == Backend_EmitObj) 526 CGFT = TargetMachine::CGFT_ObjectFile; 527 else if (Action == Backend_EmitMCNull) 528 CGFT = TargetMachine::CGFT_Null; 529 else 530 assert(Action == Backend_EmitAssembly && "Invalid action!"); 531 532 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 533 // "codegen" passes so that it isn't run multiple times when there is 534 // inlining happening. 535 if (LangOpts.ObjCAutoRefCount && 536 CodeGenOpts.OptimizationLevel > 0) 537 PM->add(createObjCARCContractPass()); 538 539 if (TM->addPassesToEmitFile(*PM, OS, CGFT, 540 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 541 Diags.Report(diag::err_fe_unable_to_interface_with_target); 542 return false; 543 } 544 545 return true; 546 } 547 548 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) { 549 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0); 550 llvm::formatted_raw_ostream FormattedOS; 551 552 bool UsesCodeGen = (Action != Backend_EmitNothing && 553 Action != Backend_EmitBC && 554 Action != Backend_EmitLL); 555 if (!TM) 556 TM.reset(CreateTargetMachine(UsesCodeGen)); 557 558 if (UsesCodeGen && !TM) return; 559 CreatePasses(); 560 561 switch (Action) { 562 case Backend_EmitNothing: 563 break; 564 565 case Backend_EmitBC: 566 getPerModulePasses()->add(createBitcodeWriterPass(*OS)); 567 break; 568 569 case Backend_EmitLL: 570 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM); 571 getPerModulePasses()->add(createPrintModulePass(FormattedOS)); 572 break; 573 574 default: 575 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM); 576 if (!AddEmitPasses(Action, FormattedOS)) 577 return; 578 } 579 580 // Before executing passes, print the final values of the LLVM options. 581 cl::PrintOptionValues(); 582 583 // Run passes. For now we do all passes at once, but eventually we 584 // would like to have the option of streaming code generation. 585 586 if (PerFunctionPasses) { 587 PrettyStackTraceString CrashInfo("Per-function optimization"); 588 589 PerFunctionPasses->doInitialization(); 590 for (Module::iterator I = TheModule->begin(), 591 E = TheModule->end(); I != E; ++I) 592 if (!I->isDeclaration()) 593 PerFunctionPasses->run(*I); 594 PerFunctionPasses->doFinalization(); 595 } 596 597 if (PerModulePasses) { 598 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 599 PerModulePasses->run(*TheModule); 600 } 601 602 if (CodeGenPasses) { 603 PrettyStackTraceString CrashInfo("Code generation"); 604 CodeGenPasses->run(*TheModule); 605 } 606 } 607 608 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 609 const CodeGenOptions &CGOpts, 610 const clang::TargetOptions &TOpts, 611 const LangOptions &LOpts, StringRef TDesc, 612 Module *M, BackendAction Action, 613 raw_ostream *OS) { 614 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M); 615 616 AsmHelper.EmitAssembly(Action, OS); 617 618 // If an optional clang TargetInfo description string was passed in, use it to 619 // verify the LLVM TargetMachine's DataLayout. 620 if (AsmHelper.TM && !TDesc.empty()) { 621 std::string DLDesc = 622 AsmHelper.TM->getDataLayout()->getStringRepresentation(); 623 if (DLDesc != TDesc) { 624 unsigned DiagID = Diags.getCustomDiagID( 625 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 626 "expected target description '%1'"); 627 Diags.Report(DiagID) << DLDesc << TDesc; 628 } 629 } 630 } 631