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