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/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/Linker/Linker.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Object/IRObjectFile.h"
30 #include "llvm/PassManager.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Target/TargetLibraryInfo.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
40 #include "llvm/Transforms/Utils/GlobalStatus.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
44 #include <plugin-api.h>
45 #include <system_error>
49 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
50 // Precise and Debian Wheezy (binutils 2.23 is required)
59 std::vector
<ld_plugin_symbol
> syms
;
63 static ld_plugin_status
discard_message(int level
, const char *format
, ...) {
64 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
65 // callback in the transfer vector. This should never be called.
69 static ld_plugin_get_input_file get_input_file
= nullptr;
70 static ld_plugin_release_input_file release_input_file
= nullptr;
71 static ld_plugin_add_symbols add_symbols
= nullptr;
72 static ld_plugin_get_symbols get_symbols
= nullptr;
73 static ld_plugin_add_input_file add_input_file
= nullptr;
74 static ld_plugin_set_extra_library_path set_extra_library_path
= nullptr;
75 static ld_plugin_get_view get_view
= nullptr;
76 static ld_plugin_message message
= discard_message
;
77 static Reloc::Model RelocationModel
= Reloc::Default
;
78 static std::string output_name
= "";
79 static std::list
<claimed_file
> Modules
;
80 static std::vector
<std::string
> Cleanup
;
81 static llvm::TargetOptions TargetOpts
;
90 static bool generate_api_file
= false;
91 static OutputType TheOutputType
= OT_NORMAL
;
92 static std::string obj_path
;
93 static std::string extra_library_path
;
94 static std::string triple
;
95 static std::string mcpu
;
96 // Additional options to pass into the code generator.
97 // Note: This array will contain all plugin options which are not claimed
98 // as plugin exclusive to pass to the code generator.
99 // For example, "generate-api-file" and "as"options are for the plugin
100 // use only and will not be passed.
101 static std::vector
<const char *> extra
;
103 static void process_plugin_option(const char* opt_
)
107 llvm::StringRef opt
= opt_
;
109 if (opt
== "generate-api-file") {
110 generate_api_file
= true;
111 } else if (opt
.startswith("mcpu=")) {
112 mcpu
= opt
.substr(strlen("mcpu="));
113 } else if (opt
.startswith("extra-library-path=")) {
114 extra_library_path
= opt
.substr(strlen("extra_library_path="));
115 } else if (opt
.startswith("mtriple=")) {
116 triple
= opt
.substr(strlen("mtriple="));
117 } else if (opt
.startswith("obj-path=")) {
118 obj_path
= opt
.substr(strlen("obj-path="));
119 } else if (opt
== "emit-llvm") {
120 TheOutputType
= OT_BC_ONLY
;
121 } else if (opt
== "save-temps") {
122 TheOutputType
= OT_SAVE_TEMPS
;
123 } else if (opt
== "disable-output") {
124 TheOutputType
= OT_DISABLE
;
126 // Save this option to pass to the code generator.
127 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
130 extra
.push_back("LLVMgold");
132 extra
.push_back(opt_
);
137 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
139 static ld_plugin_status
all_symbols_read_hook(void);
140 static ld_plugin_status
cleanup_hook(void);
142 extern "C" ld_plugin_status
onload(ld_plugin_tv
*tv
);
143 ld_plugin_status
onload(ld_plugin_tv
*tv
) {
144 InitializeAllTargetInfos();
145 InitializeAllTargets();
146 InitializeAllTargetMCs();
147 InitializeAllAsmParsers();
148 InitializeAllAsmPrinters();
150 // We're given a pointer to the first transfer vector. We read through them
151 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
152 // contain pointers to functions that we need to call to register our own
153 // hooks. The others are addresses of functions we can use to call into gold
156 bool registeredClaimFile
= false;
157 bool RegisteredAllSymbolsRead
= false;
159 for (; tv
->tv_tag
!= LDPT_NULL
; ++tv
) {
160 switch (tv
->tv_tag
) {
161 case LDPT_OUTPUT_NAME
:
162 output_name
= tv
->tv_u
.tv_string
;
164 case LDPT_LINKER_OUTPUT
:
165 switch (tv
->tv_u
.tv_val
) {
167 case LDPO_DYN
: // .so
168 case LDPO_PIE
: // position independent executable
169 RelocationModel
= Reloc::PIC_
;
171 case LDPO_EXEC
: // .exe
172 RelocationModel
= Reloc::Static
;
175 message(LDPL_ERROR
, "Unknown output file type %d", tv
->tv_u
.tv_val
);
180 options::process_plugin_option(tv
->tv_u
.tv_string
);
182 case LDPT_REGISTER_CLAIM_FILE_HOOK
: {
183 ld_plugin_register_claim_file callback
;
184 callback
= tv
->tv_u
.tv_register_claim_file
;
186 if (callback(claim_file_hook
) != LDPS_OK
)
189 registeredClaimFile
= true;
191 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK
: {
192 ld_plugin_register_all_symbols_read callback
;
193 callback
= tv
->tv_u
.tv_register_all_symbols_read
;
195 if (callback(all_symbols_read_hook
) != LDPS_OK
)
198 RegisteredAllSymbolsRead
= true;
200 case LDPT_REGISTER_CLEANUP_HOOK
: {
201 ld_plugin_register_cleanup callback
;
202 callback
= tv
->tv_u
.tv_register_cleanup
;
204 if (callback(cleanup_hook
) != LDPS_OK
)
207 case LDPT_GET_INPUT_FILE
:
208 get_input_file
= tv
->tv_u
.tv_get_input_file
;
210 case LDPT_RELEASE_INPUT_FILE
:
211 release_input_file
= tv
->tv_u
.tv_release_input_file
;
213 case LDPT_ADD_SYMBOLS
:
214 add_symbols
= tv
->tv_u
.tv_add_symbols
;
216 case LDPT_GET_SYMBOLS_V2
:
217 get_symbols
= tv
->tv_u
.tv_get_symbols
;
219 case LDPT_ADD_INPUT_FILE
:
220 add_input_file
= tv
->tv_u
.tv_add_input_file
;
222 case LDPT_SET_EXTRA_LIBRARY_PATH
:
223 set_extra_library_path
= tv
->tv_u
.tv_set_extra_library_path
;
226 get_view
= tv
->tv_u
.tv_get_view
;
229 message
= tv
->tv_u
.tv_message
;
236 if (!registeredClaimFile
) {
237 message(LDPL_ERROR
, "register_claim_file not passed to LLVMgold.");
241 message(LDPL_ERROR
, "add_symbols not passed to LLVMgold.");
245 if (!RegisteredAllSymbolsRead
)
248 if (!get_input_file
) {
249 message(LDPL_ERROR
, "get_input_file not passed to LLVMgold.");
252 if (!release_input_file
) {
253 message(LDPL_ERROR
, "relesase_input_file not passed to LLVMgold.");
260 static const GlobalObject
*getBaseObject(const GlobalValue
&GV
) {
261 if (auto *GA
= dyn_cast
<GlobalAlias
>(&GV
))
262 return GA
->getBaseObject();
263 return cast
<GlobalObject
>(&GV
);
266 static bool shouldSkip(uint32_t Symflags
) {
267 if (!(Symflags
& object::BasicSymbolRef::SF_Global
))
269 if (Symflags
& object::BasicSymbolRef::SF_FormatSpecific
)
274 static void diagnosticHandler(const DiagnosticInfo
&DI
, void *Context
) {
275 assert(DI
.getSeverity() == DS_Error
&& "Only expecting errors");
276 const auto &BDI
= cast
<BitcodeDiagnosticInfo
>(DI
);
277 std::error_code EC
= BDI
.getError();
278 if (EC
== BitcodeError::InvalidBitcodeSignature
)
281 std::string ErrStorage
;
283 raw_string_ostream
OS(ErrStorage
);
284 DiagnosticPrinterRawOStream
DP(OS
);
287 message(LDPL_FATAL
, "LLVM gold plugin has failed to create LTO module: %s",
291 /// Called by gold to see whether this file is one that our plugin can handle.
292 /// We'll try to open it and register all the symbols with add_symbol if
294 static ld_plugin_status
claim_file_hook(const ld_plugin_input_file
*file
,
297 MemoryBufferRef BufferRef
;
298 std::unique_ptr
<MemoryBuffer
> Buffer
;
301 if (get_view(file
->handle
, &view
) != LDPS_OK
) {
302 message(LDPL_ERROR
, "Failed to get a view of %s", file
->name
);
305 BufferRef
= MemoryBufferRef(StringRef((const char *)view
, file
->filesize
), "");
308 // Gold has found what might be IR part-way inside of a file, such as
311 offset
= file
->offset
;
313 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOrErr
=
314 MemoryBuffer::getOpenFileSlice(file
->fd
, file
->name
, file
->filesize
,
316 if (std::error_code EC
= BufferOrErr
.getError()) {
317 message(LDPL_ERROR
, EC
.message().c_str());
320 Buffer
= std::move(BufferOrErr
.get());
321 BufferRef
= Buffer
->getMemBufferRef();
324 Context
.setDiagnosticHandler(diagnosticHandler
);
325 ErrorOr
<std::unique_ptr
<object::IRObjectFile
>> ObjOrErr
=
326 object::IRObjectFile::create(BufferRef
, Context
);
327 std::error_code EC
= ObjOrErr
.getError();
328 if (EC
== object::object_error::invalid_file_type
||
329 EC
== object::object_error::bitcode_section_not_found
)
335 message(LDPL_ERROR
, "LLVM gold plugin has failed to create LTO module: %s",
336 EC
.message().c_str());
339 std::unique_ptr
<object::IRObjectFile
> Obj
= std::move(*ObjOrErr
);
341 Modules
.resize(Modules
.size() + 1);
342 claimed_file
&cf
= Modules
.back();
344 cf
.handle
= file
->handle
;
346 for (auto &Sym
: Obj
->symbols()) {
347 uint32_t Symflags
= Sym
.getFlags();
348 if (shouldSkip(Symflags
))
351 cf
.syms
.push_back(ld_plugin_symbol());
352 ld_plugin_symbol
&sym
= cf
.syms
.back();
353 sym
.version
= nullptr;
355 SmallString
<64> Name
;
357 raw_svector_ostream
OS(Name
);
360 sym
.name
= strdup(Name
.c_str());
362 const GlobalValue
*GV
= Obj
->getSymbolGV(Sym
.getRawDataRefImpl());
364 sym
.visibility
= LDPV_DEFAULT
;
366 switch (GV
->getVisibility()) {
367 case GlobalValue::DefaultVisibility
:
368 sym
.visibility
= LDPV_DEFAULT
;
370 case GlobalValue::HiddenVisibility
:
371 sym
.visibility
= LDPV_HIDDEN
;
373 case GlobalValue::ProtectedVisibility
:
374 sym
.visibility
= LDPV_PROTECTED
;
379 if (Symflags
& object::BasicSymbolRef::SF_Undefined
) {
380 sym
.def
= LDPK_UNDEF
;
381 if (GV
&& GV
->hasExternalWeakLinkage())
382 sym
.def
= LDPK_WEAKUNDEF
;
386 assert(!GV
->hasExternalWeakLinkage() &&
387 !GV
->hasAvailableExternallyLinkage() && "Not a declaration!");
388 if (GV
->hasCommonLinkage())
389 sym
.def
= LDPK_COMMON
;
390 else if (GV
->isWeakForLinker())
391 sym
.def
= LDPK_WEAKDEF
;
396 sym
.comdat_key
= nullptr;
398 const GlobalObject
*Base
= getBaseObject(*GV
);
400 message(LDPL_FATAL
, "Unable to determine comdat of alias!");
401 const Comdat
*C
= Base
->getComdat();
403 sym
.comdat_key
= strdup(C
->getName().str().c_str());
404 else if (Base
->hasWeakLinkage() || Base
->hasLinkOnceLinkage())
405 sym
.comdat_key
= strdup(sym
.name
);
408 sym
.resolution
= LDPR_UNKNOWN
;
411 if (!cf
.syms
.empty()) {
412 if (add_symbols(cf
.handle
, cf
.syms
.size(), &cf
.syms
[0]) != LDPS_OK
) {
413 message(LDPL_ERROR
, "Unable to add symbols!");
421 static void keepGlobalValue(GlobalValue
&GV
,
422 std::vector
<GlobalAlias
*> &KeptAliases
) {
423 assert(!GV
.hasLocalLinkage());
425 if (auto *GA
= dyn_cast
<GlobalAlias
>(&GV
))
426 KeptAliases
.push_back(GA
);
428 switch (GV
.getLinkage()) {
431 case GlobalValue::LinkOnceAnyLinkage
:
432 GV
.setLinkage(GlobalValue::WeakAnyLinkage
);
434 case GlobalValue::LinkOnceODRLinkage
:
435 GV
.setLinkage(GlobalValue::WeakODRLinkage
);
439 assert(!GV
.isDiscardableIfUnused());
442 static void internalize(GlobalValue
&GV
) {
443 if (GV
.isDeclarationForLinker())
444 return; // We get here if there is a matching asm definition.
445 if (!GV
.hasLocalLinkage())
446 GV
.setLinkage(GlobalValue::InternalLinkage
);
449 static void drop(GlobalValue
&GV
) {
450 if (auto *F
= dyn_cast
<Function
>(&GV
)) {
452 F
->setComdat(nullptr); // Should deleteBody do this?
456 if (auto *Var
= dyn_cast
<GlobalVariable
>(&GV
)) {
457 Var
->setInitializer(nullptr);
459 GlobalValue::ExternalLinkage
); // Should setInitializer do this?
460 Var
->setComdat(nullptr); // and this?
464 auto &Alias
= cast
<GlobalAlias
>(GV
);
465 Module
&M
= *Alias
.getParent();
466 PointerType
&Ty
= *cast
<PointerType
>(Alias
.getType());
467 GlobalValue::LinkageTypes L
= Alias
.getLinkage();
469 new GlobalVariable(M
, Ty
.getElementType(), /*isConstant*/ false, L
,
470 /*Initializer*/ nullptr);
471 Var
->takeName(&Alias
);
472 Alias
.replaceAllUsesWith(Var
);
473 Alias
.eraseFromParent();
476 static const char *getResolutionName(ld_plugin_symbol_resolution R
) {
482 case LDPR_PREVAILING_DEF
:
483 return "PREVAILING_DEF";
484 case LDPR_PREVAILING_DEF_IRONLY
:
485 return "PREVAILING_DEF_IRONLY";
486 case LDPR_PREEMPTED_REG
:
487 return "PREEMPTED_REG";
488 case LDPR_PREEMPTED_IR
:
489 return "PREEMPTED_IR";
490 case LDPR_RESOLVED_IR
:
491 return "RESOLVED_IR";
492 case LDPR_RESOLVED_EXEC
:
493 return "RESOLVED_EXEC";
494 case LDPR_RESOLVED_DYN
:
495 return "RESOLVED_DYN";
496 case LDPR_PREVAILING_DEF_IRONLY_EXP
:
497 return "PREVAILING_DEF_IRONLY_EXP";
499 llvm_unreachable("Unknown resolution");
503 class LocalValueMaterializer
: public ValueMaterializer
{
504 DenseSet
<GlobalValue
*> &Dropped
;
505 DenseMap
<GlobalObject
*, GlobalObject
*> LocalVersions
;
508 LocalValueMaterializer(DenseSet
<GlobalValue
*> &Dropped
) : Dropped(Dropped
) {}
509 Value
*materializeValueFor(Value
*V
) override
;
513 Value
*LocalValueMaterializer::materializeValueFor(Value
*V
) {
514 auto *GO
= dyn_cast
<GlobalObject
>(V
);
518 auto I
= LocalVersions
.find(GO
);
519 if (I
!= LocalVersions
.end())
522 if (!Dropped
.count(GO
))
525 Module
&M
= *GO
->getParent();
526 GlobalValue::LinkageTypes L
= GO
->getLinkage();
527 GlobalObject
*Declaration
;
528 if (auto *F
= dyn_cast
<Function
>(GO
)) {
529 Declaration
= Function::Create(F
->getFunctionType(), L
, "", &M
);
531 auto *Var
= cast
<GlobalVariable
>(GO
);
532 Declaration
= new GlobalVariable(M
, Var
->getType()->getElementType(),
533 Var
->isConstant(), L
,
534 /*Initializer*/ nullptr);
536 Declaration
->takeName(GO
);
537 Declaration
->copyAttributesFrom(GO
);
539 GO
->setLinkage(GlobalValue::InternalLinkage
);
540 GO
->setName(Declaration
->getName());
542 GO
->replaceAllUsesWith(Declaration
);
544 LocalVersions
[Declaration
] = GO
;
549 static Constant
*mapConstantToLocalCopy(Constant
*C
, ValueToValueMapTy
&VM
,
550 LocalValueMaterializer
*Materializer
) {
551 return MapValue(C
, VM
, RF_IgnoreMissingEntries
, nullptr, Materializer
);
554 static void freeSymName(ld_plugin_symbol
&Sym
) {
556 free(Sym
.comdat_key
);
558 Sym
.comdat_key
= nullptr;
561 static std::unique_ptr
<Module
>
562 getModuleForFile(LLVMContext
&Context
, claimed_file
&F
,
563 off_t Filesize
, raw_fd_ostream
*ApiFile
,
564 StringSet
<> &Internalize
, StringSet
<> &Maybe
) {
566 if (get_symbols(F
.handle
, F
.syms
.size(), &F
.syms
[0]) != LDPS_OK
)
567 message(LDPL_FATAL
, "Failed to get symbol information");
570 if (get_view(F
.handle
, &View
) != LDPS_OK
)
571 message(LDPL_FATAL
, "Failed to get a view of file");
573 MemoryBufferRef
BufferRef(StringRef((const char *)View
, Filesize
), "");
574 ErrorOr
<std::unique_ptr
<object::IRObjectFile
>> ObjOrErr
=
575 object::IRObjectFile::create(BufferRef
, Context
);
577 if (std::error_code EC
= ObjOrErr
.getError())
578 message(LDPL_FATAL
, "Could not read bitcode from file : %s",
579 EC
.message().c_str());
581 object::IRObjectFile
&Obj
= **ObjOrErr
;
583 Module
&M
= Obj
.getModule();
585 SmallPtrSet
<GlobalValue
*, 8> Used
;
586 collectUsedGlobalVariables(M
, Used
, /*CompilerUsed*/ false);
588 DenseSet
<GlobalValue
*> Drop
;
589 std::vector
<GlobalAlias
*> KeptAliases
;
592 for (auto &ObjSym
: Obj
.symbols()) {
593 if (shouldSkip(ObjSym
.getFlags()))
595 ld_plugin_symbol
&Sym
= F
.syms
[SymNum
];
598 ld_plugin_symbol_resolution Resolution
=
599 (ld_plugin_symbol_resolution
)Sym
.resolution
;
601 if (options::generate_api_file
)
602 *ApiFile
<< Sym
.name
<< ' ' << getResolutionName(Resolution
) << '\n';
604 GlobalValue
*GV
= Obj
.getSymbolGV(ObjSym
.getRawDataRefImpl());
607 continue; // Asm symbol.
610 if (Resolution
!= LDPR_PREVAILING_DEF_IRONLY
&& GV
->hasCommonLinkage()) {
611 // Common linkage is special. There is no single symbol that wins the
612 // resolution. Instead we have to collect the maximum alignment and size.
613 // The IR linker does that for us if we just pass it every common GV.
614 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
615 // internalize once the IR linker has done its job.
620 switch (Resolution
) {
622 llvm_unreachable("Unexpected resolution");
624 case LDPR_RESOLVED_IR
:
625 case LDPR_RESOLVED_EXEC
:
626 case LDPR_RESOLVED_DYN
:
627 assert(GV
->isDeclarationForLinker());
631 if (!GV
->isDeclarationForLinker()) {
632 assert(GV
->hasComdat());
637 case LDPR_PREVAILING_DEF_IRONLY
: {
638 keepGlobalValue(*GV
, KeptAliases
);
639 if (!Used
.count(GV
)) {
640 // Since we use the regular lib/Linker, we cannot just internalize GV
641 // now or it will not be copied to the merged module. Instead we force
642 // it to be copied and then internalize it.
643 Internalize
.insert(GV
->getName());
648 case LDPR_PREVAILING_DEF
:
649 keepGlobalValue(*GV
, KeptAliases
);
652 case LDPR_PREEMPTED_IR
:
653 // Gold might have selected a linkonce_odr and preempted a weak_odr.
654 // In that case we have to make sure we don't end up internalizing it.
655 if (!GV
->isDiscardableIfUnused())
656 Maybe
.erase(GV
->getName());
659 case LDPR_PREEMPTED_REG
:
663 case LDPR_PREVAILING_DEF_IRONLY_EXP
: {
664 // We can only check for address uses after we merge the modules. The
665 // reason is that this GV might have a copy in another module
666 // and in that module the address might be significant, but that
667 // copy will be LDPR_PREEMPTED_IR.
668 if (GV
->hasLinkOnceODRLinkage())
669 Maybe
.insert(GV
->getName());
670 keepGlobalValue(*GV
, KeptAliases
);
678 ValueToValueMapTy VM
;
679 LocalValueMaterializer
Materializer(Drop
);
680 for (GlobalAlias
*GA
: KeptAliases
) {
681 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
682 // expression is being dropped. If that is the case, that GV must be copied.
683 Constant
*Aliasee
= GA
->getAliasee();
684 Constant
*Replacement
= mapConstantToLocalCopy(Aliasee
, VM
, &Materializer
);
685 GA
->setAliasee(Replacement
);
688 for (auto *GV
: Drop
)
691 return Obj
.takeModule();
694 static void runLTOPasses(Module
&M
, TargetMachine
&TM
) {
696 PassManagerBuilder PMB
;
697 PMB
.LibraryInfo
= new TargetLibraryInfo(Triple(TM
.getTargetTriple()));
698 PMB
.Inliner
= createFunctionInliningPass();
699 PMB
.VerifyInput
= true;
700 PMB
.VerifyOutput
= true;
701 PMB
.LoopVectorize
= true;
702 PMB
.SLPVectorize
= true;
703 PMB
.populateLTOPassManager(passes
, &TM
);
707 static void saveBCFile(StringRef Path
, Module
&M
) {
709 raw_fd_ostream
OS(Path
, EC
, sys::fs::OpenFlags::F_None
);
711 message(LDPL_FATAL
, "Failed to write the output file.");
712 WriteBitcodeToFile(&M
, OS
);
715 static void codegen(Module
&M
) {
716 const std::string
&TripleStr
= M
.getTargetTriple();
717 Triple
TheTriple(TripleStr
);
720 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleStr
, ErrMsg
);
722 message(LDPL_FATAL
, "Target not found: %s", ErrMsg
.c_str());
724 if (unsigned NumOpts
= options::extra
.size())
725 cl::ParseCommandLineOptions(NumOpts
, &options::extra
[0]);
727 SubtargetFeatures Features
;
728 Features
.getDefaultSubtargetFeatures(TheTriple
);
729 for (const std::string
&A
: MAttrs
)
730 Features
.AddFeature(A
);
732 TargetOptions Options
= InitTargetOptionsFromCodeGenFlags();
733 std::unique_ptr
<TargetMachine
> TM(TheTarget
->createTargetMachine(
734 TripleStr
, options::mcpu
, Features
.getString(), Options
, RelocationModel
,
735 CodeModel::Default
, CodeGenOpt::Aggressive
));
737 runLTOPasses(M
, *TM
);
739 if (options::TheOutputType
== options::OT_SAVE_TEMPS
)
740 saveBCFile(output_name
+ ".opt.bc", M
);
742 PassManager CodeGenPasses
;
743 CodeGenPasses
.add(new DataLayoutPass());
745 SmallString
<128> Filename
;
747 if (options::obj_path
.empty()) {
749 sys::fs::createTemporaryFile("lto-llvm", "o", FD
, Filename
);
751 message(LDPL_FATAL
, "Could not create temporary file: %s",
752 EC
.message().c_str());
754 Filename
= options::obj_path
;
756 sys::fs::openFileForWrite(Filename
.c_str(), FD
, sys::fs::F_None
);
758 message(LDPL_FATAL
, "Could not open file: %s", EC
.message().c_str());
762 raw_fd_ostream
OS(FD
, true);
763 formatted_raw_ostream
FOS(OS
);
765 if (TM
->addPassesToEmitFile(CodeGenPasses
, FOS
,
766 TargetMachine::CGFT_ObjectFile
))
767 message(LDPL_FATAL
, "Failed to setup codegen");
768 CodeGenPasses
.run(M
);
771 if (add_input_file(Filename
.c_str()) != LDPS_OK
)
773 "Unable to add .o file to the link. File left behind in: %s",
776 if (options::obj_path
.empty())
777 Cleanup
.push_back(Filename
.c_str());
780 /// gold informs us that all symbols have been read. At this point, we use
781 /// get_symbols to see if any of our definitions have been overridden by a
782 /// native object file. Then, perform optimization and codegen.
783 static ld_plugin_status
allSymbolsReadHook(raw_fd_ostream
*ApiFile
) {
788 std::unique_ptr
<Module
> Combined(new Module("ld-temp.o", Context
));
789 Linker
L(Combined
.get());
791 std::string DefaultTriple
= sys::getDefaultTargetTriple();
793 StringSet
<> Internalize
;
795 for (claimed_file
&F
: Modules
) {
796 ld_plugin_input_file File
;
797 if (get_input_file(F
.handle
, &File
) != LDPS_OK
)
798 message(LDPL_FATAL
, "Failed to get file information");
799 std::unique_ptr
<Module
> M
=
800 getModuleForFile(Context
, F
, File
.filesize
, ApiFile
,
802 if (!options::triple
.empty())
803 M
->setTargetTriple(options::triple
.c_str());
804 else if (M
->getTargetTriple().empty()) {
805 M
->setTargetTriple(DefaultTriple
);
808 if (L
.linkInModule(M
.get()))
809 message(LDPL_FATAL
, "Failed to link module");
810 if (release_input_file(F
.handle
) != LDPS_OK
)
811 message(LDPL_FATAL
, "Failed to release file information");
814 for (const auto &Name
: Internalize
) {
815 GlobalValue
*GV
= Combined
->getNamedValue(Name
.first());
820 for (const auto &Name
: Maybe
) {
821 GlobalValue
*GV
= Combined
->getNamedValue(Name
.first());
824 GV
->setLinkage(GlobalValue::LinkOnceODRLinkage
);
825 if (canBeOmittedFromSymbolTable(GV
))
829 if (options::TheOutputType
== options::OT_DISABLE
)
832 if (options::TheOutputType
!= options::OT_NORMAL
) {
834 if (options::TheOutputType
== options::OT_BC_ONLY
)
837 path
= output_name
+ ".bc";
838 saveBCFile(path
, *L
.getModule());
839 if (options::TheOutputType
== options::OT_BC_ONLY
)
843 codegen(*L
.getModule());
845 if (!options::extra_library_path
.empty() &&
846 set_extra_library_path(options::extra_library_path
.c_str()) != LDPS_OK
)
847 message(LDPL_FATAL
, "Unable to set the extra library path.");
852 static ld_plugin_status
all_symbols_read_hook(void) {
853 ld_plugin_status Ret
;
854 if (!options::generate_api_file
) {
855 Ret
= allSymbolsReadHook(nullptr);
858 raw_fd_ostream
ApiFile("apifile.txt", EC
, sys::fs::F_None
);
860 message(LDPL_FATAL
, "Unable to open apifile.txt for writing: %s",
861 EC
.message().c_str());
862 Ret
= allSymbolsReadHook(&ApiFile
);
867 if (options::TheOutputType
== options::OT_BC_ONLY
||
868 options::TheOutputType
== options::OT_DISABLE
)
874 static ld_plugin_status
cleanup_hook(void) {
875 for (std::string
&Name
: Cleanup
) {
876 std::error_code EC
= sys::fs::remove(Name
);
878 message(LDPL_ERROR
, "Failed to delete '%s': %s", Name
.c_str(),
879 EC
.message().c_str());