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 "clang/Lex/HeaderSearchOptions.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitcodeWriter.h" 26 #include "llvm/Bitcode/BitcodeWriterPass.h" 27 #include "llvm/CodeGen/RegAllocRegistry.h" 28 #include "llvm/CodeGen/SchedulerRegistry.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/IRPrintingPasses.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSummaryIndex.h" 34 #include "llvm/IR/Verifier.h" 35 #include "llvm/LTO/LTOBackend.h" 36 #include "llvm/MC/MCAsmInfo.h" 37 #include "llvm/MC/SubtargetFeature.h" 38 #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 39 #include "llvm/Passes/PassBuilder.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/PrettyStackTrace.h" 43 #include "llvm/Support/TargetRegistry.h" 44 #include "llvm/Support/Timer.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include "llvm/Target/TargetSubtargetInfo.h" 49 #include "llvm/Transforms/Coroutines.h" 50 #include "llvm/Transforms/IPO.h" 51 #include "llvm/Transforms/IPO/AlwaysInliner.h" 52 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 53 #include "llvm/Transforms/Instrumentation.h" 54 #include "llvm/Transforms/ObjCARC.h" 55 #include "llvm/Transforms/Scalar.h" 56 #include "llvm/Transforms/Scalar/GVN.h" 57 #include "llvm/Transforms/Utils/SymbolRewriter.h" 58 #include <memory> 59 using namespace clang; 60 using namespace llvm; 61 62 namespace { 63 64 class EmitAssemblyHelper { 65 DiagnosticsEngine &Diags; 66 const HeaderSearchOptions &HSOpts; 67 const CodeGenOptions &CodeGenOpts; 68 const clang::TargetOptions &TargetOpts; 69 const LangOptions &LangOpts; 70 Module *TheModule; 71 72 Timer CodeGenerationTime; 73 74 std::unique_ptr<raw_pwrite_stream> OS; 75 76 private: 77 TargetIRAnalysis getTargetIRAnalysis() const { 78 if (TM) 79 return TM->getTargetIRAnalysis(); 80 81 return TargetIRAnalysis(); 82 } 83 84 /// Set LLVM command line options passed through -backend-option. 85 void setCommandLineOpts(); 86 87 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); 88 89 /// Generates the TargetMachine. 90 /// Leaves TM unchanged if it is unable to create the target machine. 91 /// Some of our clang tests specify triples which are not built 92 /// into clang. This is okay because these tests check the generated 93 /// IR, and they require DataLayout which depends on the triple. 94 /// In this case, we allow this method to fail and not report an error. 95 /// When MustCreateTM is used, we print an error if we are unable to load 96 /// the requested target. 97 void CreateTargetMachine(bool MustCreateTM); 98 99 /// Add passes necessary to emit assembly or LLVM IR. 100 /// 101 /// \return True on success. 102 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, 103 raw_pwrite_stream &OS); 104 105 public: 106 EmitAssemblyHelper(DiagnosticsEngine &_Diags, 107 const HeaderSearchOptions &HeaderSearchOpts, 108 const CodeGenOptions &CGOpts, 109 const clang::TargetOptions &TOpts, 110 const LangOptions &LOpts, Module *M) 111 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), 112 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), 113 CodeGenerationTime("codegen", "Code Generation Time") {} 114 115 ~EmitAssemblyHelper() { 116 if (CodeGenOpts.DisableFree) 117 BuryPointer(std::move(TM)); 118 } 119 120 std::unique_ptr<TargetMachine> TM; 121 122 void EmitAssembly(BackendAction Action, 123 std::unique_ptr<raw_pwrite_stream> OS); 124 125 void EmitAssemblyWithNewPassManager(BackendAction Action, 126 std::unique_ptr<raw_pwrite_stream> 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 addAddDiscriminatorsPass(const PassManagerBuilder &Builder, 161 legacy::PassManagerBase &PM) { 162 PM.add(createAddDiscriminatorsPass()); 163 } 164 165 static void addBoundsCheckingPass(const PassManagerBuilder &Builder, 166 legacy::PassManagerBase &PM) { 167 PM.add(createBoundsCheckingPass()); 168 } 169 170 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, 171 legacy::PassManagerBase &PM) { 172 const PassManagerBuilderWrapper &BuilderWrapper = 173 static_cast<const PassManagerBuilderWrapper&>(Builder); 174 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 175 SanitizerCoverageOptions Opts; 176 Opts.CoverageType = 177 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType); 178 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; 179 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; 180 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; 181 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; 182 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; 183 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; 184 Opts.TracePC = CGOpts.SanitizeCoverageTracePC; 185 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; 186 PM.add(createSanitizerCoverageModulePass(Opts)); 187 } 188 189 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, 190 legacy::PassManagerBase &PM) { 191 const PassManagerBuilderWrapper &BuilderWrapper = 192 static_cast<const PassManagerBuilderWrapper&>(Builder); 193 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 194 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); 195 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; 196 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, 197 UseAfterScope)); 198 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover)); 199 } 200 201 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, 202 legacy::PassManagerBase &PM) { 203 PM.add(createAddressSanitizerFunctionPass( 204 /*CompileKernel*/ true, 205 /*Recover*/ true, /*UseAfterScope*/ false)); 206 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true, 207 /*Recover*/true)); 208 } 209 210 static void addMemorySanitizerPass(const PassManagerBuilder &Builder, 211 legacy::PassManagerBase &PM) { 212 const PassManagerBuilderWrapper &BuilderWrapper = 213 static_cast<const PassManagerBuilderWrapper&>(Builder); 214 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); 215 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; 216 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); 217 PM.add(createMemorySanitizerPass(TrackOrigins, Recover)); 218 219 // MemorySanitizer inserts complex instrumentation that mostly follows 220 // the logic of the original code, but operates on "shadow" values. 221 // It can benefit from re-running some general purpose optimization passes. 222 if (Builder.OptLevel > 0) { 223 PM.add(createEarlyCSEPass()); 224 PM.add(createReassociatePass()); 225 PM.add(createLICMPass()); 226 PM.add(createGVNPass()); 227 PM.add(createInstructionCombiningPass()); 228 PM.add(createDeadStoreEliminationPass()); 229 } 230 } 231 232 static void addThreadSanitizerPass(const PassManagerBuilder &Builder, 233 legacy::PassManagerBase &PM) { 234 PM.add(createThreadSanitizerPass()); 235 } 236 237 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, 238 legacy::PassManagerBase &PM) { 239 const PassManagerBuilderWrapper &BuilderWrapper = 240 static_cast<const PassManagerBuilderWrapper&>(Builder); 241 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 242 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); 243 } 244 245 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder, 246 legacy::PassManagerBase &PM) { 247 const PassManagerBuilderWrapper &BuilderWrapper = 248 static_cast<const PassManagerBuilderWrapper&>(Builder); 249 const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); 250 EfficiencySanitizerOptions Opts; 251 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag)) 252 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag; 253 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet)) 254 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet; 255 PM.add(createEfficiencySanitizerPass(Opts)); 256 } 257 258 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, 259 const CodeGenOptions &CodeGenOpts) { 260 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); 261 if (!CodeGenOpts.SimplifyLibCalls) 262 TLII->disableAllFunctions(); 263 else { 264 // Disable individual libc/libm calls in TargetLibraryInfo. 265 LibFunc F; 266 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs()) 267 if (TLII->getLibFunc(FuncName, F)) 268 TLII->setUnavailable(F); 269 } 270 271 switch (CodeGenOpts.getVecLib()) { 272 case CodeGenOptions::Accelerate: 273 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); 274 break; 275 case CodeGenOptions::SVML: 276 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); 277 break; 278 default: 279 break; 280 } 281 return TLII; 282 } 283 284 static void addSymbolRewriterPass(const CodeGenOptions &Opts, 285 legacy::PassManager *MPM) { 286 llvm::SymbolRewriter::RewriteDescriptorList DL; 287 288 llvm::SymbolRewriter::RewriteMapParser MapParser; 289 for (const auto &MapFile : Opts.RewriteMapFiles) 290 MapParser.parse(MapFile, &DL); 291 292 MPM->add(createRewriteSymbolsPass(DL)); 293 } 294 295 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, 296 legacy::FunctionPassManager &FPM) { 297 // Handle disabling of all LLVM passes, where we want to preserve the 298 // internal module before any optimization. 299 if (CodeGenOpts.DisableLLVMPasses) 300 return; 301 302 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts); 303 304 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM 305 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) 306 // are inserted before PMBuilder ones - they'd get the default-constructed 307 // TLI with an unknown target otherwise. 308 Triple TargetTriple(TheModule->getTargetTriple()); 309 std::unique_ptr<TargetLibraryInfoImpl> TLII( 310 createTLII(TargetTriple, CodeGenOpts)); 311 312 // At O0 and O1 we only run the always inliner which is more efficient. At 313 // higher optimization levels we run the normal inliner. 314 if (CodeGenOpts.OptimizationLevel <= 1) { 315 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 && 316 !CodeGenOpts.DisableLifetimeMarkers); 317 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); 318 } else { 319 PMBuilder.Inliner = createFunctionInliningPass( 320 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize); 321 } 322 323 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; 324 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; 325 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB; 326 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; 327 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; 328 329 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; 330 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; 331 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex; 332 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; 333 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; 334 335 MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 336 337 if (TM) 338 TM->adjustPassManager(PMBuilder); 339 340 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 341 addAddDiscriminatorsPass); 342 343 // In ObjC ARC mode, add the main ARC optimization passes. 344 if (LangOpts.ObjCAutoRefCount) { 345 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, 346 addObjCARCExpandPass); 347 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, 348 addObjCARCAPElimPass); 349 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 350 addObjCARCOptPass); 351 } 352 353 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { 354 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, 355 addBoundsCheckingPass); 356 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 357 addBoundsCheckingPass); 358 } 359 360 if (CodeGenOpts.SanitizeCoverageType || 361 CodeGenOpts.SanitizeCoverageIndirectCalls || 362 CodeGenOpts.SanitizeCoverageTraceCmp) { 363 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 364 addSanitizerCoveragePass); 365 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 366 addSanitizerCoveragePass); 367 } 368 369 if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 370 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 371 addAddressSanitizerPasses); 372 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 373 addAddressSanitizerPasses); 374 } 375 376 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { 377 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 378 addKernelAddressSanitizerPasses); 379 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 380 addKernelAddressSanitizerPasses); 381 } 382 383 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { 384 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 385 addMemorySanitizerPass); 386 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 387 addMemorySanitizerPass); 388 } 389 390 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { 391 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 392 addThreadSanitizerPass); 393 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 394 addThreadSanitizerPass); 395 } 396 397 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { 398 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 399 addDataFlowSanitizerPass); 400 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 401 addDataFlowSanitizerPass); 402 } 403 404 if (LangOpts.CoroutinesTS) 405 addCoroutinePassesToExtensionPoints(PMBuilder); 406 407 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) { 408 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, 409 addEfficiencySanitizerPass); 410 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, 411 addEfficiencySanitizerPass); 412 } 413 414 // Set up the per-function pass manager. 415 FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); 416 if (CodeGenOpts.VerifyModule) 417 FPM.add(createVerifierPass()); 418 419 // Set up the per-module pass manager. 420 if (!CodeGenOpts.RewriteMapFiles.empty()) 421 addSymbolRewriterPass(CodeGenOpts, &MPM); 422 423 if (!CodeGenOpts.DisableGCov && 424 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) { 425 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if 426 // LLVM's -default-gcov-version flag is set to something invalid. 427 GCOVOptions Options; 428 Options.EmitNotes = CodeGenOpts.EmitGcovNotes; 429 Options.EmitData = CodeGenOpts.EmitGcovArcs; 430 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4); 431 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; 432 Options.NoRedZone = CodeGenOpts.DisableRedZone; 433 Options.FunctionNamesInData = 434 !CodeGenOpts.CoverageNoFunctionNamesInData; 435 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; 436 MPM.add(createGCOVProfilerPass(Options)); 437 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) 438 MPM.add(createStripSymbolsPass(true)); 439 } 440 441 if (CodeGenOpts.hasProfileClangInstr()) { 442 InstrProfOptions Options; 443 Options.NoRedZone = CodeGenOpts.DisableRedZone; 444 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; 445 MPM.add(createInstrProfilingLegacyPass(Options)); 446 } 447 if (CodeGenOpts.hasProfileIRInstr()) { 448 PMBuilder.EnablePGOInstrGen = true; 449 if (!CodeGenOpts.InstrProfileOutput.empty()) 450 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; 451 else 452 PMBuilder.PGOInstrGen = "default_%m.profraw"; 453 } 454 if (CodeGenOpts.hasProfileIRUse()) 455 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; 456 457 if (!CodeGenOpts.SampleProfileFile.empty()) 458 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; 459 460 PMBuilder.populateFunctionPassManager(FPM); 461 PMBuilder.populateModulePassManager(MPM); 462 } 463 464 void EmitAssemblyHelper::setCommandLineOpts() { 465 SmallVector<const char *, 16> BackendArgs; 466 BackendArgs.push_back("clang"); // Fake program name. 467 if (!CodeGenOpts.DebugPass.empty()) { 468 BackendArgs.push_back("-debug-pass"); 469 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); 470 } 471 if (!CodeGenOpts.LimitFloatPrecision.empty()) { 472 BackendArgs.push_back("-limit-float-precision"); 473 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); 474 } 475 for (const std::string &BackendOption : CodeGenOpts.BackendOptions) 476 BackendArgs.push_back(BackendOption.c_str()); 477 BackendArgs.push_back(nullptr); 478 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, 479 BackendArgs.data()); 480 } 481 482 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { 483 // Create the TargetMachine for generating code. 484 std::string Error; 485 std::string Triple = TheModule->getTargetTriple(); 486 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); 487 if (!TheTarget) { 488 if (MustCreateTM) 489 Diags.Report(diag::err_fe_unable_to_create_target) << Error; 490 return; 491 } 492 493 unsigned CodeModel = 494 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel) 495 .Case("small", llvm::CodeModel::Small) 496 .Case("kernel", llvm::CodeModel::Kernel) 497 .Case("medium", llvm::CodeModel::Medium) 498 .Case("large", llvm::CodeModel::Large) 499 .Case("default", llvm::CodeModel::Default) 500 .Default(~0u); 501 assert(CodeModel != ~0u && "invalid code model!"); 502 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel); 503 504 std::string FeaturesStr = 505 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ","); 506 507 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp. 508 llvm::Optional<llvm::Reloc::Model> RM; 509 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel) 510 .Case("static", llvm::Reloc::Static) 511 .Case("pic", llvm::Reloc::PIC_) 512 .Case("ropi", llvm::Reloc::ROPI) 513 .Case("rwpi", llvm::Reloc::RWPI) 514 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 515 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC); 516 assert(RM.hasValue() && "invalid PIC model!"); 517 518 CodeGenOpt::Level OptLevel; 519 switch (CodeGenOpts.OptimizationLevel) { 520 default: 521 llvm_unreachable("Invalid optimization level!"); 522 case 0: 523 OptLevel = CodeGenOpt::None; 524 break; 525 case 1: 526 OptLevel = CodeGenOpt::Less; 527 break; 528 case 2: 529 OptLevel = CodeGenOpt::Default; 530 break; // O2/Os/Oz 531 case 3: 532 OptLevel = CodeGenOpt::Aggressive; 533 break; 534 } 535 536 llvm::TargetOptions Options; 537 538 Options.ThreadModel = 539 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel) 540 .Case("posix", llvm::ThreadModel::POSIX) 541 .Case("single", llvm::ThreadModel::Single); 542 543 // Set float ABI type. 544 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" || 545 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) && 546 "Invalid Floating Point ABI!"); 547 Options.FloatABIType = 548 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI) 549 .Case("soft", llvm::FloatABI::Soft) 550 .Case("softfp", llvm::FloatABI::Soft) 551 .Case("hard", llvm::FloatABI::Hard) 552 .Default(llvm::FloatABI::Default); 553 554 // Set FP fusion mode. 555 switch (CodeGenOpts.getFPContractMode()) { 556 case CodeGenOptions::FPC_Off: 557 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict; 558 break; 559 case CodeGenOptions::FPC_On: 560 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; 561 break; 562 case CodeGenOptions::FPC_Fast: 563 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; 564 break; 565 } 566 567 Options.UseInitArray = CodeGenOpts.UseInitArray; 568 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; 569 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections; 570 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; 571 Options.DebugInfoForProfiling = CodeGenOpts.DebugInfoForProfiling; 572 573 // Set EABI version. 574 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion) 575 .Case("4", llvm::EABI::EABI4) 576 .Case("5", llvm::EABI::EABI5) 577 .Case("gnu", llvm::EABI::GNU) 578 .Default(llvm::EABI::Default); 579 580 if (LangOpts.SjLjExceptions) 581 Options.ExceptionModel = llvm::ExceptionHandling::SjLj; 582 583 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD; 584 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; 585 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; 586 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; 587 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; 588 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; 589 Options.FunctionSections = CodeGenOpts.FunctionSections; 590 Options.DataSections = CodeGenOpts.DataSections; 591 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; 592 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; 593 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); 594 595 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; 596 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; 597 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; 598 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; 599 Options.MCOptions.MCIncrementalLinkerCompatible = 600 CodeGenOpts.IncrementalLinkerCompatible; 601 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations; 602 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; 603 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; 604 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; 605 Options.MCOptions.ABIName = TargetOpts.ABI; 606 for (const auto &Entry : HSOpts.UserEntries) 607 if (!Entry.IsFramework && 608 (Entry.Group == frontend::IncludeDirGroup::Quoted || 609 Entry.Group == frontend::IncludeDirGroup::Angled || 610 Entry.Group == frontend::IncludeDirGroup::System)) 611 Options.MCOptions.IASSearchPaths.push_back( 612 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); 613 614 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, 615 Options, RM, CM, OptLevel)); 616 } 617 618 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, 619 BackendAction Action, 620 raw_pwrite_stream &OS) { 621 // Add LibraryInfo. 622 llvm::Triple TargetTriple(TheModule->getTargetTriple()); 623 std::unique_ptr<TargetLibraryInfoImpl> TLII( 624 createTLII(TargetTriple, CodeGenOpts)); 625 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); 626 627 // Normal mode, emit a .s or .o file by running the code generator. Note, 628 // this also adds codegenerator level optimization passes. 629 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; 630 if (Action == Backend_EmitObj) 631 CGFT = TargetMachine::CGFT_ObjectFile; 632 else if (Action == Backend_EmitMCNull) 633 CGFT = TargetMachine::CGFT_Null; 634 else 635 assert(Action == Backend_EmitAssembly && "Invalid action!"); 636 637 // Add ObjC ARC final-cleanup optimizations. This is done as part of the 638 // "codegen" passes so that it isn't run multiple times when there is 639 // inlining happening. 640 if (CodeGenOpts.OptimizationLevel > 0) 641 CodeGenPasses.add(createObjCARCContractPass()); 642 643 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT, 644 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { 645 Diags.Report(diag::err_fe_unable_to_interface_with_target); 646 return false; 647 } 648 649 return true; 650 } 651 652 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, 653 std::unique_ptr<raw_pwrite_stream> OS) { 654 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 655 656 setCommandLineOpts(); 657 658 bool UsesCodeGen = (Action != Backend_EmitNothing && 659 Action != Backend_EmitBC && 660 Action != Backend_EmitLL); 661 CreateTargetMachine(UsesCodeGen); 662 663 if (UsesCodeGen && !TM) 664 return; 665 if (TM) 666 TheModule->setDataLayout(TM->createDataLayout()); 667 668 legacy::PassManager PerModulePasses; 669 PerModulePasses.add( 670 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 671 672 legacy::FunctionPassManager PerFunctionPasses(TheModule); 673 PerFunctionPasses.add( 674 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 675 676 CreatePasses(PerModulePasses, PerFunctionPasses); 677 678 legacy::PassManager CodeGenPasses; 679 CodeGenPasses.add( 680 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 681 682 switch (Action) { 683 case Backend_EmitNothing: 684 break; 685 686 case Backend_EmitBC: 687 if (CodeGenOpts.EmitSummaryIndex) 688 PerModulePasses.add(createWriteThinLTOBitcodePass(*OS)); 689 else 690 PerModulePasses.add( 691 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists)); 692 break; 693 694 case Backend_EmitLL: 695 PerModulePasses.add( 696 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 697 break; 698 699 default: 700 if (!AddEmitPasses(CodeGenPasses, Action, *OS)) 701 return; 702 } 703 704 // Before executing passes, print the final values of the LLVM options. 705 cl::PrintOptionValues(); 706 707 // Run passes. For now we do all passes at once, but eventually we 708 // would like to have the option of streaming code generation. 709 710 { 711 PrettyStackTraceString CrashInfo("Per-function optimization"); 712 713 PerFunctionPasses.doInitialization(); 714 for (Function &F : *TheModule) 715 if (!F.isDeclaration()) 716 PerFunctionPasses.run(F); 717 PerFunctionPasses.doFinalization(); 718 } 719 720 { 721 PrettyStackTraceString CrashInfo("Per-module optimization passes"); 722 PerModulePasses.run(*TheModule); 723 } 724 725 { 726 PrettyStackTraceString CrashInfo("Code generation"); 727 CodeGenPasses.run(*TheModule); 728 } 729 } 730 731 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { 732 switch (Opts.OptimizationLevel) { 733 default: 734 llvm_unreachable("Invalid optimization level!"); 735 736 case 1: 737 return PassBuilder::O1; 738 739 case 2: 740 switch (Opts.OptimizeSize) { 741 default: 742 llvm_unreachable("Invalide optimization level for size!"); 743 744 case 0: 745 return PassBuilder::O2; 746 747 case 1: 748 return PassBuilder::Os; 749 750 case 2: 751 return PassBuilder::Oz; 752 } 753 754 case 3: 755 return PassBuilder::O3; 756 } 757 } 758 759 /// A clean version of `EmitAssembly` that uses the new pass manager. 760 /// 761 /// Not all features are currently supported in this system, but where 762 /// necessary it falls back to the legacy pass manager to at least provide 763 /// basic functionality. 764 /// 765 /// This API is planned to have its functionality finished and then to replace 766 /// `EmitAssembly` at some point in the future when the default switches. 767 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( 768 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) { 769 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr); 770 setCommandLineOpts(); 771 772 // The new pass manager always makes a target machine available to passes 773 // during construction. 774 CreateTargetMachine(/*MustCreateTM*/ true); 775 if (!TM) 776 // This will already be diagnosed, just bail. 777 return; 778 TheModule->setDataLayout(TM->createDataLayout()); 779 780 PassBuilder PB(TM.get()); 781 782 LoopAnalysisManager LAM; 783 FunctionAnalysisManager FAM; 784 CGSCCAnalysisManager CGAM; 785 ModuleAnalysisManager MAM; 786 787 // Register the AA manager first so that our version is the one used. 788 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); 789 790 // Register all the basic analyses with the managers. 791 PB.registerModuleAnalyses(MAM); 792 PB.registerCGSCCAnalyses(CGAM); 793 PB.registerFunctionAnalyses(FAM); 794 PB.registerLoopAnalyses(LAM); 795 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 796 797 ModulePassManager MPM; 798 799 if (!CodeGenOpts.DisableLLVMPasses) { 800 if (CodeGenOpts.OptimizationLevel == 0) { 801 // Build a minimal pipeline based on the semantics required by Clang, 802 // which is just that always inlining occurs. 803 MPM.addPass(AlwaysInlinerPass()); 804 } else { 805 // Otherwise, use the default pass pipeline. We also have to map our 806 // optimization levels into one of the distinct levels used to configure 807 // the pipeline. 808 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); 809 810 MPM = PB.buildPerModuleDefaultPipeline(Level); 811 } 812 } 813 814 // FIXME: We still use the legacy pass manager to do code generation. We 815 // create that pass manager here and use it as needed below. 816 legacy::PassManager CodeGenPasses; 817 bool NeedCodeGen = false; 818 819 // Append any output we need to the pass manager. 820 switch (Action) { 821 case Backend_EmitNothing: 822 break; 823 824 case Backend_EmitBC: 825 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 826 CodeGenOpts.EmitSummaryIndex, 827 CodeGenOpts.EmitSummaryIndex)); 828 break; 829 830 case Backend_EmitLL: 831 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists)); 832 break; 833 834 case Backend_EmitAssembly: 835 case Backend_EmitMCNull: 836 case Backend_EmitObj: 837 NeedCodeGen = true; 838 CodeGenPasses.add( 839 createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); 840 if (!AddEmitPasses(CodeGenPasses, Action, *OS)) 841 // FIXME: Should we handle this error differently? 842 return; 843 break; 844 } 845 846 // Before executing passes, print the final values of the LLVM options. 847 cl::PrintOptionValues(); 848 849 // Now that we have all of the passes ready, run them. 850 { 851 PrettyStackTraceString CrashInfo("Optimizer"); 852 MPM.run(*TheModule, MAM); 853 } 854 855 // Now if needed, run the legacy PM for codegen. 856 if (NeedCodeGen) { 857 PrettyStackTraceString CrashInfo("Code generation"); 858 CodeGenPasses.run(*TheModule); 859 } 860 } 861 862 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) { 863 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 864 if (!BMsOrErr) 865 return BMsOrErr.takeError(); 866 867 // The bitcode file may contain multiple modules, we want the one with a 868 // summary. 869 for (BitcodeModule &BM : *BMsOrErr) { 870 Expected<bool> HasSummary = BM.hasSummary(); 871 if (HasSummary && *HasSummary) 872 return BM; 873 } 874 875 return make_error<StringError>("Could not find module summary", 876 inconvertibleErrorCode()); 877 } 878 879 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M, 880 std::unique_ptr<raw_pwrite_stream> OS, 881 std::string SampleProfile) { 882 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> 883 ModuleToDefinedGVSummaries; 884 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 885 886 // We can simply import the values mentioned in the combined index, since 887 // we should only invoke this using the individual indexes written out 888 // via a WriteIndexesThinBackend. 889 FunctionImporter::ImportMapTy ImportList; 890 for (auto &GlobalList : *CombinedIndex) { 891 auto GUID = GlobalList.first; 892 assert(GlobalList.second.size() == 1 && 893 "Expected individual combined index to have one summary per GUID"); 894 auto &Summary = GlobalList.second[0]; 895 // Skip the summaries for the importing module. These are included to 896 // e.g. record required linkage changes. 897 if (Summary->modulePath() == M->getModuleIdentifier()) 898 continue; 899 // Doesn't matter what value we plug in to the map, just needs an entry 900 // to provoke importing by thinBackend. 901 ImportList[Summary->modulePath()][GUID] = 1; 902 } 903 904 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports; 905 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap; 906 907 for (auto &I : ImportList) { 908 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr = 909 llvm::MemoryBuffer::getFile(I.first()); 910 if (!MBOrErr) { 911 errs() << "Error loading imported file '" << I.first() 912 << "': " << MBOrErr.getError().message() << "\n"; 913 return; 914 } 915 916 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr); 917 if (!BMOrErr) { 918 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { 919 errs() << "Error loading imported file '" << I.first() 920 << "': " << EIB.message() << '\n'; 921 }); 922 return; 923 } 924 ModuleMap.insert({I.first(), *BMOrErr}); 925 926 OwnedImports.push_back(std::move(*MBOrErr)); 927 } 928 auto AddStream = [&](size_t Task) { 929 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS)); 930 }; 931 lto::Config Conf; 932 Conf.SampleProfile = SampleProfile; 933 if (Error E = thinBackend( 934 Conf, 0, AddStream, *M, *CombinedIndex, ImportList, 935 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) { 936 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 937 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n'; 938 }); 939 } 940 } 941 942 void clang::EmitBackendOutput(DiagnosticsEngine &Diags, 943 const HeaderSearchOptions &HeaderOpts, 944 const CodeGenOptions &CGOpts, 945 const clang::TargetOptions &TOpts, 946 const LangOptions &LOpts, 947 const llvm::DataLayout &TDesc, Module *M, 948 BackendAction Action, 949 std::unique_ptr<raw_pwrite_stream> OS) { 950 if (!CGOpts.ThinLTOIndexFile.empty()) { 951 // If we are performing a ThinLTO importing compile, load the function index 952 // into memory and pass it into runThinLTOBackend, which will run the 953 // function importer and invoke LTO passes. 954 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = 955 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile); 956 if (!IndexOrErr) { 957 logAllUnhandledErrors(IndexOrErr.takeError(), errs(), 958 "Error loading index file '" + 959 CGOpts.ThinLTOIndexFile + "': "); 960 return; 961 } 962 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr); 963 // A null CombinedIndex means we should skip ThinLTO compilation 964 // (LLVM will optionally ignore empty index files, returning null instead 965 // of an error). 966 bool DoThinLTOBackend = CombinedIndex != nullptr; 967 if (DoThinLTOBackend) { 968 runThinLTOBackend(CombinedIndex.get(), M, std::move(OS), 969 CGOpts.SampleProfileFile); 970 return; 971 } 972 } 973 974 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); 975 976 if (CGOpts.ExperimentalNewPassManager) 977 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); 978 else 979 AsmHelper.EmitAssembly(Action, std::move(OS)); 980 981 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's 982 // DataLayout. 983 if (AsmHelper.TM) { 984 std::string DLDesc = M->getDataLayout().getStringRepresentation(); 985 if (DLDesc != TDesc.getStringRepresentation()) { 986 unsigned DiagID = Diags.getCustomDiagID( 987 DiagnosticsEngine::Error, "backend data layout '%0' does not match " 988 "expected target description '%1'"); 989 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); 990 } 991 } 992 } 993 994 static const char* getSectionNameForBitcode(const Triple &T) { 995 switch (T.getObjectFormat()) { 996 case Triple::MachO: 997 return "__LLVM,__bitcode"; 998 case Triple::COFF: 999 case Triple::ELF: 1000 case Triple::Wasm: 1001 case Triple::UnknownObjectFormat: 1002 return ".llvmbc"; 1003 } 1004 llvm_unreachable("Unimplemented ObjectFormatType"); 1005 } 1006 1007 static const char* getSectionNameForCommandline(const Triple &T) { 1008 switch (T.getObjectFormat()) { 1009 case Triple::MachO: 1010 return "__LLVM,__cmdline"; 1011 case Triple::COFF: 1012 case Triple::ELF: 1013 case Triple::Wasm: 1014 case Triple::UnknownObjectFormat: 1015 return ".llvmcmd"; 1016 } 1017 llvm_unreachable("Unimplemented ObjectFormatType"); 1018 } 1019 1020 // With -fembed-bitcode, save a copy of the llvm IR as data in the 1021 // __LLVM,__bitcode section. 1022 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, 1023 llvm::MemoryBufferRef Buf) { 1024 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) 1025 return; 1026 1027 // Save llvm.compiler.used and remote it. 1028 SmallVector<Constant*, 2> UsedArray; 1029 SmallSet<GlobalValue*, 4> UsedGlobals; 1030 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0); 1031 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true); 1032 for (auto *GV : UsedGlobals) { 1033 if (GV->getName() != "llvm.embedded.module" && 1034 GV->getName() != "llvm.cmdline") 1035 UsedArray.push_back( 1036 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1037 } 1038 if (Used) 1039 Used->eraseFromParent(); 1040 1041 // Embed the bitcode for the llvm module. 1042 std::string Data; 1043 ArrayRef<uint8_t> ModuleData; 1044 Triple T(M->getTargetTriple()); 1045 // Create a constant that contains the bitcode. 1046 // In case of embedding a marker, ignore the input Buf and use the empty 1047 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty. 1048 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) { 1049 if (!isBitcode((const unsigned char *)Buf.getBufferStart(), 1050 (const unsigned char *)Buf.getBufferEnd())) { 1051 // If the input is LLVM Assembly, bitcode is produced by serializing 1052 // the module. Use-lists order need to be perserved in this case. 1053 llvm::raw_string_ostream OS(Data); 1054 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true); 1055 ModuleData = 1056 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size()); 1057 } else 1058 // If the input is LLVM bitcode, write the input byte stream directly. 1059 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(), 1060 Buf.getBufferSize()); 1061 } 1062 llvm::Constant *ModuleConstant = 1063 llvm::ConstantDataArray::get(M->getContext(), ModuleData); 1064 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1065 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, 1066 ModuleConstant); 1067 GV->setSection(getSectionNameForBitcode(T)); 1068 UsedArray.push_back( 1069 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1070 if (llvm::GlobalVariable *Old = 1071 M->getGlobalVariable("llvm.embedded.module", true)) { 1072 assert(Old->hasOneUse() && 1073 "llvm.embedded.module can only be used once in llvm.compiler.used"); 1074 GV->takeName(Old); 1075 Old->eraseFromParent(); 1076 } else { 1077 GV->setName("llvm.embedded.module"); 1078 } 1079 1080 // Skip if only bitcode needs to be embedded. 1081 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) { 1082 // Embed command-line options. 1083 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()), 1084 CGOpts.CmdArgs.size()); 1085 llvm::Constant *CmdConstant = 1086 llvm::ConstantDataArray::get(M->getContext(), CmdData); 1087 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, 1088 llvm::GlobalValue::PrivateLinkage, 1089 CmdConstant); 1090 GV->setSection(getSectionNameForCommandline(T)); 1091 UsedArray.push_back( 1092 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); 1093 if (llvm::GlobalVariable *Old = 1094 M->getGlobalVariable("llvm.cmdline", true)) { 1095 assert(Old->hasOneUse() && 1096 "llvm.cmdline can only be used once in llvm.compiler.used"); 1097 GV->takeName(Old); 1098 Old->eraseFromParent(); 1099 } else { 1100 GV->setName("llvm.cmdline"); 1101 } 1102 } 1103 1104 if (UsedArray.empty()) 1105 return; 1106 1107 // Recreate llvm.compiler.used. 1108 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size()); 1109 auto *NewUsed = new GlobalVariable( 1110 *M, ATy, false, llvm::GlobalValue::AppendingLinkage, 1111 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used"); 1112 NewUsed->setSection("llvm.metadata"); 1113 } 1114