[PM] Move TargetLibraryInfo into the Analysis library.
[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/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/CommandFlags.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/Linker/Linker.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Object/IRObjectFile.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.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"
43 #include <list>
44 #include <plugin-api.h>
45 #include <system_error>
46 #include <vector>
47
48 #ifndef LDPO_PIE
49 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
50 // Precise and Debian Wheezy (binutils 2.23 is required)
51 # define LDPO_PIE 3
52 #endif
53
54 using namespace llvm;
55
56 namespace {
57 struct claimed_file {
58   void *handle;
59   std::vector<ld_plugin_symbol> syms;
60 };
61 }
62
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.
66   abort();
67 }
68
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;
82
83 namespace options {
84   enum OutputType {
85     OT_NORMAL,
86     OT_DISABLE,
87     OT_BC_ONLY,
88     OT_SAVE_TEMPS
89   };
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;
102
103   static void process_plugin_option(const char* opt_)
104   {
105     if (opt_ == nullptr)
106       return;
107     llvm::StringRef opt = opt_;
108
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;
125     } else {
126       // Save this option to pass to the code generator.
127       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
128       // add that.
129       if (extra.empty())
130         extra.push_back("LLVMgold");
131
132       extra.push_back(opt_);
133     }
134   }
135 }
136
137 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
138                                         int *claimed);
139 static ld_plugin_status all_symbols_read_hook(void);
140 static ld_plugin_status cleanup_hook(void);
141
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();
149
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
154   // for services.
155
156   bool registeredClaimFile = false;
157   bool RegisteredAllSymbolsRead = false;
158
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;
163         break;
164       case LDPT_LINKER_OUTPUT:
165         switch (tv->tv_u.tv_val) {
166           case LDPO_REL:  // .o
167           case LDPO_DYN:  // .so
168           case LDPO_PIE:  // position independent executable
169             RelocationModel = Reloc::PIC_;
170             break;
171           case LDPO_EXEC:  // .exe
172             RelocationModel = Reloc::Static;
173             break;
174           default:
175             message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
176             return LDPS_ERR;
177         }
178         break;
179       case LDPT_OPTION:
180         options::process_plugin_option(tv->tv_u.tv_string);
181         break;
182       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
183         ld_plugin_register_claim_file callback;
184         callback = tv->tv_u.tv_register_claim_file;
185
186         if (callback(claim_file_hook) != LDPS_OK)
187           return LDPS_ERR;
188
189         registeredClaimFile = true;
190       } break;
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;
194
195         if (callback(all_symbols_read_hook) != LDPS_OK)
196           return LDPS_ERR;
197
198         RegisteredAllSymbolsRead = true;
199       } break;
200       case LDPT_REGISTER_CLEANUP_HOOK: {
201         ld_plugin_register_cleanup callback;
202         callback = tv->tv_u.tv_register_cleanup;
203
204         if (callback(cleanup_hook) != LDPS_OK)
205           return LDPS_ERR;
206       } break;
207       case LDPT_GET_INPUT_FILE:
208         get_input_file = tv->tv_u.tv_get_input_file;
209         break;
210       case LDPT_RELEASE_INPUT_FILE:
211         release_input_file = tv->tv_u.tv_release_input_file;
212         break;
213       case LDPT_ADD_SYMBOLS:
214         add_symbols = tv->tv_u.tv_add_symbols;
215         break;
216       case LDPT_GET_SYMBOLS_V2:
217         get_symbols = tv->tv_u.tv_get_symbols;
218         break;
219       case LDPT_ADD_INPUT_FILE:
220         add_input_file = tv->tv_u.tv_add_input_file;
221         break;
222       case LDPT_SET_EXTRA_LIBRARY_PATH:
223         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
224         break;
225       case LDPT_GET_VIEW:
226         get_view = tv->tv_u.tv_get_view;
227         break;
228       case LDPT_MESSAGE:
229         message = tv->tv_u.tv_message;
230         break;
231       default:
232         break;
233     }
234   }
235
236   if (!registeredClaimFile) {
237     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
238     return LDPS_ERR;
239   }
240   if (!add_symbols) {
241     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
242     return LDPS_ERR;
243   }
244
245   if (!RegisteredAllSymbolsRead)
246     return LDPS_OK;
247
248   if (!get_input_file) {
249     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
250     return LDPS_ERR;
251   }
252   if (!release_input_file) {
253     message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
254     return LDPS_ERR;
255   }
256
257   return LDPS_OK;
258 }
259
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);
264 }
265
266 static bool shouldSkip(uint32_t Symflags) {
267   if (!(Symflags & object::BasicSymbolRef::SF_Global))
268     return true;
269   if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
270     return true;
271   return false;
272 }
273
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)
279     return;
280
281   std::string ErrStorage;
282   {
283     raw_string_ostream OS(ErrStorage);
284     DiagnosticPrinterRawOStream DP(OS);
285     DI.print(DP);
286   }
287   message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
288           ErrStorage.c_str());
289 }
290
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
293 /// possible.
294 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
295                                         int *claimed) {
296   LLVMContext Context;
297   MemoryBufferRef BufferRef;
298   std::unique_ptr<MemoryBuffer> Buffer;
299   if (get_view) {
300     const void *view;
301     if (get_view(file->handle, &view) != LDPS_OK) {
302       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
303       return LDPS_ERR;
304     }
305     BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
306   } else {
307     int64_t offset = 0;
308     // Gold has found what might be IR part-way inside of a file, such as
309     // an .a archive.
310     if (file->offset) {
311       offset = file->offset;
312     }
313     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
314         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
315                                        offset);
316     if (std::error_code EC = BufferOrErr.getError()) {
317       message(LDPL_ERROR, EC.message().c_str());
318       return LDPS_ERR;
319     }
320     Buffer = std::move(BufferOrErr.get());
321     BufferRef = Buffer->getMemBufferRef();
322   }
323
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)
330     return LDPS_OK;
331
332   *claimed = 1;
333
334   if (EC) {
335     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
336             EC.message().c_str());
337     return LDPS_ERR;
338   }
339   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
340
341   Modules.resize(Modules.size() + 1);
342   claimed_file &cf = Modules.back();
343
344   cf.handle = file->handle;
345
346   for (auto &Sym : Obj->symbols()) {
347     uint32_t Symflags = Sym.getFlags();
348     if (shouldSkip(Symflags))
349       continue;
350
351     cf.syms.push_back(ld_plugin_symbol());
352     ld_plugin_symbol &sym = cf.syms.back();
353     sym.version = nullptr;
354
355     SmallString<64> Name;
356     {
357       raw_svector_ostream OS(Name);
358       Sym.printName(OS);
359     }
360     sym.name = strdup(Name.c_str());
361
362     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
363
364     sym.visibility = LDPV_DEFAULT;
365     if (GV) {
366       switch (GV->getVisibility()) {
367       case GlobalValue::DefaultVisibility:
368         sym.visibility = LDPV_DEFAULT;
369         break;
370       case GlobalValue::HiddenVisibility:
371         sym.visibility = LDPV_HIDDEN;
372         break;
373       case GlobalValue::ProtectedVisibility:
374         sym.visibility = LDPV_PROTECTED;
375         break;
376       }
377     }
378
379     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
380       sym.def = LDPK_UNDEF;
381       if (GV && GV->hasExternalWeakLinkage())
382         sym.def = LDPK_WEAKUNDEF;
383     } else {
384       sym.def = LDPK_DEF;
385       if (GV) {
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;
392       }
393     }
394
395     sym.size = 0;
396     sym.comdat_key = nullptr;
397     if (GV) {
398       const GlobalObject *Base = getBaseObject(*GV);
399       if (!Base)
400         message(LDPL_FATAL, "Unable to determine comdat of alias!");
401       const Comdat *C = Base->getComdat();
402       if (C)
403         sym.comdat_key = strdup(C->getName().str().c_str());
404       else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
405         sym.comdat_key = strdup(sym.name);
406     }
407
408     sym.resolution = LDPR_UNKNOWN;
409   }
410
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!");
414       return LDPS_ERR;
415     }
416   }
417
418   return LDPS_OK;
419 }
420
421 static void keepGlobalValue(GlobalValue &GV,
422                             std::vector<GlobalAlias *> &KeptAliases) {
423   assert(!GV.hasLocalLinkage());
424
425   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
426     KeptAliases.push_back(GA);
427
428   switch (GV.getLinkage()) {
429   default:
430     break;
431   case GlobalValue::LinkOnceAnyLinkage:
432     GV.setLinkage(GlobalValue::WeakAnyLinkage);
433     break;
434   case GlobalValue::LinkOnceODRLinkage:
435     GV.setLinkage(GlobalValue::WeakODRLinkage);
436     break;
437   }
438
439   assert(!GV.isDiscardableIfUnused());
440 }
441
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);
447 }
448
449 static void drop(GlobalValue &GV) {
450   if (auto *F = dyn_cast<Function>(&GV)) {
451     F->deleteBody();
452     F->setComdat(nullptr); // Should deleteBody do this?
453     return;
454   }
455
456   if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
457     Var->setInitializer(nullptr);
458     Var->setLinkage(
459         GlobalValue::ExternalLinkage); // Should setInitializer do this?
460     Var->setComdat(nullptr); // and this?
461     return;
462   }
463
464   auto &Alias = cast<GlobalAlias>(GV);
465   Module &M = *Alias.getParent();
466   PointerType &Ty = *cast<PointerType>(Alias.getType());
467   GlobalValue::LinkageTypes L = Alias.getLinkage();
468   auto *Var =
469       new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
470                          /*Initializer*/ nullptr);
471   Var->takeName(&Alias);
472   Alias.replaceAllUsesWith(Var);
473   Alias.eraseFromParent();
474 }
475
476 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
477   switch (R) {
478   case LDPR_UNKNOWN:
479     return "UNKNOWN";
480   case LDPR_UNDEF:
481     return "UNDEF";
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";
498   }
499   llvm_unreachable("Unknown resolution");
500 }
501
502 namespace {
503 class LocalValueMaterializer : public ValueMaterializer {
504   DenseSet<GlobalValue *> &Dropped;
505   DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
506
507 public:
508   LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
509   Value *materializeValueFor(Value *V) override;
510 };
511 }
512
513 Value *LocalValueMaterializer::materializeValueFor(Value *V) {
514   auto *GO = dyn_cast<GlobalObject>(V);
515   if (!GO)
516     return nullptr;
517
518   auto I = LocalVersions.find(GO);
519   if (I != LocalVersions.end())
520     return I->second;
521
522   if (!Dropped.count(GO))
523     return nullptr;
524
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);
530   } else {
531     auto *Var = cast<GlobalVariable>(GO);
532     Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
533                                      Var->isConstant(), L,
534                                      /*Initializer*/ nullptr);
535   }
536   Declaration->takeName(GO);
537   Declaration->copyAttributesFrom(GO);
538
539   GO->setLinkage(GlobalValue::InternalLinkage);
540   GO->setName(Declaration->getName());
541   Dropped.erase(GO);
542   GO->replaceAllUsesWith(Declaration);
543
544   LocalVersions[Declaration] = GO;
545
546   return GO;
547 }
548
549 static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
550                                         LocalValueMaterializer *Materializer) {
551   return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
552 }
553
554 static void freeSymName(ld_plugin_symbol &Sym) {
555   free(Sym.name);
556   free(Sym.comdat_key);
557   Sym.name = nullptr;
558   Sym.comdat_key = nullptr;
559 }
560
561 static std::unique_ptr<Module>
562 getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
563                  StringSet<> &Internalize, StringSet<> &Maybe) {
564   ld_plugin_input_file File;
565   if (get_input_file(F.handle, &File) != LDPS_OK)
566     message(LDPL_FATAL, "Failed to get file information");
567
568   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
569     message(LDPL_FATAL, "Failed to get symbol information");
570
571   const void *View;
572   if (get_view(F.handle, &View) != LDPS_OK)
573     message(LDPL_FATAL, "Failed to get a view of file");
574
575   MemoryBufferRef BufferRef(StringRef((const char *)View, File.filesize), "");
576   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
577       object::IRObjectFile::create(BufferRef, Context);
578
579   if (std::error_code EC = ObjOrErr.getError())
580     message(LDPL_FATAL, "Could not read bitcode from file : %s",
581             EC.message().c_str());
582
583   if (release_input_file(F.handle) != LDPS_OK)
584     message(LDPL_FATAL, "Failed to release file information");
585
586   object::IRObjectFile &Obj = **ObjOrErr;
587
588   Module &M = Obj.getModule();
589
590   SmallPtrSet<GlobalValue *, 8> Used;
591   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
592
593   DenseSet<GlobalValue *> Drop;
594   std::vector<GlobalAlias *> KeptAliases;
595
596   unsigned SymNum = 0;
597   for (auto &ObjSym : Obj.symbols()) {
598     if (shouldSkip(ObjSym.getFlags()))
599       continue;
600     ld_plugin_symbol &Sym = F.syms[SymNum];
601     ++SymNum;
602
603     ld_plugin_symbol_resolution Resolution =
604         (ld_plugin_symbol_resolution)Sym.resolution;
605
606     if (options::generate_api_file)
607       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
608
609     GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
610     if (!GV) {
611       freeSymName(Sym);
612       continue; // Asm symbol.
613     }
614
615     if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
616       // Common linkage is special. There is no single symbol that wins the
617       // resolution. Instead we have to collect the maximum alignment and size.
618       // The IR linker does that for us if we just pass it every common GV.
619       // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
620       // internalize once the IR linker has done its job.
621       freeSymName(Sym);
622       continue;
623     }
624
625     switch (Resolution) {
626     case LDPR_UNKNOWN:
627       llvm_unreachable("Unexpected resolution");
628
629     case LDPR_RESOLVED_IR:
630     case LDPR_RESOLVED_EXEC:
631     case LDPR_RESOLVED_DYN:
632       assert(GV->isDeclarationForLinker());
633       break;
634
635     case LDPR_UNDEF:
636       if (!GV->isDeclarationForLinker()) {
637         assert(GV->hasComdat());
638         Drop.insert(GV);
639       }
640       break;
641
642     case LDPR_PREVAILING_DEF_IRONLY: {
643       keepGlobalValue(*GV, KeptAliases);
644       if (!Used.count(GV)) {
645         // Since we use the regular lib/Linker, we cannot just internalize GV
646         // now or it will not be copied to the merged module. Instead we force
647         // it to be copied and then internalize it.
648         Internalize.insert(GV->getName());
649       }
650       break;
651     }
652
653     case LDPR_PREVAILING_DEF:
654       keepGlobalValue(*GV, KeptAliases);
655       break;
656
657     case LDPR_PREEMPTED_IR:
658       // Gold might have selected a linkonce_odr and preempted a weak_odr.
659       // In that case we have to make sure we don't end up internalizing it.
660       if (!GV->isDiscardableIfUnused())
661         Maybe.erase(GV->getName());
662
663       // fall-through
664     case LDPR_PREEMPTED_REG:
665       Drop.insert(GV);
666       break;
667
668     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
669       // We can only check for address uses after we merge the modules. The
670       // reason is that this GV might have a copy in another module
671       // and in that module the address might be significant, but that
672       // copy will be LDPR_PREEMPTED_IR.
673       if (GV->hasLinkOnceODRLinkage())
674         Maybe.insert(GV->getName());
675       keepGlobalValue(*GV, KeptAliases);
676       break;
677     }
678     }
679
680     freeSymName(Sym);
681   }
682
683   ValueToValueMapTy VM;
684   LocalValueMaterializer Materializer(Drop);
685   for (GlobalAlias *GA : KeptAliases) {
686     // Gold told us to keep GA. It is possible that a GV usied in the aliasee
687     // expression is being dropped. If that is the case, that GV must be copied.
688     Constant *Aliasee = GA->getAliasee();
689     Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
690     GA->setAliasee(Replacement);
691   }
692
693   for (auto *GV : Drop)
694     drop(*GV);
695
696   return Obj.takeModule();
697 }
698
699 static void runLTOPasses(Module &M, TargetMachine &TM) {
700   PassManager passes;
701   PassManagerBuilder PMB;
702   PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
703   PMB.Inliner = createFunctionInliningPass();
704   PMB.VerifyInput = true;
705   PMB.VerifyOutput = true;
706   PMB.LoopVectorize = true;
707   PMB.SLPVectorize = true;
708   PMB.populateLTOPassManager(passes, &TM);
709   passes.run(M);
710 }
711
712 static void saveBCFile(StringRef Path, Module &M) {
713   std::error_code EC;
714   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
715   if (EC)
716     message(LDPL_FATAL, "Failed to write the output file.");
717   WriteBitcodeToFile(&M, OS);
718 }
719
720 static void codegen(Module &M) {
721   const std::string &TripleStr = M.getTargetTriple();
722   Triple TheTriple(TripleStr);
723
724   std::string ErrMsg;
725   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
726   if (!TheTarget)
727     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
728
729   if (unsigned NumOpts = options::extra.size())
730     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
731
732   SubtargetFeatures Features;
733   Features.getDefaultSubtargetFeatures(TheTriple);
734   for (const std::string &A : MAttrs)
735     Features.AddFeature(A);
736
737   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
738   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
739       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
740       CodeModel::Default, CodeGenOpt::Aggressive));
741
742   runLTOPasses(M, *TM);
743
744   if (options::TheOutputType == options::OT_SAVE_TEMPS)
745     saveBCFile(output_name + ".opt.bc", M);
746
747   PassManager CodeGenPasses;
748   CodeGenPasses.add(new DataLayoutPass());
749
750   SmallString<128> Filename;
751   int FD;
752   if (options::obj_path.empty()) {
753     std::error_code EC =
754         sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
755     if (EC)
756       message(LDPL_FATAL, "Could not create temporary file: %s",
757               EC.message().c_str());
758   } else {
759     Filename = options::obj_path;
760     std::error_code EC =
761         sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
762     if (EC)
763       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
764   }
765
766   {
767     raw_fd_ostream OS(FD, true);
768     formatted_raw_ostream FOS(OS);
769
770     if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
771                                 TargetMachine::CGFT_ObjectFile))
772       message(LDPL_FATAL, "Failed to setup codegen");
773     CodeGenPasses.run(M);
774   }
775
776   if (add_input_file(Filename.c_str()) != LDPS_OK)
777     message(LDPL_FATAL,
778             "Unable to add .o file to the link. File left behind in: %s",
779             Filename.c_str());
780
781   if (options::obj_path.empty())
782     Cleanup.push_back(Filename.c_str());
783 }
784
785 /// gold informs us that all symbols have been read. At this point, we use
786 /// get_symbols to see if any of our definitions have been overridden by a
787 /// native object file. Then, perform optimization and codegen.
788 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
789   if (Modules.empty())
790     return LDPS_OK;
791
792   LLVMContext Context;
793   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
794   Linker L(Combined.get());
795
796   std::string DefaultTriple = sys::getDefaultTargetTriple();
797
798   StringSet<> Internalize;
799   StringSet<> Maybe;
800   for (claimed_file &F : Modules) {
801     std::unique_ptr<Module> M =
802         getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
803     if (!options::triple.empty())
804       M->setTargetTriple(options::triple.c_str());
805     else if (M->getTargetTriple().empty()) {
806       M->setTargetTriple(DefaultTriple);
807     }
808
809     if (L.linkInModule(M.get()))
810       message(LDPL_FATAL, "Failed to link module");
811   }
812
813   for (const auto &Name : Internalize) {
814     GlobalValue *GV = Combined->getNamedValue(Name.first());
815     if (GV)
816       internalize(*GV);
817   }
818
819   for (const auto &Name : Maybe) {
820     GlobalValue *GV = Combined->getNamedValue(Name.first());
821     if (!GV)
822       continue;
823     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
824     if (canBeOmittedFromSymbolTable(GV))
825       internalize(*GV);
826   }
827
828   if (options::TheOutputType == options::OT_DISABLE)
829     return LDPS_OK;
830
831   if (options::TheOutputType != options::OT_NORMAL) {
832     std::string path;
833     if (options::TheOutputType == options::OT_BC_ONLY)
834       path = output_name;
835     else
836       path = output_name + ".bc";
837     saveBCFile(path, *L.getModule());
838     if (options::TheOutputType == options::OT_BC_ONLY)
839       return LDPS_OK;
840   }
841
842   codegen(*L.getModule());
843
844   if (!options::extra_library_path.empty() &&
845       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
846     message(LDPL_FATAL, "Unable to set the extra library path.");
847
848   return LDPS_OK;
849 }
850
851 static ld_plugin_status all_symbols_read_hook(void) {
852   ld_plugin_status Ret;
853   if (!options::generate_api_file) {
854     Ret = allSymbolsReadHook(nullptr);
855   } else {
856     std::error_code EC;
857     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
858     if (EC)
859       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
860               EC.message().c_str());
861     Ret = allSymbolsReadHook(&ApiFile);
862   }
863
864   llvm_shutdown();
865
866   if (options::TheOutputType == options::OT_BC_ONLY ||
867       options::TheOutputType == options::OT_DISABLE)
868     exit(0);
869
870   return Ret;
871 }
872
873 static ld_plugin_status cleanup_hook(void) {
874   for (std::string &Name : Cleanup) {
875     std::error_code EC = sys::fs::remove(Name);
876     if (EC)
877       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
878               EC.message().c_str());
879   }
880
881   return LDPS_OK;
882 }