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