1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a gold plugin for LLVM. It provides an LLVM implementation of the
11 // interface described in http://gcc.gnu.org/wiki/whopr/driver .
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Linker/Linker.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Object/IRObjectFile.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
42 #include "llvm/Transforms/Utils/GlobalStatus.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 #include "llvm/Transforms/Utils/ValueMapper.h"
46 #include <plugin-api.h>
47 #include <system_error>
51 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
52 // Precise and Debian Wheezy (binutils 2.23 is required)
61 std::vector<ld_plugin_symbol> syms;
65 static ld_plugin_status discard_message(int level, const char *format, ...) {
66 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
67 // callback in the transfer vector. This should never be called.
71 static ld_plugin_get_input_file get_input_file = nullptr;
72 static ld_plugin_release_input_file release_input_file = nullptr;
73 static ld_plugin_add_symbols add_symbols = nullptr;
74 static ld_plugin_get_symbols get_symbols = nullptr;
75 static ld_plugin_add_input_file add_input_file = nullptr;
76 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
77 static ld_plugin_get_view get_view = nullptr;
78 static ld_plugin_message message = discard_message;
79 static Reloc::Model RelocationModel = Reloc::Default;
80 static std::string output_name = "";
81 static std::list<claimed_file> Modules;
82 static std::vector<std::string> Cleanup;
83 static llvm::TargetOptions TargetOpts;
92 static bool generate_api_file = false;
93 static OutputType TheOutputType = OT_NORMAL;
94 static unsigned OptLevel = 2;
95 static std::string obj_path;
96 static std::string extra_library_path;
97 static std::string triple;
98 static std::string mcpu;
99 // Additional options to pass into the code generator.
100 // Note: This array will contain all plugin options which are not claimed
101 // as plugin exclusive to pass to the code generator.
102 // For example, "generate-api-file" and "as"options are for the plugin
103 // use only and will not be passed.
104 static std::vector<const char *> extra;
106 static void process_plugin_option(const char* opt_)
110 llvm::StringRef opt = opt_;
112 if (opt == "generate-api-file") {
113 generate_api_file = true;
114 } else if (opt.startswith("mcpu=")) {
115 mcpu = opt.substr(strlen("mcpu="));
116 } else if (opt.startswith("extra-library-path=")) {
117 extra_library_path = opt.substr(strlen("extra_library_path="));
118 } else if (opt.startswith("mtriple=")) {
119 triple = opt.substr(strlen("mtriple="));
120 } else if (opt.startswith("obj-path=")) {
121 obj_path = opt.substr(strlen("obj-path="));
122 } else if (opt == "emit-llvm") {
123 TheOutputType = OT_BC_ONLY;
124 } else if (opt == "save-temps") {
125 TheOutputType = OT_SAVE_TEMPS;
126 } else if (opt == "disable-output") {
127 TheOutputType = OT_DISABLE;
128 } else if (opt.size() == 2 && opt[0] == 'O') {
129 if (opt[1] < '0' || opt[1] > '3')
130 report_fatal_error("Optimization level must be between 0 and 3");
131 OptLevel = opt[1] - '0';
133 // Save this option to pass to the code generator.
134 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
137 extra.push_back("LLVMgold");
139 extra.push_back(opt_);
144 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
146 static ld_plugin_status all_symbols_read_hook(void);
147 static ld_plugin_status cleanup_hook(void);
149 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
150 ld_plugin_status onload(ld_plugin_tv *tv) {
151 InitializeAllTargetInfos();
152 InitializeAllTargets();
153 InitializeAllTargetMCs();
154 InitializeAllAsmParsers();
155 InitializeAllAsmPrinters();
157 // We're given a pointer to the first transfer vector. We read through them
158 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
159 // contain pointers to functions that we need to call to register our own
160 // hooks. The others are addresses of functions we can use to call into gold
163 bool registeredClaimFile = false;
164 bool RegisteredAllSymbolsRead = false;
166 for (; tv->tv_tag != LDPT_NULL; ++tv) {
167 switch (tv->tv_tag) {
168 case LDPT_OUTPUT_NAME:
169 output_name = tv->tv_u.tv_string;
171 case LDPT_LINKER_OUTPUT:
172 switch (tv->tv_u.tv_val) {
174 case LDPO_DYN: // .so
175 case LDPO_PIE: // position independent executable
176 RelocationModel = Reloc::PIC_;
178 case LDPO_EXEC: // .exe
179 RelocationModel = Reloc::Static;
182 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
187 options::process_plugin_option(tv->tv_u.tv_string);
189 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
190 ld_plugin_register_claim_file callback;
191 callback = tv->tv_u.tv_register_claim_file;
193 if (callback(claim_file_hook) != LDPS_OK)
196 registeredClaimFile = true;
198 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
199 ld_plugin_register_all_symbols_read callback;
200 callback = tv->tv_u.tv_register_all_symbols_read;
202 if (callback(all_symbols_read_hook) != LDPS_OK)
205 RegisteredAllSymbolsRead = true;
207 case LDPT_REGISTER_CLEANUP_HOOK: {
208 ld_plugin_register_cleanup callback;
209 callback = tv->tv_u.tv_register_cleanup;
211 if (callback(cleanup_hook) != LDPS_OK)
214 case LDPT_GET_INPUT_FILE:
215 get_input_file = tv->tv_u.tv_get_input_file;
217 case LDPT_RELEASE_INPUT_FILE:
218 release_input_file = tv->tv_u.tv_release_input_file;
220 case LDPT_ADD_SYMBOLS:
221 add_symbols = tv->tv_u.tv_add_symbols;
223 case LDPT_GET_SYMBOLS_V2:
224 get_symbols = tv->tv_u.tv_get_symbols;
226 case LDPT_ADD_INPUT_FILE:
227 add_input_file = tv->tv_u.tv_add_input_file;
229 case LDPT_SET_EXTRA_LIBRARY_PATH:
230 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
233 get_view = tv->tv_u.tv_get_view;
236 message = tv->tv_u.tv_message;
243 if (!registeredClaimFile) {
244 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
248 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
252 if (!RegisteredAllSymbolsRead)
255 if (!get_input_file) {
256 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
259 if (!release_input_file) {
260 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
267 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
268 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
269 return GA->getBaseObject();
270 return cast<GlobalObject>(&GV);
273 static bool shouldSkip(uint32_t Symflags) {
274 if (!(Symflags & object::BasicSymbolRef::SF_Global))
276 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
281 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
282 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
283 std::error_code EC = BDI->getError();
284 if (EC == BitcodeError::InvalidBitcodeSignature)
288 std::string ErrStorage;
290 raw_string_ostream OS(ErrStorage);
291 DiagnosticPrinterRawOStream DP(OS);
294 ld_plugin_level Level;
295 switch (DI.getSeverity()) {
297 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
299 llvm_unreachable("Fatal doesn't return.");
301 Level = LDPL_WARNING;
308 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
311 /// Called by gold to see whether this file is one that our plugin can handle.
312 /// We'll try to open it and register all the symbols with add_symbol if
314 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
317 MemoryBufferRef BufferRef;
318 std::unique_ptr<MemoryBuffer> Buffer;
321 if (get_view(file->handle, &view) != LDPS_OK) {
322 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
325 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
328 // Gold has found what might be IR part-way inside of a file, such as
331 offset = file->offset;
333 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
334 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
336 if (std::error_code EC = BufferOrErr.getError()) {
337 message(LDPL_ERROR, EC.message().c_str());
340 Buffer = std::move(BufferOrErr.get());
341 BufferRef = Buffer->getMemBufferRef();
344 Context.setDiagnosticHandler(diagnosticHandler);
345 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
346 object::IRObjectFile::create(BufferRef, Context);
347 std::error_code EC = ObjOrErr.getError();
348 if (EC == object::object_error::invalid_file_type ||
349 EC == object::object_error::bitcode_section_not_found)
355 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
356 EC.message().c_str());
359 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
361 Modules.resize(Modules.size() + 1);
362 claimed_file &cf = Modules.back();
364 cf.handle = file->handle;
366 for (auto &Sym : Obj->symbols()) {
367 uint32_t Symflags = Sym.getFlags();
368 if (shouldSkip(Symflags))
371 cf.syms.push_back(ld_plugin_symbol());
372 ld_plugin_symbol &sym = cf.syms.back();
373 sym.version = nullptr;
375 SmallString<64> Name;
377 raw_svector_ostream OS(Name);
380 sym.name = strdup(Name.c_str());
382 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
384 sym.visibility = LDPV_DEFAULT;
386 switch (GV->getVisibility()) {
387 case GlobalValue::DefaultVisibility:
388 sym.visibility = LDPV_DEFAULT;
390 case GlobalValue::HiddenVisibility:
391 sym.visibility = LDPV_HIDDEN;
393 case GlobalValue::ProtectedVisibility:
394 sym.visibility = LDPV_PROTECTED;
399 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
400 sym.def = LDPK_UNDEF;
401 if (GV && GV->hasExternalWeakLinkage())
402 sym.def = LDPK_WEAKUNDEF;
406 assert(!GV->hasExternalWeakLinkage() &&
407 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
408 if (GV->hasCommonLinkage())
409 sym.def = LDPK_COMMON;
410 else if (GV->isWeakForLinker())
411 sym.def = LDPK_WEAKDEF;
416 sym.comdat_key = nullptr;
418 const GlobalObject *Base = getBaseObject(*GV);
420 message(LDPL_FATAL, "Unable to determine comdat of alias!");
421 const Comdat *C = Base->getComdat();
423 sym.comdat_key = strdup(C->getName().str().c_str());
424 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
425 sym.comdat_key = strdup(sym.name);
428 sym.resolution = LDPR_UNKNOWN;
431 if (!cf.syms.empty()) {
432 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
433 message(LDPL_ERROR, "Unable to add symbols!");
441 static void keepGlobalValue(GlobalValue &GV,
442 std::vector<GlobalAlias *> &KeptAliases) {
443 assert(!GV.hasLocalLinkage());
445 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
446 KeptAliases.push_back(GA);
448 switch (GV.getLinkage()) {
451 case GlobalValue::LinkOnceAnyLinkage:
452 GV.setLinkage(GlobalValue::WeakAnyLinkage);
454 case GlobalValue::LinkOnceODRLinkage:
455 GV.setLinkage(GlobalValue::WeakODRLinkage);
459 assert(!GV.isDiscardableIfUnused());
462 static void internalize(GlobalValue &GV) {
463 if (GV.isDeclarationForLinker())
464 return; // We get here if there is a matching asm definition.
465 if (!GV.hasLocalLinkage())
466 GV.setLinkage(GlobalValue::InternalLinkage);
469 static void drop(GlobalValue &GV) {
470 if (auto *F = dyn_cast<Function>(&GV)) {
472 F->setComdat(nullptr); // Should deleteBody do this?
476 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
477 Var->setInitializer(nullptr);
479 GlobalValue::ExternalLinkage); // Should setInitializer do this?
480 Var->setComdat(nullptr); // and this?
484 auto &Alias = cast<GlobalAlias>(GV);
485 Module &M = *Alias.getParent();
486 PointerType &Ty = *cast<PointerType>(Alias.getType());
487 GlobalValue::LinkageTypes L = Alias.getLinkage();
489 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
490 /*Initializer*/ nullptr);
491 Var->takeName(&Alias);
492 Alias.replaceAllUsesWith(Var);
493 Alias.eraseFromParent();
496 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
502 case LDPR_PREVAILING_DEF:
503 return "PREVAILING_DEF";
504 case LDPR_PREVAILING_DEF_IRONLY:
505 return "PREVAILING_DEF_IRONLY";
506 case LDPR_PREEMPTED_REG:
507 return "PREEMPTED_REG";
508 case LDPR_PREEMPTED_IR:
509 return "PREEMPTED_IR";
510 case LDPR_RESOLVED_IR:
511 return "RESOLVED_IR";
512 case LDPR_RESOLVED_EXEC:
513 return "RESOLVED_EXEC";
514 case LDPR_RESOLVED_DYN:
515 return "RESOLVED_DYN";
516 case LDPR_PREVAILING_DEF_IRONLY_EXP:
517 return "PREVAILING_DEF_IRONLY_EXP";
519 llvm_unreachable("Unknown resolution");
523 class LocalValueMaterializer : public ValueMaterializer {
524 DenseSet<GlobalValue *> &Dropped;
525 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
528 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
529 Value *materializeValueFor(Value *V) override;
533 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
534 auto *GO = dyn_cast<GlobalObject>(V);
538 auto I = LocalVersions.find(GO);
539 if (I != LocalVersions.end())
542 if (!Dropped.count(GO))
545 Module &M = *GO->getParent();
546 GlobalValue::LinkageTypes L = GO->getLinkage();
547 GlobalObject *Declaration;
548 if (auto *F = dyn_cast<Function>(GO)) {
549 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
551 auto *Var = cast<GlobalVariable>(GO);
552 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
553 Var->isConstant(), L,
554 /*Initializer*/ nullptr);
556 Declaration->takeName(GO);
557 Declaration->copyAttributesFrom(GO);
559 GO->setLinkage(GlobalValue::InternalLinkage);
560 GO->setName(Declaration->getName());
562 GO->replaceAllUsesWith(Declaration);
564 LocalVersions[Declaration] = GO;
569 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
570 LocalValueMaterializer *Materializer) {
571 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
574 static void freeSymName(ld_plugin_symbol &Sym) {
576 free(Sym.comdat_key);
578 Sym.comdat_key = nullptr;
581 static std::unique_ptr<Module>
582 getModuleForFile(LLVMContext &Context, claimed_file &F,
583 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
584 StringSet<> &Internalize, StringSet<> &Maybe) {
586 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
587 message(LDPL_FATAL, "Failed to get symbol information");
590 if (get_view(F.handle, &View) != LDPS_OK)
591 message(LDPL_FATAL, "Failed to get a view of file");
593 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
595 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
596 object::IRObjectFile::create(BufferRef, Context);
598 if (std::error_code EC = ObjOrErr.getError())
599 message(LDPL_FATAL, "Could not read bitcode from file : %s",
600 EC.message().c_str());
602 object::IRObjectFile &Obj = **ObjOrErr;
604 Module &M = Obj.getModule();
606 M.materializeMetadata();
609 SmallPtrSet<GlobalValue *, 8> Used;
610 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
612 DenseSet<GlobalValue *> Drop;
613 std::vector<GlobalAlias *> KeptAliases;
616 for (auto &ObjSym : Obj.symbols()) {
617 if (shouldSkip(ObjSym.getFlags()))
619 ld_plugin_symbol &Sym = F.syms[SymNum];
622 ld_plugin_symbol_resolution Resolution =
623 (ld_plugin_symbol_resolution)Sym.resolution;
625 if (options::generate_api_file)
626 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
628 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
631 continue; // Asm symbol.
634 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
635 // Common linkage is special. There is no single symbol that wins the
636 // resolution. Instead we have to collect the maximum alignment and size.
637 // The IR linker does that for us if we just pass it every common GV.
638 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
639 // internalize once the IR linker has done its job.
644 switch (Resolution) {
646 llvm_unreachable("Unexpected resolution");
648 case LDPR_RESOLVED_IR:
649 case LDPR_RESOLVED_EXEC:
650 case LDPR_RESOLVED_DYN:
651 assert(GV->isDeclarationForLinker());
655 if (!GV->isDeclarationForLinker()) {
656 assert(GV->hasComdat());
661 case LDPR_PREVAILING_DEF_IRONLY: {
662 keepGlobalValue(*GV, KeptAliases);
663 if (!Used.count(GV)) {
664 // Since we use the regular lib/Linker, we cannot just internalize GV
665 // now or it will not be copied to the merged module. Instead we force
666 // it to be copied and then internalize it.
667 Internalize.insert(GV->getName());
672 case LDPR_PREVAILING_DEF:
673 keepGlobalValue(*GV, KeptAliases);
676 case LDPR_PREEMPTED_IR:
677 // Gold might have selected a linkonce_odr and preempted a weak_odr.
678 // In that case we have to make sure we don't end up internalizing it.
679 if (!GV->isDiscardableIfUnused())
680 Maybe.erase(GV->getName());
683 case LDPR_PREEMPTED_REG:
687 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
688 // We can only check for address uses after we merge the modules. The
689 // reason is that this GV might have a copy in another module
690 // and in that module the address might be significant, but that
691 // copy will be LDPR_PREEMPTED_IR.
692 if (GV->hasLinkOnceODRLinkage())
693 Maybe.insert(GV->getName());
694 keepGlobalValue(*GV, KeptAliases);
702 ValueToValueMapTy VM;
703 LocalValueMaterializer Materializer(Drop);
704 for (GlobalAlias *GA : KeptAliases) {
705 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
706 // expression is being dropped. If that is the case, that GV must be copied.
707 Constant *Aliasee = GA->getAliasee();
708 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
709 GA->setAliasee(Replacement);
712 for (auto *GV : Drop)
715 return Obj.takeModule();
718 static void runLTOPasses(Module &M, TargetMachine &TM) {
719 if (const DataLayout *DL = TM.getDataLayout())
720 M.setDataLayout(*DL);
722 legacy::PassManager passes;
723 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
725 PassManagerBuilder PMB;
726 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
727 PMB.Inliner = createFunctionInliningPass();
728 PMB.VerifyInput = true;
729 PMB.VerifyOutput = true;
730 PMB.LoopVectorize = true;
731 PMB.SLPVectorize = true;
732 PMB.OptLevel = options::OptLevel;
733 PMB.populateLTOPassManager(passes);
737 static void saveBCFile(StringRef Path, Module &M) {
739 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
741 message(LDPL_FATAL, "Failed to write the output file.");
742 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
745 static void codegen(Module &M) {
746 const std::string &TripleStr = M.getTargetTriple();
747 Triple TheTriple(TripleStr);
750 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
752 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
754 if (unsigned NumOpts = options::extra.size())
755 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
757 SubtargetFeatures Features;
758 Features.getDefaultSubtargetFeatures(TheTriple);
759 for (const std::string &A : MAttrs)
760 Features.AddFeature(A);
762 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
763 CodeGenOpt::Level CGOptLevel;
764 switch (options::OptLevel) {
766 CGOptLevel = CodeGenOpt::None;
769 CGOptLevel = CodeGenOpt::Less;
772 CGOptLevel = CodeGenOpt::Default;
775 CGOptLevel = CodeGenOpt::Aggressive;
778 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
779 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
780 CodeModel::Default, CGOptLevel));
782 runLTOPasses(M, *TM);
784 if (options::TheOutputType == options::OT_SAVE_TEMPS)
785 saveBCFile(output_name + ".opt.bc", M);
787 legacy::PassManager CodeGenPasses;
789 SmallString<128> Filename;
791 if (options::obj_path.empty()) {
793 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
795 message(LDPL_FATAL, "Could not create temporary file: %s",
796 EC.message().c_str());
798 Filename = options::obj_path;
800 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
802 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
806 raw_fd_ostream OS(FD, true);
808 if (TM->addPassesToEmitFile(CodeGenPasses, OS,
809 TargetMachine::CGFT_ObjectFile))
810 message(LDPL_FATAL, "Failed to setup codegen");
811 CodeGenPasses.run(M);
814 if (add_input_file(Filename.c_str()) != LDPS_OK)
816 "Unable to add .o file to the link. File left behind in: %s",
819 if (options::obj_path.empty())
820 Cleanup.push_back(Filename.c_str());
823 /// gold informs us that all symbols have been read. At this point, we use
824 /// get_symbols to see if any of our definitions have been overridden by a
825 /// native object file. Then, perform optimization and codegen.
826 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
831 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
833 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
834 Linker L(Combined.get());
836 std::string DefaultTriple = sys::getDefaultTargetTriple();
838 StringSet<> Internalize;
840 for (claimed_file &F : Modules) {
841 ld_plugin_input_file File;
842 if (get_input_file(F.handle, &File) != LDPS_OK)
843 message(LDPL_FATAL, "Failed to get file information");
844 std::unique_ptr<Module> M =
845 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
846 if (!options::triple.empty())
847 M->setTargetTriple(options::triple.c_str());
848 else if (M->getTargetTriple().empty()) {
849 M->setTargetTriple(DefaultTriple);
852 if (L.linkInModule(M.get()))
853 message(LDPL_FATAL, "Failed to link module");
854 if (release_input_file(F.handle) != LDPS_OK)
855 message(LDPL_FATAL, "Failed to release file information");
858 for (const auto &Name : Internalize) {
859 GlobalValue *GV = Combined->getNamedValue(Name.first());
864 for (const auto &Name : Maybe) {
865 GlobalValue *GV = Combined->getNamedValue(Name.first());
868 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
869 if (canBeOmittedFromSymbolTable(GV))
873 if (options::TheOutputType == options::OT_DISABLE)
876 if (options::TheOutputType != options::OT_NORMAL) {
878 if (options::TheOutputType == options::OT_BC_ONLY)
881 path = output_name + ".bc";
882 saveBCFile(path, *L.getModule());
883 if (options::TheOutputType == options::OT_BC_ONLY)
887 codegen(*L.getModule());
889 if (!options::extra_library_path.empty() &&
890 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
891 message(LDPL_FATAL, "Unable to set the extra library path.");
896 static ld_plugin_status all_symbols_read_hook(void) {
897 ld_plugin_status Ret;
898 if (!options::generate_api_file) {
899 Ret = allSymbolsReadHook(nullptr);
902 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
904 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
905 EC.message().c_str());
906 Ret = allSymbolsReadHook(&ApiFile);
911 if (options::TheOutputType == options::OT_BC_ONLY ||
912 options::TheOutputType == options::OT_DISABLE) {
913 if (options::TheOutputType == options::OT_DISABLE)
914 // Remove the output file here since ld.bfd creates the output file
916 sys::fs::remove(output_name);
923 static ld_plugin_status cleanup_hook(void) {
924 for (std::string &Name : Cleanup) {
925 std::error_code EC = sys::fs::remove(Name);
927 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
928 EC.message().c_str());