1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===// 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 // This file implements the Link Time Optimization library. This library is 11 // intended to be used by linker to optimize code at link time. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/LTO/LTOCodeGenerator.h" 16 17 #include "UpdateCompilerUsed.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/Analysis/Passes.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/Bitcode/ReaderWriter.h" 24 #include "llvm/CodeGen/ParallelCG.h" 25 #include "llvm/CodeGen/RuntimeLibcalls.h" 26 #include "llvm/Config/config.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/LegacyPassManager.h" 34 #include "llvm/IR/Mangler.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/InitializePasses.h" 38 #include "llvm/LTO/LTOModule.h" 39 #include "llvm/Linker/Linker.h" 40 #include "llvm/MC/MCAsmInfo.h" 41 #include "llvm/MC/MCContext.h" 42 #include "llvm/MC/SubtargetFeature.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/Host.h" 46 #include "llvm/Support/MemoryBuffer.h" 47 #include "llvm/Support/Signals.h" 48 #include "llvm/Support/TargetRegistry.h" 49 #include "llvm/Support/TargetSelect.h" 50 #include "llvm/Support/ToolOutputFile.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include "llvm/Target/TargetLowering.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include "llvm/Target/TargetRegisterInfo.h" 55 #include "llvm/Target/TargetSubtargetInfo.h" 56 #include "llvm/Transforms/IPO.h" 57 #include "llvm/Transforms/IPO/Internalize.h" 58 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 59 #include "llvm/Transforms/ObjCARC.h" 60 #include <system_error> 61 using namespace llvm; 62 63 const char* LTOCodeGenerator::getVersionString() { 64 #ifdef LLVM_VERSION_INFO 65 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; 66 #else 67 return PACKAGE_NAME " version " PACKAGE_VERSION; 68 #endif 69 } 70 71 namespace llvm { 72 cl::opt<bool> LTODiscardValueNames( 73 "lto-discard-value-names", 74 cl::desc("Strip names from Value during LTO (other than GlobalValue)."), 75 #ifdef NDEBUG 76 cl::init(true), 77 #else 78 cl::init(false), 79 #endif 80 cl::Hidden); 81 } 82 83 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context) 84 : Context(Context), MergedModule(new Module("ld-temp.o", Context)), 85 TheLinker(new Linker(*MergedModule)) { 86 Context.setDiscardValueNames(LTODiscardValueNames); 87 initializeLTOPasses(); 88 } 89 90 LTOCodeGenerator::~LTOCodeGenerator() {} 91 92 // Initialize LTO passes. Please keep this function in sync with 93 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO 94 // passes are initialized. 95 void LTOCodeGenerator::initializeLTOPasses() { 96 PassRegistry &R = *PassRegistry::getPassRegistry(); 97 98 initializeInternalizePassPass(R); 99 initializeIPSCCPPass(R); 100 initializeGlobalOptPass(R); 101 initializeConstantMergePass(R); 102 initializeDAHPass(R); 103 initializeInstructionCombiningPassPass(R); 104 initializeSimpleInlinerPass(R); 105 initializePruneEHPass(R); 106 initializeGlobalDCEPass(R); 107 initializeArgPromotionPass(R); 108 initializeJumpThreadingPass(R); 109 initializeSROALegacyPassPass(R); 110 initializeSROA_DTPass(R); 111 initializeSROA_SSAUpPass(R); 112 initializePostOrderFunctionAttrsLegacyPassPass(R); 113 initializeReversePostOrderFunctionAttrsPass(R); 114 initializeGlobalsAAWrapperPassPass(R); 115 initializeLICMPass(R); 116 initializeMergedLoadStoreMotionPass(R); 117 initializeGVNLegacyPassPass(R); 118 initializeMemCpyOptPass(R); 119 initializeDCEPass(R); 120 initializeCFGSimplifyPassPass(R); 121 } 122 123 bool LTOCodeGenerator::addModule(LTOModule *Mod) { 124 assert(&Mod->getModule().getContext() == &Context && 125 "Expected module in same context"); 126 127 bool ret = TheLinker->linkInModule(Mod->takeModule()); 128 129 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs(); 130 for (int i = 0, e = undefs.size(); i != e; ++i) 131 AsmUndefinedRefs[undefs[i]] = 1; 132 133 return !ret; 134 } 135 136 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) { 137 assert(&Mod->getModule().getContext() == &Context && 138 "Expected module in same context"); 139 140 AsmUndefinedRefs.clear(); 141 142 MergedModule = Mod->takeModule(); 143 TheLinker = make_unique<Linker>(*MergedModule); 144 145 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs(); 146 for (int I = 0, E = Undefs.size(); I != E; ++I) 147 AsmUndefinedRefs[Undefs[I]] = 1; 148 } 149 150 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) { 151 this->Options = Options; 152 } 153 154 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) { 155 switch (Debug) { 156 case LTO_DEBUG_MODEL_NONE: 157 EmitDwarfDebugInfo = false; 158 return; 159 160 case LTO_DEBUG_MODEL_DWARF: 161 EmitDwarfDebugInfo = true; 162 return; 163 } 164 llvm_unreachable("Unknown debug format!"); 165 } 166 167 void LTOCodeGenerator::setOptLevel(unsigned Level) { 168 OptLevel = Level; 169 switch (OptLevel) { 170 case 0: 171 CGOptLevel = CodeGenOpt::None; 172 break; 173 case 1: 174 CGOptLevel = CodeGenOpt::Less; 175 break; 176 case 2: 177 CGOptLevel = CodeGenOpt::Default; 178 break; 179 case 3: 180 CGOptLevel = CodeGenOpt::Aggressive; 181 break; 182 } 183 } 184 185 bool LTOCodeGenerator::writeMergedModules(const char *Path) { 186 if (!determineTarget()) 187 return false; 188 189 // mark which symbols can not be internalized 190 applyScopeRestrictions(); 191 192 // create output file 193 std::error_code EC; 194 tool_output_file Out(Path, EC, sys::fs::F_None); 195 if (EC) { 196 std::string ErrMsg = "could not open bitcode file for writing: "; 197 ErrMsg += Path; 198 emitError(ErrMsg); 199 return false; 200 } 201 202 // write bitcode to it 203 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists); 204 Out.os().close(); 205 206 if (Out.os().has_error()) { 207 std::string ErrMsg = "could not write bitcode file: "; 208 ErrMsg += Path; 209 emitError(ErrMsg); 210 Out.os().clear_error(); 211 return false; 212 } 213 214 Out.keep(); 215 return true; 216 } 217 218 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) { 219 // make unique temp output file to put generated code 220 SmallString<128> Filename; 221 int FD; 222 223 const char *Extension = 224 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o"); 225 226 std::error_code EC = 227 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename); 228 if (EC) { 229 emitError(EC.message()); 230 return false; 231 } 232 233 // generate object file 234 tool_output_file objFile(Filename.c_str(), FD); 235 236 bool genResult = compileOptimized(&objFile.os()); 237 objFile.os().close(); 238 if (objFile.os().has_error()) { 239 objFile.os().clear_error(); 240 sys::fs::remove(Twine(Filename)); 241 return false; 242 } 243 244 objFile.keep(); 245 if (!genResult) { 246 sys::fs::remove(Twine(Filename)); 247 return false; 248 } 249 250 NativeObjectPath = Filename.c_str(); 251 *Name = NativeObjectPath.c_str(); 252 return true; 253 } 254 255 std::unique_ptr<MemoryBuffer> 256 LTOCodeGenerator::compileOptimized() { 257 const char *name; 258 if (!compileOptimizedToFile(&name)) 259 return nullptr; 260 261 // read .o file into memory buffer 262 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 263 MemoryBuffer::getFile(name, -1, false); 264 if (std::error_code EC = BufferOrErr.getError()) { 265 emitError(EC.message()); 266 sys::fs::remove(NativeObjectPath); 267 return nullptr; 268 } 269 270 // remove temp files 271 sys::fs::remove(NativeObjectPath); 272 273 return std::move(*BufferOrErr); 274 } 275 276 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify, 277 bool DisableInline, 278 bool DisableGVNLoadPRE, 279 bool DisableVectorization) { 280 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, 281 DisableVectorization)) 282 return false; 283 284 return compileOptimizedToFile(Name); 285 } 286 287 std::unique_ptr<MemoryBuffer> 288 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline, 289 bool DisableGVNLoadPRE, bool DisableVectorization) { 290 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, 291 DisableVectorization)) 292 return nullptr; 293 294 return compileOptimized(); 295 } 296 297 bool LTOCodeGenerator::determineTarget() { 298 if (TargetMach) 299 return true; 300 301 std::string TripleStr = MergedModule->getTargetTriple(); 302 if (TripleStr.empty()) { 303 TripleStr = sys::getDefaultTargetTriple(); 304 MergedModule->setTargetTriple(TripleStr); 305 } 306 llvm::Triple Triple(TripleStr); 307 308 // create target machine from info for merged modules 309 std::string ErrMsg; 310 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg); 311 if (!march) { 312 emitError(ErrMsg); 313 return false; 314 } 315 316 // Construct LTOModule, hand over ownership of module and target. Use MAttr as 317 // the default set of features. 318 SubtargetFeatures Features(MAttr); 319 Features.getDefaultSubtargetFeatures(Triple); 320 FeatureStr = Features.getString(); 321 // Set a default CPU for Darwin triples. 322 if (MCpu.empty() && Triple.isOSDarwin()) { 323 if (Triple.getArch() == llvm::Triple::x86_64) 324 MCpu = "core2"; 325 else if (Triple.getArch() == llvm::Triple::x86) 326 MCpu = "yonah"; 327 else if (Triple.getArch() == llvm::Triple::aarch64) 328 MCpu = "cyclone"; 329 } 330 331 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr, 332 Options, RelocModel, 333 CodeModel::Default, CGOptLevel)); 334 return true; 335 } 336 337 void LTOCodeGenerator::applyScopeRestrictions() { 338 if (ScopeRestrictionsDone || !ShouldInternalize) 339 return; 340 341 if (ShouldRestoreGlobalsLinkage) { 342 // Record the linkage type of non-local symbols so they can be restored 343 // prior 344 // to module splitting. 345 auto RecordLinkage = [&](const GlobalValue &GV) { 346 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() && 347 GV.hasName()) 348 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage())); 349 }; 350 for (auto &GV : *MergedModule) 351 RecordLinkage(GV); 352 for (auto &GV : MergedModule->globals()) 353 RecordLinkage(GV); 354 for (auto &GV : MergedModule->aliases()) 355 RecordLinkage(GV); 356 } 357 358 // Update the llvm.compiler_used globals to force preserving libcalls and 359 // symbols referenced from asm 360 UpdateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs); 361 362 // Declare a callback for the internalize pass that will ask for every 363 // candidate GlobalValue if it can be internalized or not. 364 Mangler Mangler; 365 SmallString<64> MangledName; 366 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 367 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled 368 // with the linker supplied name, which on Darwin includes a leading 369 // underscore. 370 MangledName.clear(); 371 MangledName.reserve(GV.getName().size() + 1); 372 Mangler::getNameWithPrefix(MangledName, GV.getName(), 373 MergedModule->getDataLayout()); 374 return MustPreserveSymbols.count(MangledName); 375 }; 376 377 internalizeModule(*MergedModule, MustPreserveGV); 378 379 ScopeRestrictionsDone = true; 380 } 381 382 /// Restore original linkage for symbols that may have been internalized 383 void LTOCodeGenerator::restoreLinkageForExternals() { 384 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage) 385 return; 386 387 assert(ScopeRestrictionsDone && 388 "Cannot externalize without internalization!"); 389 390 if (ExternalSymbols.empty()) 391 return; 392 393 auto externalize = [this](GlobalValue &GV) { 394 if (!GV.hasLocalLinkage() || !GV.hasName()) 395 return; 396 397 auto I = ExternalSymbols.find(GV.getName()); 398 if (I == ExternalSymbols.end()) 399 return; 400 401 GV.setLinkage(I->second); 402 }; 403 404 std::for_each(MergedModule->begin(), MergedModule->end(), externalize); 405 std::for_each(MergedModule->global_begin(), MergedModule->global_end(), 406 externalize); 407 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(), 408 externalize); 409 } 410 411 /// Optimize merged modules using various IPO passes 412 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline, 413 bool DisableGVNLoadPRE, 414 bool DisableVectorization) { 415 if (!this->determineTarget()) 416 return false; 417 418 // We always run the verifier once on the merged module, the `DisableVerify` 419 // parameter only applies to subsequent verify. 420 if (verifyModule(*MergedModule, &dbgs())) 421 report_fatal_error("Broken module found, compilation aborted!"); 422 423 // Mark which symbols can not be internalized 424 this->applyScopeRestrictions(); 425 426 // Instantiate the pass manager to organize the passes. 427 legacy::PassManager passes; 428 429 // Add an appropriate DataLayout instance for this module... 430 MergedModule->setDataLayout(TargetMach->createDataLayout()); 431 432 passes.add( 433 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis())); 434 435 Triple TargetTriple(TargetMach->getTargetTriple()); 436 PassManagerBuilder PMB; 437 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE; 438 PMB.LoopVectorize = !DisableVectorization; 439 PMB.SLPVectorize = !DisableVectorization; 440 if (!DisableInline) 441 PMB.Inliner = createFunctionInliningPass(); 442 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple); 443 PMB.OptLevel = OptLevel; 444 PMB.VerifyInput = !DisableVerify; 445 PMB.VerifyOutput = !DisableVerify; 446 447 PMB.populateLTOPassManager(passes); 448 449 // Run our queue of passes all at once now, efficiently. 450 passes.run(*MergedModule); 451 452 return true; 453 } 454 455 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) { 456 if (!this->determineTarget()) 457 return false; 458 459 legacy::PassManager preCodeGenPasses; 460 461 // If the bitcode files contain ARC code and were compiled with optimization, 462 // the ObjCARCContractPass must be run, so do it unconditionally here. 463 preCodeGenPasses.add(createObjCARCContractPass()); 464 preCodeGenPasses.run(*MergedModule); 465 466 // Re-externalize globals that may have been internalized to increase scope 467 // for splitting 468 restoreLinkageForExternals(); 469 470 // Do code generation. We need to preserve the module in case the client calls 471 // writeMergedModules() after compilation, but we only need to allow this at 472 // parallelism level 1. This is achieved by having splitCodeGen return the 473 // original module at parallelism level 1 which we then assign back to 474 // MergedModule. 475 MergedModule = splitCodeGen( 476 std::move(MergedModule), Out, {}, MCpu, FeatureStr, Options, RelocModel, 477 CodeModel::Default, CGOptLevel, FileType, ShouldRestoreGlobalsLinkage); 478 479 // If statistics were requested, print them out after codegen. 480 if (llvm::AreStatisticsEnabled()) 481 llvm::PrintStatistics(); 482 483 return true; 484 } 485 486 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging 487 /// LTO problems. 488 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) { 489 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty(); 490 o = getToken(o.second)) 491 CodegenOptions.push_back(o.first); 492 } 493 494 void LTOCodeGenerator::parseCodeGenDebugOptions() { 495 // if options were requested, set them 496 if (!CodegenOptions.empty()) { 497 // ParseCommandLineOptions() expects argv[0] to be program name. 498 std::vector<const char *> CodegenArgv(1, "libLLVMLTO"); 499 for (std::string &Arg : CodegenOptions) 500 CodegenArgv.push_back(Arg.c_str()); 501 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data()); 502 } 503 } 504 505 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI, 506 void *Context) { 507 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI); 508 } 509 510 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) { 511 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity. 512 lto_codegen_diagnostic_severity_t Severity; 513 switch (DI.getSeverity()) { 514 case DS_Error: 515 Severity = LTO_DS_ERROR; 516 break; 517 case DS_Warning: 518 Severity = LTO_DS_WARNING; 519 break; 520 case DS_Remark: 521 Severity = LTO_DS_REMARK; 522 break; 523 case DS_Note: 524 Severity = LTO_DS_NOTE; 525 break; 526 } 527 // Create the string that will be reported to the external diagnostic handler. 528 std::string MsgStorage; 529 raw_string_ostream Stream(MsgStorage); 530 DiagnosticPrinterRawOStream DP(Stream); 531 DI.print(DP); 532 Stream.flush(); 533 534 // If this method has been called it means someone has set up an external 535 // diagnostic handler. Assert on that. 536 assert(DiagHandler && "Invalid diagnostic handler"); 537 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext); 538 } 539 540 void 541 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler, 542 void *Ctxt) { 543 this->DiagHandler = DiagHandler; 544 this->DiagContext = Ctxt; 545 if (!DiagHandler) 546 return Context.setDiagnosticHandler(nullptr, nullptr); 547 // Register the LTOCodeGenerator stub in the LLVMContext to forward the 548 // diagnostic to the external DiagHandler. 549 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this, 550 /* RespectFilters */ true); 551 } 552 553 namespace { 554 class LTODiagnosticInfo : public DiagnosticInfo { 555 const Twine &Msg; 556 public: 557 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error) 558 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} 559 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 560 }; 561 } 562 563 void LTOCodeGenerator::emitError(const std::string &ErrMsg) { 564 if (DiagHandler) 565 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext); 566 else 567 Context.diagnose(LTODiagnosticInfo(ErrMsg)); 568 } 569