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