Revert "Convert a few std::strings to StringRef."
[oota-llvm.git] / lib / LTO / LTOModule.cpp
1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
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 file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LTO/LTOModule.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Transforms/Utils/GlobalStatus.h"
43 #include <system_error>
44 using namespace llvm;
45
46 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
47                      llvm::TargetMachine *TM)
48     : IRFile(std::move(Obj)), _target(TM) {}
49
50 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
51 /// bitcode.
52 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
53   return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
54          sys::fs::file_magic::bitcode;
55 }
56
57 bool LTOModule::isBitcodeFile(const char *path) {
58   sys::fs::file_magic type;
59   if (sys::fs::identify_magic(path, type))
60     return false;
61   return type == sys::fs::file_magic::bitcode;
62 }
63
64 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
65                                    StringRef triplePrefix) {
66   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
67   return StringRef(Triple).startswith(triplePrefix);
68 }
69
70 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
71                                      std::string &errMsg) {
72   std::unique_ptr<MemoryBuffer> buffer;
73   if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
74     errMsg = ec.message();
75     return nullptr;
76   }
77   return makeLTOModule(std::move(buffer), options, errMsg);
78 }
79
80 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
81                                          TargetOptions options,
82                                          std::string &errMsg) {
83   return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
84 }
85
86 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
87                                               size_t map_size, off_t offset,
88                                               TargetOptions options,
89                                               std::string &errMsg) {
90   std::unique_ptr<MemoryBuffer> buffer;
91   if (std::error_code ec =
92           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
93     errMsg = ec.message();
94     return nullptr;
95   }
96   return makeLTOModule(std::move(buffer), options, errMsg);
97 }
98
99 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
100                                        TargetOptions options,
101                                        std::string &errMsg, StringRef path) {
102   std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
103   if (!buffer)
104     return nullptr;
105   return makeLTOModule(std::move(buffer), options, errMsg);
106 }
107
108 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
109                                     TargetOptions options,
110                                     std::string &errMsg) {
111   ErrorOr<Module *> MOrErr =
112       getLazyBitcodeModule(Buffer.get(), getGlobalContext());
113   if (std::error_code EC = MOrErr.getError()) {
114     errMsg = EC.message();
115     return nullptr;
116   }
117   std::unique_ptr<Module> M(MOrErr.get());
118
119   std::string TripleStr = M->getTargetTriple();
120   if (TripleStr.empty())
121     TripleStr = sys::getDefaultTargetTriple();
122   llvm::Triple Triple(TripleStr);
123
124   // find machine architecture for this module
125   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
126   if (!march)
127     return nullptr;
128
129   // construct LTOModule, hand over ownership of module and target
130   SubtargetFeatures Features;
131   Features.getDefaultSubtargetFeatures(Triple);
132   std::string FeatureStr = Features.getString();
133   // Set a default CPU for Darwin triples.
134   std::string CPU;
135   if (Triple.isOSDarwin()) {
136     if (Triple.getArch() == llvm::Triple::x86_64)
137       CPU = "core2";
138     else if (Triple.getArch() == llvm::Triple::x86)
139       CPU = "yonah";
140     else if (Triple.getArch() == llvm::Triple::arm64 ||
141              Triple.getArch() == llvm::Triple::aarch64)
142       CPU = "cyclone";
143   }
144
145   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
146                                                      options);
147   M->materializeAllPermanently(true);
148   M->setDataLayout(target->getDataLayout());
149
150   std::unique_ptr<object::IRObjectFile> IRObj(
151       new object::IRObjectFile(std::move(Buffer), std::move(M)));
152
153   LTOModule *Ret = new LTOModule(std::move(IRObj), target);
154
155   if (Ret->parseSymbols(errMsg)) {
156     delete Ret;
157     return nullptr;
158   }
159
160   Ret->parseMetadata();
161
162   return Ret;
163 }
164
165 /// Create a MemoryBuffer from a memory range with an optional name.
166 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
167                                     StringRef name) {
168   const char *startPtr = (const char*)mem;
169   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
170 }
171
172 /// objcClassNameFromExpression - Get string that the data pointer points to.
173 bool
174 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
175   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
176     Constant *op = ce->getOperand(0);
177     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
178       Constant *cn = gvn->getInitializer();
179       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
180         if (ca->isCString()) {
181           name = ".objc_class_name_" + ca->getAsCString().str();
182           return true;
183         }
184       }
185     }
186   }
187   return false;
188 }
189
190 /// addObjCClass - Parse i386/ppc ObjC class data structure.
191 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
192   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
193   if (!c) return;
194
195   // second slot in __OBJC,__class is pointer to superclass name
196   std::string superclassName;
197   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
198     NameAndAttributes info;
199     StringMap<NameAndAttributes>::value_type &entry =
200       _undefines.GetOrCreateValue(superclassName);
201     if (!entry.getValue().name) {
202       const char *symbolName = entry.getKey().data();
203       info.name = symbolName;
204       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
205       info.isFunction = false;
206       info.symbol = clgv;
207       entry.setValue(info);
208     }
209   }
210
211   // third slot in __OBJC,__class is pointer to class name
212   std::string className;
213   if (objcClassNameFromExpression(c->getOperand(2), className)) {
214     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
215     entry.setValue(1);
216
217     NameAndAttributes info;
218     info.name = entry.getKey().data();
219     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
220       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
221     info.isFunction = false;
222     info.symbol = clgv;
223     _symbols.push_back(info);
224   }
225 }
226
227 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
228 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
229   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
230   if (!c) return;
231
232   // second slot in __OBJC,__category is pointer to target class name
233   std::string targetclassName;
234   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
235     return;
236
237   NameAndAttributes info;
238   StringMap<NameAndAttributes>::value_type &entry =
239     _undefines.GetOrCreateValue(targetclassName);
240
241   if (entry.getValue().name)
242     return;
243
244   const char *symbolName = entry.getKey().data();
245   info.name = symbolName;
246   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
247   info.isFunction = false;
248   info.symbol = clgv;
249   entry.setValue(info);
250 }
251
252 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
253 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
254   std::string targetclassName;
255   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
256     return;
257
258   NameAndAttributes info;
259   StringMap<NameAndAttributes>::value_type &entry =
260     _undefines.GetOrCreateValue(targetclassName);
261   if (entry.getValue().name)
262     return;
263
264   const char *symbolName = entry.getKey().data();
265   info.name = symbolName;
266   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
267   info.isFunction = false;
268   info.symbol = clgv;
269   entry.setValue(info);
270 }
271
272 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
273   SmallString<64> Buffer;
274   {
275     raw_svector_ostream OS(Buffer);
276     Sym.printName(OS);
277   }
278
279   const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
280   addDefinedDataSymbol(Buffer.c_str(), V);
281 }
282
283 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
284   // Add to list of defined symbols.
285   addDefinedSymbol(Name, v, false);
286
287   if (!v->hasSection() /* || !isTargetDarwin */)
288     return;
289
290   // Special case i386/ppc ObjC data structures in magic sections:
291   // The issue is that the old ObjC object format did some strange
292   // contortions to avoid real linker symbols.  For instance, the
293   // ObjC class data structure is allocated statically in the executable
294   // that defines that class.  That data structures contains a pointer to
295   // its superclass.  But instead of just initializing that part of the
296   // struct to the address of its superclass, and letting the static and
297   // dynamic linkers do the rest, the runtime works by having that field
298   // instead point to a C-string that is the name of the superclass.
299   // At runtime the objc initialization updates that pointer and sets
300   // it to point to the actual super class.  As far as the linker
301   // knows it is just a pointer to a string.  But then someone wanted the
302   // linker to issue errors at build time if the superclass was not found.
303   // So they figured out a way in mach-o object format to use an absolute
304   // symbols (.objc_class_name_Foo = 0) and a floating reference
305   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
306   // a class was missing.
307   // The following synthesizes the implicit .objc_* symbols for the linker
308   // from the ObjC data structures generated by the front end.
309
310   // special case if this data blob is an ObjC class definition
311   std::string Section = v->getSection();
312   if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
313     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
314       addObjCClass(gv);
315     }
316   }
317
318   // special case if this data blob is an ObjC category definition
319   else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
320     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321       addObjCCategory(gv);
322     }
323   }
324
325   // special case if this data blob is the list of referenced classes
326   else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
327     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328       addObjCClassRef(gv);
329     }
330   }
331 }
332
333 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
334   SmallString<64> Buffer;
335   {
336     raw_svector_ostream OS(Buffer);
337     Sym.printName(OS);
338   }
339
340   const Function *F =
341       cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
342   addDefinedFunctionSymbol(Buffer.c_str(), F);
343 }
344
345 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
346   // add to list of defined symbols
347   addDefinedSymbol(Name, F, true);
348 }
349
350 static bool canBeHidden(const GlobalValue *GV) {
351   // FIXME: this is duplicated with another static function in AsmPrinter.cpp
352   GlobalValue::LinkageTypes L = GV->getLinkage();
353
354   if (L != GlobalValue::LinkOnceODRLinkage)
355     return false;
356
357   if (GV->hasUnnamedAddr())
358     return true;
359
360   // If it is a non constant variable, it needs to be uniqued across shared
361   // objects.
362   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
363     if (!Var->isConstant())
364       return false;
365   }
366
367   GlobalStatus GS;
368   if (GlobalStatus::analyzeGlobal(GV, GS))
369     return false;
370
371   return !GS.IsCompared;
372 }
373
374 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
375                                  bool isFunction) {
376   // set alignment part log2() can have rounding errors
377   uint32_t align = def->getAlignment();
378   uint32_t attr = align ? countTrailingZeros(align) : 0;
379
380   // set permissions part
381   if (isFunction) {
382     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
383   } else {
384     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
385     if (gv && gv->isConstant())
386       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
387     else
388       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
389   }
390
391   // set definition part
392   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
393     attr |= LTO_SYMBOL_DEFINITION_WEAK;
394   else if (def->hasCommonLinkage())
395     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
396   else
397     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
398
399   // set scope part
400   if (def->hasLocalLinkage())
401     // Ignore visibility if linkage is local.
402     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
403   else if (def->hasHiddenVisibility())
404     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
405   else if (def->hasProtectedVisibility())
406     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
407   else if (canBeHidden(def))
408     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
409   else
410     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
411
412   StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
413   entry.setValue(1);
414
415   // fill information structure
416   NameAndAttributes info;
417   StringRef NameRef = entry.getKey();
418   info.name = NameRef.data();
419   assert(info.name[NameRef.size()] == '\0');
420   info.attributes = attr;
421   info.isFunction = isFunction;
422   info.symbol = def;
423
424   // add to table of symbols
425   _symbols.push_back(info);
426 }
427
428 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
429 /// defined list.
430 void LTOModule::addAsmGlobalSymbol(const char *name,
431                                    lto_symbol_attributes scope) {
432   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
433
434   // only add new define if not already defined
435   if (entry.getValue())
436     return;
437
438   entry.setValue(1);
439
440   NameAndAttributes &info = _undefines[entry.getKey().data()];
441
442   if (info.symbol == nullptr) {
443     // FIXME: This is trying to take care of module ASM like this:
444     //
445     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
446     //
447     // but is gross and its mother dresses it funny. Have the ASM parser give us
448     // more details for this type of situation so that we're not guessing so
449     // much.
450
451     // fill information structure
452     info.name = entry.getKey().data();
453     info.attributes =
454       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
455     info.isFunction = false;
456     info.symbol = nullptr;
457
458     // add to table of symbols
459     _symbols.push_back(info);
460     return;
461   }
462
463   if (info.isFunction)
464     addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
465   else
466     addDefinedDataSymbol(info.name, info.symbol);
467
468   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
469   _symbols.back().attributes |= scope;
470 }
471
472 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
473 /// undefined list.
474 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
475   StringMap<NameAndAttributes>::value_type &entry =
476     _undefines.GetOrCreateValue(name);
477
478   _asm_undefines.push_back(entry.getKey().data());
479
480   // we already have the symbol
481   if (entry.getValue().name)
482     return;
483
484   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
485   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
486   NameAndAttributes info;
487   info.name = entry.getKey().data();
488   info.attributes = attr;
489   info.isFunction = false;
490   info.symbol = nullptr;
491
492   entry.setValue(info);
493 }
494
495 /// Add a symbol which isn't defined just yet to a list to be resolved later.
496 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
497                                             bool isFunc) {
498   SmallString<64> name;
499   {
500     raw_svector_ostream OS(name);
501     Sym.printName(OS);
502   }
503
504   StringMap<NameAndAttributes>::value_type &entry =
505     _undefines.GetOrCreateValue(name);
506
507   // we already have the symbol
508   if (entry.getValue().name)
509     return;
510
511   NameAndAttributes info;
512
513   info.name = entry.getKey().data();
514
515   const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
516
517   if (decl->hasExternalWeakLinkage())
518     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
519   else
520     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
521
522   info.isFunction = isFunc;
523   info.symbol = decl;
524
525   entry.setValue(info);
526 }
527
528 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
529 /// them to either the defined or undefined lists.
530 bool LTOModule::parseSymbols(std::string &errMsg) {
531   for (auto &Sym : IRFile->symbols()) {
532     const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
533     uint32_t Flags = Sym.getFlags();
534     if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
535       continue;
536
537     bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
538
539     if (!GV) {
540       SmallString<64> Buffer;
541       {
542         raw_svector_ostream OS(Buffer);
543         Sym.printName(OS);
544       }
545       const char *Name = Buffer.c_str();
546
547       if (IsUndefined)
548         addAsmGlobalSymbolUndef(Name);
549       else if (Flags & object::BasicSymbolRef::SF_Global)
550         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
551       else
552         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
553       continue;
554     }
555
556     auto *F = dyn_cast<Function>(GV);
557     if (IsUndefined) {
558       addPotentialUndefinedSymbol(Sym, F != nullptr);
559       continue;
560     }
561
562     if (F) {
563       addDefinedFunctionSymbol(Sym);
564       continue;
565     }
566
567     if (isa<GlobalVariable>(GV)) {
568       addDefinedDataSymbol(Sym);
569       continue;
570     }
571
572     assert(isa<GlobalAlias>(GV));
573     addDefinedDataSymbol(Sym);
574   }
575
576   // make symbols for all undefines
577   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
578          e = _undefines.end(); u != e; ++u) {
579     // If this symbol also has a definition, then don't make an undefine because
580     // it is a tentative definition.
581     if (_defines.count(u->getKey())) continue;
582     NameAndAttributes info = u->getValue();
583     _symbols.push_back(info);
584   }
585
586   return false;
587 }
588
589 /// parseMetadata - Parse metadata from the module
590 void LTOModule::parseMetadata() {
591   // Linker Options
592   if (Value *Val = getModule().getModuleFlag("Linker Options")) {
593     MDNode *LinkerOptions = cast<MDNode>(Val);
594     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
595       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
596       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
597         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
598         StringRef Op = _linkeropt_strings.
599             GetOrCreateValue(MDOption->getString()).getKey();
600         StringRef DepLibName = _target->getTargetLowering()->
601             getObjFileLowering().getDepLibFromLinkerOpt(Op);
602         if (!DepLibName.empty())
603           _deplibs.push_back(DepLibName.data());
604         else if (!Op.empty())
605           _linkeropts.push_back(Op.data());
606       }
607     }
608   }
609
610   // Add other interesting metadata here.
611 }