LTO: introduce object file-based on-disk module format.
[oota-llvm.git] / tools / gold / gold-plugin.cpp
1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization  ------===//
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 is a gold plugin for LLVM. It provides an LLVM implementation of the
11 // interface described in http://gcc.gnu.org/wiki/whopr/driver .
12 //
13 //===----------------------------------------------------------------------===//
14
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/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Transforms/Utils/GlobalStatus.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
39 #include "llvm/Transforms/Utils/ValueMapper.h"
40 #include <list>
41 #include <plugin-api.h>
42 #include <system_error>
43 #include <vector>
44
45 #ifndef LDPO_PIE
46 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
47 // Precise and Debian Wheezy (binutils 2.23 is required)
48 # define LDPO_PIE 3
49 #endif
50
51 using namespace llvm;
52
53 namespace {
54 struct claimed_file {
55   void *handle;
56   std::vector<ld_plugin_symbol> syms;
57 };
58 }
59
60 static ld_plugin_status discard_message(int level, const char *format, ...) {
61   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
62   // callback in the transfer vector. This should never be called.
63   abort();
64 }
65
66 static ld_plugin_get_input_file get_input_file = nullptr;
67 static ld_plugin_release_input_file release_input_file = nullptr;
68 static ld_plugin_add_symbols add_symbols = nullptr;
69 static ld_plugin_get_symbols get_symbols = nullptr;
70 static ld_plugin_add_input_file add_input_file = nullptr;
71 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
72 static ld_plugin_get_view get_view = nullptr;
73 static ld_plugin_message message = discard_message;
74 static Reloc::Model RelocationModel = Reloc::Default;
75 static std::string output_name = "";
76 static std::list<claimed_file> Modules;
77 static std::vector<std::string> Cleanup;
78 static llvm::TargetOptions TargetOpts;
79
80 namespace options {
81   enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
82   static bool generate_api_file = false;
83   static generate_bc generate_bc_file = BC_NO;
84   static std::string bc_path;
85   static std::string obj_path;
86   static std::string extra_library_path;
87   static std::string triple;
88   static std::string mcpu;
89   // Additional options to pass into the code generator.
90   // Note: This array will contain all plugin options which are not claimed
91   // as plugin exclusive to pass to the code generator.
92   // For example, "generate-api-file" and "as"options are for the plugin
93   // use only and will not be passed.
94   static std::vector<const char *> extra;
95
96   static void process_plugin_option(const char* opt_)
97   {
98     if (opt_ == nullptr)
99       return;
100     llvm::StringRef opt = opt_;
101
102     if (opt == "generate-api-file") {
103       generate_api_file = true;
104     } else if (opt.startswith("mcpu=")) {
105       mcpu = opt.substr(strlen("mcpu="));
106     } else if (opt.startswith("extra-library-path=")) {
107       extra_library_path = opt.substr(strlen("extra_library_path="));
108     } else if (opt.startswith("mtriple=")) {
109       triple = opt.substr(strlen("mtriple="));
110     } else if (opt.startswith("obj-path=")) {
111       obj_path = opt.substr(strlen("obj-path="));
112     } else if (opt == "emit-llvm") {
113       generate_bc_file = BC_ONLY;
114     } else if (opt == "also-emit-llvm") {
115       generate_bc_file = BC_ALSO;
116     } else if (opt.startswith("also-emit-llvm=")) {
117       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
118       generate_bc_file = BC_ALSO;
119       if (!bc_path.empty()) {
120         message(LDPL_WARNING, "Path to the output IL file specified twice. "
121                               "Discarding %s",
122                 opt_);
123       } else {
124         bc_path = path;
125       }
126     } else {
127       // Save this option to pass to the code generator.
128       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
129       // add that.
130       if (extra.empty())
131         extra.push_back("LLVMgold");
132
133       extra.push_back(opt_);
134     }
135   }
136 }
137
138 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
139                                         int *claimed);
140 static ld_plugin_status all_symbols_read_hook(void);
141 static ld_plugin_status cleanup_hook(void);
142
143 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
144 ld_plugin_status onload(ld_plugin_tv *tv) {
145   InitializeAllTargetInfos();
146   InitializeAllTargets();
147   InitializeAllTargetMCs();
148   InitializeAllAsmParsers();
149   InitializeAllAsmPrinters();
150
151   // We're given a pointer to the first transfer vector. We read through them
152   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
153   // contain pointers to functions that we need to call to register our own
154   // hooks. The others are addresses of functions we can use to call into gold
155   // for services.
156
157   bool registeredClaimFile = false;
158   bool RegisteredAllSymbolsRead = false;
159
160   for (; tv->tv_tag != LDPT_NULL; ++tv) {
161     switch (tv->tv_tag) {
162       case LDPT_OUTPUT_NAME:
163         output_name = tv->tv_u.tv_string;
164         break;
165       case LDPT_LINKER_OUTPUT:
166         switch (tv->tv_u.tv_val) {
167           case LDPO_REL:  // .o
168           case LDPO_DYN:  // .so
169           case LDPO_PIE:  // position independent executable
170             RelocationModel = Reloc::PIC_;
171             break;
172           case LDPO_EXEC:  // .exe
173             RelocationModel = Reloc::Static;
174             break;
175           default:
176             message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
177             return LDPS_ERR;
178         }
179         break;
180       case LDPT_OPTION:
181         options::process_plugin_option(tv->tv_u.tv_string);
182         break;
183       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
184         ld_plugin_register_claim_file callback;
185         callback = tv->tv_u.tv_register_claim_file;
186
187         if (callback(claim_file_hook) != LDPS_OK)
188           return LDPS_ERR;
189
190         registeredClaimFile = true;
191       } break;
192       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
193         ld_plugin_register_all_symbols_read callback;
194         callback = tv->tv_u.tv_register_all_symbols_read;
195
196         if (callback(all_symbols_read_hook) != LDPS_OK)
197           return LDPS_ERR;
198
199         RegisteredAllSymbolsRead = true;
200       } break;
201       case LDPT_REGISTER_CLEANUP_HOOK: {
202         ld_plugin_register_cleanup callback;
203         callback = tv->tv_u.tv_register_cleanup;
204
205         if (callback(cleanup_hook) != LDPS_OK)
206           return LDPS_ERR;
207       } break;
208       case LDPT_GET_INPUT_FILE:
209         get_input_file = tv->tv_u.tv_get_input_file;
210         break;
211       case LDPT_RELEASE_INPUT_FILE:
212         release_input_file = tv->tv_u.tv_release_input_file;
213         break;
214       case LDPT_ADD_SYMBOLS:
215         add_symbols = tv->tv_u.tv_add_symbols;
216         break;
217       case LDPT_GET_SYMBOLS_V2:
218         get_symbols = tv->tv_u.tv_get_symbols;
219         break;
220       case LDPT_ADD_INPUT_FILE:
221         add_input_file = tv->tv_u.tv_add_input_file;
222         break;
223       case LDPT_SET_EXTRA_LIBRARY_PATH:
224         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
225         break;
226       case LDPT_GET_VIEW:
227         get_view = tv->tv_u.tv_get_view;
228         break;
229       case LDPT_MESSAGE:
230         message = tv->tv_u.tv_message;
231         break;
232       default:
233         break;
234     }
235   }
236
237   if (!registeredClaimFile) {
238     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
239     return LDPS_ERR;
240   }
241   if (!add_symbols) {
242     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
243     return LDPS_ERR;
244   }
245
246   if (!RegisteredAllSymbolsRead)
247     return LDPS_OK;
248
249   if (!get_input_file) {
250     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
251     return LDPS_ERR;
252   }
253   if (!release_input_file) {
254     message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
255     return LDPS_ERR;
256   }
257
258   return LDPS_OK;
259 }
260
261 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
262   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
263     return GA->getBaseObject();
264   return cast<GlobalObject>(&GV);
265 }
266
267 /// Called by gold to see whether this file is one that our plugin can handle.
268 /// We'll try to open it and register all the symbols with add_symbol if
269 /// possible.
270 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
271                                         int *claimed) {
272   LLVMContext Context;
273   MemoryBufferRef BufferRef;
274   std::unique_ptr<MemoryBuffer> Buffer;
275   if (get_view) {
276     const void *view;
277     if (get_view(file->handle, &view) != LDPS_OK) {
278       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
279       return LDPS_ERR;
280     }
281     BufferRef = MemoryBufferRef(StringRef((char *)view, file->filesize), "");
282   } else {
283     int64_t offset = 0;
284     // Gold has found what might be IR part-way inside of a file, such as
285     // an .a archive.
286     if (file->offset) {
287       offset = file->offset;
288     }
289     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
290         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
291                                        offset);
292     if (std::error_code EC = BufferOrErr.getError()) {
293       message(LDPL_ERROR, EC.message().c_str());
294       return LDPS_ERR;
295     }
296     Buffer = std::move(BufferOrErr.get());
297     BufferRef = Buffer->getMemBufferRef();
298   }
299
300   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
301       object::IRObjectFile::createIRObjectFile(BufferRef, Context);
302   std::error_code EC = ObjOrErr.getError();
303   if (EC == BitcodeError::InvalidBitcodeSignature ||
304       EC == object::object_error::invalid_file_type ||
305       EC == object::object_error::bitcode_section_not_found)
306     return LDPS_OK;
307
308   *claimed = 1;
309
310   if (EC) {
311     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
312             EC.message().c_str());
313     return LDPS_ERR;
314   }
315   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
316
317   Modules.resize(Modules.size() + 1);
318   claimed_file &cf = Modules.back();
319
320   cf.handle = file->handle;
321
322   for (auto &Sym : Obj->symbols()) {
323     uint32_t Symflags = Sym.getFlags();
324     if (!(Symflags & object::BasicSymbolRef::SF_Global))
325       continue;
326
327     if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
328       continue;
329
330     cf.syms.push_back(ld_plugin_symbol());
331     ld_plugin_symbol &sym = cf.syms.back();
332     sym.version = nullptr;
333
334     SmallString<64> Name;
335     {
336       raw_svector_ostream OS(Name);
337       Sym.printName(OS);
338     }
339     sym.name = strdup(Name.c_str());
340
341     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
342
343     sym.visibility = LDPV_DEFAULT;
344     if (GV) {
345       switch (GV->getVisibility()) {
346       case GlobalValue::DefaultVisibility:
347         sym.visibility = LDPV_DEFAULT;
348         break;
349       case GlobalValue::HiddenVisibility:
350         sym.visibility = LDPV_HIDDEN;
351         break;
352       case GlobalValue::ProtectedVisibility:
353         sym.visibility = LDPV_PROTECTED;
354         break;
355       }
356     }
357
358     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
359       sym.def = LDPK_UNDEF;
360       if (GV && GV->hasExternalWeakLinkage())
361         sym.def = LDPK_WEAKUNDEF;
362     } else {
363       sym.def = LDPK_DEF;
364       if (GV) {
365         assert(!GV->hasExternalWeakLinkage() &&
366                !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
367         if (GV->hasCommonLinkage())
368           sym.def = LDPK_COMMON;
369         else if (GV->isWeakForLinker())
370           sym.def = LDPK_WEAKDEF;
371       }
372     }
373
374     sym.size = 0;
375     sym.comdat_key = nullptr;
376     if (GV) {
377       const GlobalObject *Base = getBaseObject(*GV);
378       if (!Base)
379         message(LDPL_FATAL, "Unable to determine comdat of alias!");
380       const Comdat *C = Base->getComdat();
381       if (C)
382         sym.comdat_key = strdup(C->getName().str().c_str());
383       else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
384         sym.comdat_key = strdup(sym.name);
385     }
386
387     sym.resolution = LDPR_UNKNOWN;
388   }
389
390   if (!cf.syms.empty()) {
391     if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
392       message(LDPL_ERROR, "Unable to add symbols!");
393       return LDPS_ERR;
394     }
395   }
396
397   return LDPS_OK;
398 }
399
400 static void keepGlobalValue(GlobalValue &GV,
401                             std::vector<GlobalAlias *> &KeptAliases) {
402   assert(!GV.hasLocalLinkage());
403
404   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
405     KeptAliases.push_back(GA);
406
407   switch (GV.getLinkage()) {
408   default:
409     break;
410   case GlobalValue::LinkOnceAnyLinkage:
411     GV.setLinkage(GlobalValue::WeakAnyLinkage);
412     break;
413   case GlobalValue::LinkOnceODRLinkage:
414     GV.setLinkage(GlobalValue::WeakODRLinkage);
415     break;
416   }
417
418   assert(!GV.isDiscardableIfUnused());
419 }
420
421 static bool isDeclaration(const GlobalValue &V) {
422   if (V.hasAvailableExternallyLinkage())
423     return true;
424
425   if (V.isMaterializable())
426     return false;
427
428   return V.isDeclaration();
429 }
430
431 static void internalize(GlobalValue &GV) {
432   if (isDeclaration(GV))
433     return; // We get here if there is a matching asm definition.
434   if (!GV.hasLocalLinkage())
435     GV.setLinkage(GlobalValue::InternalLinkage);
436 }
437
438 static void drop(GlobalValue &GV) {
439   if (auto *F = dyn_cast<Function>(&GV)) {
440     F->deleteBody();
441     F->setComdat(nullptr); // Should deleteBody do this?
442     return;
443   }
444
445   if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
446     Var->setInitializer(nullptr);
447     Var->setLinkage(
448         GlobalValue::ExternalLinkage); // Should setInitializer do this?
449     Var->setComdat(nullptr); // and this?
450     return;
451   }
452
453   auto &Alias = cast<GlobalAlias>(GV);
454   Module &M = *Alias.getParent();
455   PointerType &Ty = *cast<PointerType>(Alias.getType());
456   GlobalValue::LinkageTypes L = Alias.getLinkage();
457   auto *Var =
458       new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
459                          /*Initializer*/ nullptr);
460   Var->takeName(&Alias);
461   Alias.replaceAllUsesWith(Var);
462   Alias.eraseFromParent();
463 }
464
465 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
466   switch (R) {
467   case LDPR_UNKNOWN:
468     return "UNKNOWN";
469   case LDPR_UNDEF:
470     return "UNDEF";
471   case LDPR_PREVAILING_DEF:
472     return "PREVAILING_DEF";
473   case LDPR_PREVAILING_DEF_IRONLY:
474     return "PREVAILING_DEF_IRONLY";
475   case LDPR_PREEMPTED_REG:
476     return "PREEMPTED_REG";
477   case LDPR_PREEMPTED_IR:
478     return "PREEMPTED_IR";
479   case LDPR_RESOLVED_IR:
480     return "RESOLVED_IR";
481   case LDPR_RESOLVED_EXEC:
482     return "RESOLVED_EXEC";
483   case LDPR_RESOLVED_DYN:
484     return "RESOLVED_DYN";
485   case LDPR_PREVAILING_DEF_IRONLY_EXP:
486     return "PREVAILING_DEF_IRONLY_EXP";
487   }
488 }
489
490 static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
491   Module *M = GO->getParent();
492   GlobalObject *Ret;
493   if (auto *F = dyn_cast<Function>(GO)) {
494     auto *NewF = Function::Create(
495         F->getFunctionType(), GlobalValue::InternalLinkage, F->getName(), M);
496     NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
497     Ret = NewF;
498     F->deleteBody();
499   } else {
500     auto *Var = cast<GlobalVariable>(GO);
501     Ret = new GlobalVariable(
502         *M, Var->getType()->getElementType(), Var->isConstant(),
503         GlobalValue::InternalLinkage, Var->getInitializer(), Var->getName(),
504         nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
505         Var->isExternallyInitialized());
506     Var->setInitializer(nullptr);
507   }
508   Ret->copyAttributesFrom(GO);
509   Ret->setComdat(GO->getComdat());
510
511   return Ret;
512 }
513
514 namespace {
515 class LocalValueMaterializer : public ValueMaterializer {
516   DenseSet<GlobalValue *> &Dropped;
517
518 public:
519   LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
520   Value *materializeValueFor(Value *V) override;
521 };
522 }
523
524 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
525   auto *GV = dyn_cast<GlobalValue>(V);
526   if (!GV)
527     return nullptr;
528   if (!Dropped.count(GV))
529     return nullptr;
530   assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
531   return makeInternalReplacement(cast<GlobalObject>(GV));
532 }
533
534 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
535                                         LocalValueMaterializer *Materializer) {
536   return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
537 }
538
539 static std::unique_ptr<Module>
540 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
541                  StringSet<> &Internalize, StringSet<> &Maybe) {
542   ld_plugin_input_file File;
543   if (get_input_file(F.handle, &File) != LDPS_OK)
544     message(LDPL_FATAL, "Failed to get file information");
545
546   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
547     message(LDPL_FATAL, "Failed to get symbol information");
548
549   const void *View;
550   if (get_view(F.handle, &View) != LDPS_OK)
551     message(LDPL_FATAL, "Failed to get a view of file");
552
553   llvm::ErrorOr<MemoryBufferRef> MBOrErr =
554       object::IRObjectFile::findBitcodeInMemBuffer(
555           MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
556   if (std::error_code EC = MBOrErr.getError())
557     message(LDPL_FATAL, "Could not read bitcode from file : %s",
558             EC.message().c_str());
559
560   std::unique_ptr<MemoryBuffer> Buffer =
561       MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
562
563   if (release_input_file(F.handle) != LDPS_OK)
564     message(LDPL_FATAL, "Failed to release file information");
565
566   ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
567
568   if (std::error_code EC = MOrErr.getError())
569     message(LDPL_FATAL, "Could not read bitcode from file : %s",
570             EC.message().c_str());
571
572   std::unique_ptr<Module> M(MOrErr.get());
573
574   SmallPtrSet<GlobalValue *, 8> Used;
575   collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
576
577   DenseSet<GlobalValue *> Drop;
578   std::vector<GlobalAlias *> KeptAliases;
579   for (ld_plugin_symbol &Sym : F.syms) {
580     ld_plugin_symbol_resolution Resolution =
581         (ld_plugin_symbol_resolution)Sym.resolution;
582
583     if (options::generate_api_file)
584       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
585
586     GlobalValue *GV = M->getNamedValue(Sym.name);
587     if (!GV)
588       continue; // Asm symbol.
589
590     if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
591       // Common linkage is special. There is no single symbol that wins the
592       // resolution. Instead we have to collect the maximum alignment and size.
593       // The IR linker does that for us if we just pass it every common GV.
594       // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
595       // internalize once the IR linker has done its job.
596       continue;
597     }
598
599     switch (Resolution) {
600     case LDPR_UNKNOWN:
601       llvm_unreachable("Unexpected resolution");
602
603     case LDPR_RESOLVED_IR:
604     case LDPR_RESOLVED_EXEC:
605     case LDPR_RESOLVED_DYN:
606     case LDPR_UNDEF:
607       assert(isDeclaration(*GV));
608       break;
609
610     case LDPR_PREVAILING_DEF_IRONLY: {
611       keepGlobalValue(*GV, KeptAliases);
612       if (!Used.count(GV)) {
613         // Since we use the regular lib/Linker, we cannot just internalize GV
614         // now or it will not be copied to the merged module. Instead we force
615         // it to be copied and then internalize it.
616         Internalize.insert(Sym.name);
617       }
618       break;
619     }
620
621     case LDPR_PREVAILING_DEF:
622       keepGlobalValue(*GV, KeptAliases);
623       break;
624
625     case LDPR_PREEMPTED_REG:
626     case LDPR_PREEMPTED_IR:
627       Drop.insert(GV);
628       break;
629
630     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
631       // We can only check for address uses after we merge the modules. The
632       // reason is that this GV might have a copy in another module
633       // and in that module the address might be significant, but that
634       // copy will be LDPR_PREEMPTED_IR.
635       if (GV->hasLinkOnceODRLinkage())
636         Maybe.insert(Sym.name);
637       keepGlobalValue(*GV, KeptAliases);
638       break;
639     }
640     }
641
642     free(Sym.name);
643     free(Sym.comdat_key);
644     Sym.name = nullptr;
645     Sym.comdat_key = nullptr;
646   }
647
648   if (!Drop.empty())
649     // This is horrible. Given how lazy loading is implemented, dropping
650     // the body while there is a materializer present doesn't work, the
651     // linker will just read the body back.
652     M->materializeAllPermanently();
653
654   ValueToValueMapTy VM;
655   LocalValueMaterializer Materializer(Drop);
656   for (GlobalAlias *GA : KeptAliases) {
657     // Gold told us to keep GA. It is possible that a GV usied in the aliasee
658     // expression is being dropped. If that is the case, that GV must be copied.
659     Constant *Aliasee = GA->getAliasee();
660     Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
661     if (Aliasee != Replacement)
662       GA->setAliasee(Replacement);
663   }
664
665   for (auto *GV : Drop)
666     drop(*GV);
667
668   return M;
669 }
670
671 static void runLTOPasses(Module &M, TargetMachine &TM) {
672   PassManager passes;
673   PassManagerBuilder PMB;
674   PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
675   PMB.Inliner = createFunctionInliningPass();
676   PMB.VerifyInput = true;
677   PMB.VerifyOutput = true;
678   PMB.populateLTOPassManager(passes, &TM);
679   passes.run(M);
680 }
681
682 static void codegen(Module &M) {
683   const std::string &TripleStr = M.getTargetTriple();
684   Triple TheTriple(TripleStr);
685
686   std::string ErrMsg;
687   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
688   if (!TheTarget)
689     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
690
691   if (unsigned NumOpts = options::extra.size())
692     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
693
694   SubtargetFeatures Features;
695   Features.getDefaultSubtargetFeatures(TheTriple);
696   for (const std::string &A : MAttrs)
697     Features.AddFeature(A);
698
699   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
700   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
701       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
702       CodeModel::Default, CodeGenOpt::Aggressive));
703
704   runLTOPasses(M, *TM);
705
706   PassManager CodeGenPasses;
707   CodeGenPasses.add(new DataLayoutPass());
708
709   SmallString<128> Filename;
710   int FD;
711   if (options::obj_path.empty()) {
712     std::error_code EC =
713         sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
714     if (EC)
715       message(LDPL_FATAL, "Could not create temorary file: %s",
716               EC.message().c_str());
717   } else {
718     Filename = options::obj_path;
719     std::error_code EC =
720         sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
721     if (EC)
722       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
723   }
724
725   {
726     raw_fd_ostream OS(FD, true);
727     formatted_raw_ostream FOS(OS);
728
729     if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
730                                 TargetMachine::CGFT_ObjectFile))
731       message(LDPL_FATAL, "Failed to setup codegen");
732     CodeGenPasses.run(M);
733   }
734
735   if (add_input_file(Filename.c_str()) != LDPS_OK)
736     message(LDPL_FATAL,
737             "Unable to add .o file to the link. File left behind in: %s",
738             Filename.c_str());
739
740   if (options::obj_path.empty())
741     Cleanup.push_back(Filename.c_str());
742 }
743
744 /// gold informs us that all symbols have been read. At this point, we use
745 /// get_symbols to see if any of our definitions have been overridden by a
746 /// native object file. Then, perform optimization and codegen.
747 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
748   if (Modules.empty())
749     return LDPS_OK;
750
751   LLVMContext Context;
752   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
753   Linker L(Combined.get());
754
755   std::string DefaultTriple = sys::getDefaultTargetTriple();
756
757   StringSet<> Internalize;
758   StringSet<> Maybe;
759   for (claimed_file &F : Modules) {
760     std::unique_ptr<Module> M =
761         getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
762     if (!options::triple.empty())
763       M->setTargetTriple(options::triple.c_str());
764     else if (M->getTargetTriple().empty()) {
765       M->setTargetTriple(DefaultTriple);
766     }
767
768     std::string ErrMsg;
769     if (L.linkInModule(M.get(), &ErrMsg))
770       message(LDPL_FATAL, "Failed to link module: %s", ErrMsg.c_str());
771   }
772
773   for (const auto &Name : Internalize) {
774     GlobalValue *GV = Combined->getNamedValue(Name.first());
775     if (GV)
776       internalize(*GV);
777   }
778
779   for (const auto &Name : Maybe) {
780     GlobalValue *GV = Combined->getNamedValue(Name.first());
781     if (!GV)
782       continue;
783     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
784     if (canBeOmittedFromSymbolTable(GV))
785       internalize(*GV);
786   }
787
788   if (options::generate_bc_file != options::BC_NO) {
789     std::string path;
790     if (options::generate_bc_file == options::BC_ONLY)
791       path = output_name;
792     else if (!options::bc_path.empty())
793       path = options::bc_path;
794     else
795       path = output_name + ".bc";
796     {
797       std::error_code EC;
798       raw_fd_ostream OS(path, EC, sys::fs::OpenFlags::F_None);
799       if (EC)
800         message(LDPL_FATAL, "Failed to write the output file.");
801       WriteBitcodeToFile(L.getModule(), OS);
802     }
803     if (options::generate_bc_file == options::BC_ONLY)
804       return LDPS_OK;
805   }
806
807   codegen(*L.getModule());
808
809   if (!options::extra_library_path.empty() &&
810       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
811     message(LDPL_FATAL, "Unable to set the extra library path.");
812
813   return LDPS_OK;
814 }
815
816 static ld_plugin_status all_symbols_read_hook(void) {
817   ld_plugin_status Ret;
818   if (!options::generate_api_file) {
819     Ret = allSymbolsReadHook(nullptr);
820   } else {
821     std::error_code EC;
822     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
823     if (EC)
824       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
825               EC.message().c_str());
826     Ret = allSymbolsReadHook(&ApiFile);
827   }
828
829   if (options::generate_bc_file == options::BC_ONLY)
830     exit(0);
831
832   return Ret;
833 }
834
835 static ld_plugin_status cleanup_hook(void) {
836   for (std::string &Name : Cleanup) {
837     std::error_code EC = sys::fs::remove(Name);
838     if (EC)
839       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
840               EC.message().c_str());
841   }
842
843   return LDPS_OK;
844 }