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