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