1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/LTOModule.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/Object/IRObjectFile.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
46 #include "llvm/Transforms/Utils/GlobalStatus.h"
47 #include <system_error>
49 using namespace llvm::object;
51 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
52 llvm::TargetMachine *TM)
53 : IRFile(std::move(Obj)), _target(TM) {}
55 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
56 llvm::TargetMachine *TM,
57 std::unique_ptr<LLVMContext> Context)
58 : OwnedContext(std::move(Context)), IRFile(std::move(Obj)), _target(TM) {}
60 LTOModule::~LTOModule() {}
62 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
64 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
65 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
66 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
70 bool LTOModule::isBitcodeFile(const char *Path) {
71 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
72 MemoryBuffer::getFile(Path);
76 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
77 BufferOrErr.get()->getMemBufferRef());
81 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
82 StringRef TriplePrefix) {
83 ErrorOr<MemoryBufferRef> BCOrErr =
84 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
88 std::string Triple = getBitcodeTargetTriple(*BCOrErr, Context);
89 return StringRef(Triple).startswith(TriplePrefix);
92 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
93 std::string &errMsg) {
94 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
95 MemoryBuffer::getFile(path);
96 if (std::error_code EC = BufferOrErr.getError()) {
97 errMsg = EC.message();
100 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
101 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
102 &getGlobalContext());
105 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
106 TargetOptions options,
107 std::string &errMsg) {
108 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
111 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
112 size_t map_size, off_t offset,
113 TargetOptions options,
114 std::string &errMsg) {
115 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
116 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
117 if (std::error_code EC = BufferOrErr.getError()) {
118 errMsg = EC.message();
121 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
122 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
123 &getGlobalContext());
126 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
127 TargetOptions options,
128 std::string &errMsg, StringRef path) {
129 return createInContext(mem, length, options, errMsg, path,
130 &getGlobalContext());
133 LTOModule *LTOModule::createInLocalContext(const void *mem, size_t length,
134 TargetOptions options,
137 return createInContext(mem, length, options, errMsg, path, nullptr);
140 LTOModule *LTOModule::createInContext(const void *mem, size_t length,
141 TargetOptions options,
142 std::string &errMsg, StringRef path,
143 LLVMContext *Context) {
144 StringRef Data((const char *)mem, length);
145 MemoryBufferRef Buffer(Data, path);
146 return makeLTOModule(Buffer, options, errMsg, Context);
149 static ErrorOr<Module *> parseBitcodeFileImpl(MemoryBufferRef Buffer,
150 LLVMContext &Context,
153 ErrorOr<MemoryBufferRef> MBOrErr =
154 IRObjectFile::findBitcodeInMemBuffer(Buffer);
155 if (std::error_code EC = MBOrErr.getError())
159 // Parse the full file.
160 return parseBitcodeFile(*MBOrErr, Context);
163 std::unique_ptr<MemoryBuffer> LightweightBuf =
164 MemoryBuffer::getMemBuffer(*MBOrErr, false);
165 return getLazyBitcodeModule(std::move(LightweightBuf), Context);
168 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
169 TargetOptions options, std::string &errMsg,
170 LLVMContext *Context) {
171 std::unique_ptr<LLVMContext> OwnedContext;
173 OwnedContext = llvm::make_unique<LLVMContext>();
174 Context = OwnedContext.get();
177 // If we own a context, we know this is being used only for symbol
178 // extraction, not linking. Be lazy in that case.
179 ErrorOr<Module *> MOrErr = parseBitcodeFileImpl(
180 Buffer, *Context, /* ShouldBeLazy */ static_cast<bool>(OwnedContext));
181 if (std::error_code EC = MOrErr.getError()) {
182 errMsg = EC.message();
185 std::unique_ptr<Module> M(MOrErr.get());
187 std::string TripleStr = M->getTargetTriple();
188 if (TripleStr.empty())
189 TripleStr = sys::getDefaultTargetTriple();
190 llvm::Triple Triple(TripleStr);
192 // find machine architecture for this module
193 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
197 // construct LTOModule, hand over ownership of module and target
198 SubtargetFeatures Features;
199 Features.getDefaultSubtargetFeatures(Triple);
200 std::string FeatureStr = Features.getString();
201 // Set a default CPU for Darwin triples.
203 if (Triple.isOSDarwin()) {
204 if (Triple.getArch() == llvm::Triple::x86_64)
206 else if (Triple.getArch() == llvm::Triple::x86)
208 else if (Triple.getArch() == llvm::Triple::aarch64)
212 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
214 M->setDataLayout(target->getSubtargetImpl()->getDataLayout());
216 std::unique_ptr<object::IRObjectFile> IRObj(
217 new object::IRObjectFile(Buffer, std::move(M)));
221 Ret = new LTOModule(std::move(IRObj), target, std::move(OwnedContext));
223 Ret = new LTOModule(std::move(IRObj), target);
225 if (Ret->parseSymbols(errMsg)) {
230 Ret->parseMetadata();
235 /// Create a MemoryBuffer from a memory range with an optional name.
236 std::unique_ptr<MemoryBuffer>
237 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
238 const char *startPtr = (const char*)mem;
239 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
242 /// objcClassNameFromExpression - Get string that the data pointer points to.
244 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
245 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
246 Constant *op = ce->getOperand(0);
247 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
248 Constant *cn = gvn->getInitializer();
249 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
250 if (ca->isCString()) {
251 name = ".objc_class_name_" + ca->getAsCString().str();
260 /// addObjCClass - Parse i386/ppc ObjC class data structure.
261 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
262 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
265 // second slot in __OBJC,__class is pointer to superclass name
266 std::string superclassName;
267 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
269 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
270 if (IterBool.second) {
271 NameAndAttributes &info = IterBool.first->second;
272 info.name = IterBool.first->first().data();
273 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
274 info.isFunction = false;
279 // third slot in __OBJC,__class is pointer to class name
280 std::string className;
281 if (objcClassNameFromExpression(c->getOperand(2), className)) {
282 auto Iter = _defines.insert(className).first;
284 NameAndAttributes info;
285 info.name = Iter->first().data();
286 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
287 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
288 info.isFunction = false;
290 _symbols.push_back(info);
294 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
295 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
296 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
299 // second slot in __OBJC,__category is pointer to target class name
300 std::string targetclassName;
301 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
305 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
307 if (!IterBool.second)
310 NameAndAttributes &info = IterBool.first->second;
311 info.name = IterBool.first->first().data();
312 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
313 info.isFunction = false;
317 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
318 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
319 std::string targetclassName;
320 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
324 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
326 if (!IterBool.second)
329 NameAndAttributes &info = IterBool.first->second;
330 info.name = IterBool.first->first().data();
331 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
332 info.isFunction = false;
336 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
337 SmallString<64> Buffer;
339 raw_svector_ostream OS(Buffer);
343 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
344 addDefinedDataSymbol(Buffer.c_str(), V);
347 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
348 // Add to list of defined symbols.
349 addDefinedSymbol(Name, v, false);
351 if (!v->hasSection() /* || !isTargetDarwin */)
354 // Special case i386/ppc ObjC data structures in magic sections:
355 // The issue is that the old ObjC object format did some strange
356 // contortions to avoid real linker symbols. For instance, the
357 // ObjC class data structure is allocated statically in the executable
358 // that defines that class. That data structures contains a pointer to
359 // its superclass. But instead of just initializing that part of the
360 // struct to the address of its superclass, and letting the static and
361 // dynamic linkers do the rest, the runtime works by having that field
362 // instead point to a C-string that is the name of the superclass.
363 // At runtime the objc initialization updates that pointer and sets
364 // it to point to the actual super class. As far as the linker
365 // knows it is just a pointer to a string. But then someone wanted the
366 // linker to issue errors at build time if the superclass was not found.
367 // So they figured out a way in mach-o object format to use an absolute
368 // symbols (.objc_class_name_Foo = 0) and a floating reference
369 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
370 // a class was missing.
371 // The following synthesizes the implicit .objc_* symbols for the linker
372 // from the ObjC data structures generated by the front end.
374 // special case if this data blob is an ObjC class definition
375 std::string Section = v->getSection();
376 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
377 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
382 // special case if this data blob is an ObjC category definition
383 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
384 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
389 // special case if this data blob is the list of referenced classes
390 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
391 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
397 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
398 SmallString<64> Buffer;
400 raw_svector_ostream OS(Buffer);
405 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
406 addDefinedFunctionSymbol(Buffer.c_str(), F);
409 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
410 // add to list of defined symbols
411 addDefinedSymbol(Name, F, true);
414 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
416 // set alignment part log2() can have rounding errors
417 uint32_t align = def->getAlignment();
418 uint32_t attr = align ? countTrailingZeros(align) : 0;
420 // set permissions part
422 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
424 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
425 if (gv && gv->isConstant())
426 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
428 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
431 // set definition part
432 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
433 attr |= LTO_SYMBOL_DEFINITION_WEAK;
434 else if (def->hasCommonLinkage())
435 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
437 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
440 if (def->hasLocalLinkage())
441 // Ignore visibility if linkage is local.
442 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
443 else if (def->hasHiddenVisibility())
444 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
445 else if (def->hasProtectedVisibility())
446 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
447 else if (canBeOmittedFromSymbolTable(def))
448 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
450 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
452 auto Iter = _defines.insert(Name).first;
454 // fill information structure
455 NameAndAttributes info;
456 StringRef NameRef = Iter->first();
457 info.name = NameRef.data();
458 assert(info.name[NameRef.size()] == '\0');
459 info.attributes = attr;
460 info.isFunction = isFunction;
463 // add to table of symbols
464 _symbols.push_back(info);
467 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
469 void LTOModule::addAsmGlobalSymbol(const char *name,
470 lto_symbol_attributes scope) {
471 auto IterBool = _defines.insert(name);
473 // only add new define if not already defined
474 if (!IterBool.second)
477 NameAndAttributes &info = _undefines[IterBool.first->first().data()];
479 if (info.symbol == nullptr) {
480 // FIXME: This is trying to take care of module ASM like this:
482 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
484 // but is gross and its mother dresses it funny. Have the ASM parser give us
485 // more details for this type of situation so that we're not guessing so
488 // fill information structure
489 info.name = IterBool.first->first().data();
491 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
492 info.isFunction = false;
493 info.symbol = nullptr;
495 // add to table of symbols
496 _symbols.push_back(info);
501 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
503 addDefinedDataSymbol(info.name, info.symbol);
505 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
506 _symbols.back().attributes |= scope;
509 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
511 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
512 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
514 _asm_undefines.push_back(IterBool.first->first().data());
516 // we already have the symbol
517 if (!IterBool.second)
520 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
521 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
522 NameAndAttributes &info = IterBool.first->second;
523 info.name = IterBool.first->first().data();
524 info.attributes = attr;
525 info.isFunction = false;
526 info.symbol = nullptr;
529 /// Add a symbol which isn't defined just yet to a list to be resolved later.
530 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
532 SmallString<64> name;
534 raw_svector_ostream OS(name);
538 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
540 // we already have the symbol
541 if (!IterBool.second)
544 NameAndAttributes &info = IterBool.first->second;
546 info.name = IterBool.first->first().data();
548 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
550 if (decl->hasExternalWeakLinkage())
551 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
553 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
555 info.isFunction = isFunc;
559 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
560 /// them to either the defined or undefined lists.
561 bool LTOModule::parseSymbols(std::string &errMsg) {
562 for (auto &Sym : IRFile->symbols()) {
563 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
564 uint32_t Flags = Sym.getFlags();
565 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
568 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
571 SmallString<64> Buffer;
573 raw_svector_ostream OS(Buffer);
576 const char *Name = Buffer.c_str();
579 addAsmGlobalSymbolUndef(Name);
580 else if (Flags & object::BasicSymbolRef::SF_Global)
581 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
583 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
587 auto *F = dyn_cast<Function>(GV);
589 addPotentialUndefinedSymbol(Sym, F != nullptr);
594 addDefinedFunctionSymbol(Sym);
598 if (isa<GlobalVariable>(GV)) {
599 addDefinedDataSymbol(Sym);
603 assert(isa<GlobalAlias>(GV));
604 addDefinedDataSymbol(Sym);
607 // make symbols for all undefines
608 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
609 e = _undefines.end(); u != e; ++u) {
610 // If this symbol also has a definition, then don't make an undefine because
611 // it is a tentative definition.
612 if (_defines.count(u->getKey())) continue;
613 NameAndAttributes info = u->getValue();
614 _symbols.push_back(info);
620 /// parseMetadata - Parse metadata from the module
621 void LTOModule::parseMetadata() {
623 if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
624 MDNode *LinkerOptions = cast<MDNode>(Val);
625 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
626 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
627 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
628 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
629 // FIXME: Make StringSet::insert match Self-Associative Container
630 // requirements, returning <iter,bool> rather than bool, and use that
633 _linkeropt_strings.insert(MDOption->getString()).first->first();
634 StringRef DepLibName = _target->getSubtargetImpl()
635 ->getTargetLowering()
636 ->getObjFileLowering()
637 .getDepLibFromLinkerOpt(Op);
638 if (!DepLibName.empty())
639 _deplibs.push_back(DepLibName.data());
640 else if (!Op.empty())
641 _linkeropts.push_back(Op.data());
646 // Add other interesting metadata here.