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/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/Object/RecordStreamer.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include <system_error>
47 LTOModule::LTOModule(std::unique_ptr<Module> M, TargetMachine *TM)
48 : _module(std::move(M)), _target(TM),
49 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(),
51 _mangler(TM->getDataLayout()) {
52 ObjFileInfo.InitMCObjectFileInfo(TM->getTargetTriple(),
53 TM->getRelocationModel(), TM->getCodeModel(),
57 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
59 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
60 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
61 sys::fs::file_magic::bitcode;
64 bool LTOModule::isBitcodeFile(const char *path) {
65 sys::fs::file_magic type;
66 if (sys::fs::identify_magic(path, type))
68 return type == sys::fs::file_magic::bitcode;
71 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
72 StringRef triplePrefix) {
73 return getBitcodeTargetTriple(buffer, getGlobalContext()) == triplePrefix;
76 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
77 std::string &errMsg) {
78 std::unique_ptr<MemoryBuffer> buffer;
79 if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
80 errMsg = ec.message();
83 return makeLTOModule(std::move(buffer), options, errMsg);
86 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
87 TargetOptions options,
88 std::string &errMsg) {
89 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
92 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
93 size_t map_size, off_t offset,
94 TargetOptions options,
95 std::string &errMsg) {
96 std::unique_ptr<MemoryBuffer> buffer;
97 if (std::error_code ec =
98 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
99 errMsg = ec.message();
102 return makeLTOModule(std::move(buffer), options, errMsg);
105 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
106 TargetOptions options,
107 std::string &errMsg, StringRef path) {
108 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
111 return makeLTOModule(std::move(buffer), options, errMsg);
114 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
115 TargetOptions options,
116 std::string &errMsg) {
117 // parse bitcode buffer
118 ErrorOr<Module *> ModuleOrErr =
119 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
120 if (std::error_code EC = ModuleOrErr.getError()) {
121 errMsg = EC.message();
125 std::unique_ptr<Module> m(ModuleOrErr.get());
127 std::string TripleStr = m->getTargetTriple();
128 if (TripleStr.empty())
129 TripleStr = sys::getDefaultTargetTriple();
130 llvm::Triple Triple(TripleStr);
132 // find machine architecture for this module
133 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
137 // construct LTOModule, hand over ownership of module and target
138 SubtargetFeatures Features;
139 Features.getDefaultSubtargetFeatures(Triple);
140 std::string FeatureStr = Features.getString();
141 // Set a default CPU for Darwin triples.
143 if (Triple.isOSDarwin()) {
144 if (Triple.getArch() == llvm::Triple::x86_64)
146 else if (Triple.getArch() == llvm::Triple::x86)
148 else if (Triple.getArch() == llvm::Triple::arm64 ||
149 Triple.getArch() == llvm::Triple::aarch64)
153 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
155 m->materializeAllPermanently();
157 LTOModule *Ret = new LTOModule(std::move(m), target);
159 // We need a MCContext set up in order to get mangled names of private
160 // symbols. It is a bit odd that we need to report uses and definitions
161 // of private symbols, but it does look like ld64 expects to be informed
162 // of at least the ones with an 'l' prefix.
163 MCContext &Context = Ret->_context;
164 const TargetLoweringObjectFile &TLOF =
165 target->getTargetLowering()->getObjFileLowering();
166 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
168 if (Ret->parseSymbols(errMsg)) {
173 Ret->parseMetadata();
178 /// Create a MemoryBuffer from a memory range with an optional name.
179 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
181 const char *startPtr = (const char*)mem;
182 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
185 /// objcClassNameFromExpression - Get string that the data pointer points to.
187 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
188 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
189 Constant *op = ce->getOperand(0);
190 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
191 Constant *cn = gvn->getInitializer();
192 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
193 if (ca->isCString()) {
194 name = ".objc_class_name_" + ca->getAsCString().str();
203 /// addObjCClass - Parse i386/ppc ObjC class data structure.
204 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
205 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
208 // second slot in __OBJC,__class is pointer to superclass name
209 std::string superclassName;
210 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
211 NameAndAttributes info;
212 StringMap<NameAndAttributes>::value_type &entry =
213 _undefines.GetOrCreateValue(superclassName);
214 if (!entry.getValue().name) {
215 const char *symbolName = entry.getKey().data();
216 info.name = symbolName;
217 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
218 info.isFunction = false;
220 entry.setValue(info);
224 // third slot in __OBJC,__class is pointer to class name
225 std::string className;
226 if (objcClassNameFromExpression(c->getOperand(2), className)) {
227 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
230 NameAndAttributes info;
231 info.name = entry.getKey().data();
232 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
233 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
234 info.isFunction = false;
236 _symbols.push_back(info);
240 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
241 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
242 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
245 // second slot in __OBJC,__category is pointer to target class name
246 std::string targetclassName;
247 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
250 NameAndAttributes info;
251 StringMap<NameAndAttributes>::value_type &entry =
252 _undefines.GetOrCreateValue(targetclassName);
254 if (entry.getValue().name)
257 const char *symbolName = entry.getKey().data();
258 info.name = symbolName;
259 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
260 info.isFunction = false;
262 entry.setValue(info);
265 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
266 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
267 std::string targetclassName;
268 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
271 NameAndAttributes info;
272 StringMap<NameAndAttributes>::value_type &entry =
273 _undefines.GetOrCreateValue(targetclassName);
274 if (entry.getValue().name)
277 const char *symbolName = entry.getKey().data();
278 info.name = symbolName;
279 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
280 info.isFunction = false;
282 entry.setValue(info);
285 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
286 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
287 // Add to list of defined symbols.
288 addDefinedSymbol(v, false);
290 if (!v->hasSection() /* || !isTargetDarwin */)
293 // Special case i386/ppc ObjC data structures in magic sections:
294 // The issue is that the old ObjC object format did some strange
295 // contortions to avoid real linker symbols. For instance, the
296 // ObjC class data structure is allocated statically in the executable
297 // that defines that class. That data structures contains a pointer to
298 // its superclass. But instead of just initializing that part of the
299 // struct to the address of its superclass, and letting the static and
300 // dynamic linkers do the rest, the runtime works by having that field
301 // instead point to a C-string that is the name of the superclass.
302 // At runtime the objc initialization updates that pointer and sets
303 // it to point to the actual super class. As far as the linker
304 // knows it is just a pointer to a string. But then someone wanted the
305 // linker to issue errors at build time if the superclass was not found.
306 // So they figured out a way in mach-o object format to use an absolute
307 // symbols (.objc_class_name_Foo = 0) and a floating reference
308 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
309 // a class was missing.
310 // The following synthesizes the implicit .objc_* symbols for the linker
311 // from the ObjC data structures generated by the front end.
313 // special case if this data blob is an ObjC class definition
314 std::string Section = v->getSection();
315 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
316 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321 // special case if this data blob is an ObjC category definition
322 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
323 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328 // special case if this data blob is the list of referenced classes
329 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
330 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
336 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
337 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
338 // add to list of defined symbols
339 addDefinedSymbol(f, true);
342 static bool canBeHidden(const GlobalValue *GV) {
343 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
344 GlobalValue::LinkageTypes L = GV->getLinkage();
346 if (L != GlobalValue::LinkOnceODRLinkage)
349 if (GV->hasUnnamedAddr())
352 // If it is a non constant variable, it needs to be uniqued across shared
354 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
355 if (!Var->isConstant())
360 if (GlobalStatus::analyzeGlobal(GV, GS))
363 return !GS.IsCompared;
366 /// addDefinedSymbol - Add a defined symbol to the list.
367 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
368 // ignore all llvm.* symbols
369 if (def->getName().startswith("llvm."))
372 // string is owned by _defines
373 SmallString<64> Buffer;
374 _target->getNameWithPrefix(Buffer, def, _mangler);
376 // set alignment part log2() can have rounding errors
377 uint32_t align = def->getAlignment();
378 uint32_t attr = align ? countTrailingZeros(align) : 0;
380 // set permissions part
382 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
384 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
385 if (gv && gv->isConstant())
386 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
388 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
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;
397 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
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;
410 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
412 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
415 // fill information structure
416 NameAndAttributes info;
417 StringRef Name = entry.getKey();
418 info.name = Name.data();
419 assert(info.name[Name.size()] == '\0');
420 info.attributes = attr;
421 info.isFunction = isFunction;
424 // add to table of symbols
425 _symbols.push_back(info);
428 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
430 void LTOModule::addAsmGlobalSymbol(const char *name,
431 lto_symbol_attributes scope) {
432 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
434 // only add new define if not already defined
435 if (entry.getValue())
440 NameAndAttributes &info = _undefines[entry.getKey().data()];
442 if (info.symbol == nullptr) {
443 // FIXME: This is trying to take care of module ASM like this:
445 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
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
451 // fill information structure
452 info.name = entry.getKey().data();
454 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
455 info.isFunction = false;
456 info.symbol = nullptr;
458 // add to table of symbols
459 _symbols.push_back(info);
464 addDefinedFunctionSymbol(cast<Function>(info.symbol));
466 addDefinedDataSymbol(info.symbol);
468 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
469 _symbols.back().attributes |= scope;
472 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
474 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
475 StringMap<NameAndAttributes>::value_type &entry =
476 _undefines.GetOrCreateValue(name);
478 _asm_undefines.push_back(entry.getKey().data());
480 // we already have the symbol
481 if (entry.getValue().name)
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;
492 entry.setValue(info);
495 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
496 /// list to be resolved later.
498 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
499 // ignore all llvm.* symbols
500 if (decl->getName().startswith("llvm."))
503 // ignore all aliases
504 if (isa<GlobalAlias>(decl))
507 SmallString<64> name;
508 _target->getNameWithPrefix(name, decl, _mangler);
510 StringMap<NameAndAttributes>::value_type &entry =
511 _undefines.GetOrCreateValue(name);
513 // we already have the symbol
514 if (entry.getValue().name)
517 NameAndAttributes info;
519 info.name = entry.getKey().data();
521 if (decl->hasExternalWeakLinkage())
522 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
524 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
526 info.isFunction = isFunc;
529 entry.setValue(info);
532 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
533 /// defined or undefined lists.
534 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
535 const std::string &inlineAsm = _module->getModuleInlineAsm();
536 if (inlineAsm.empty())
539 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
540 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
542 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
543 std::unique_ptr<MCAsmParser> Parser(
544 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
545 const Target &T = _target->getTarget();
546 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
547 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
548 _target->getTargetTriple(), _target->getTargetCPU(),
549 _target->getTargetFeatureString()));
550 std::unique_ptr<MCTargetAsmParser> TAP(
551 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
552 _target->Options.MCOptions));
554 errMsg = "target " + std::string(T.getName()) +
555 " does not define AsmParser.";
559 Parser->setTargetParser(*TAP);
560 if (Parser->Run(false))
563 for (auto &KV : *Streamer) {
564 StringRef Key = KV.first();
565 RecordStreamer::State Value = KV.second;
566 if (Value == RecordStreamer::DefinedGlobal)
567 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
568 else if (Value == RecordStreamer::Defined)
569 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
570 else if (Value == RecordStreamer::Global ||
571 Value == RecordStreamer::Used)
572 addAsmGlobalSymbolUndef(Key.data());
578 /// isDeclaration - Return 'true' if the global value is a declaration.
579 static bool isDeclaration(const GlobalValue &V) {
580 if (V.hasAvailableExternallyLinkage())
583 if (V.isMaterializable())
586 return V.isDeclaration();
589 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
590 /// them to either the defined or undefined lists.
591 bool LTOModule::parseSymbols(std::string &errMsg) {
593 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
594 if (isDeclaration(*f))
595 addPotentialUndefinedSymbol(f, true);
597 addDefinedFunctionSymbol(f);
601 for (Module::global_iterator v = _module->global_begin(),
602 e = _module->global_end(); v != e; ++v) {
603 if (isDeclaration(*v))
604 addPotentialUndefinedSymbol(v, false);
606 addDefinedDataSymbol(v);
610 if (addAsmGlobalSymbols(errMsg))
614 for (const auto &Alias : _module->aliases())
615 addDefinedDataSymbol(&Alias);
617 // make symbols for all undefines
618 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
619 e = _undefines.end(); u != e; ++u) {
620 // If this symbol also has a definition, then don't make an undefine because
621 // it is a tentative definition.
622 if (_defines.count(u->getKey())) continue;
623 NameAndAttributes info = u->getValue();
624 _symbols.push_back(info);
630 /// parseMetadata - Parse metadata from the module
631 void LTOModule::parseMetadata() {
633 if (Value *Val = _module->getModuleFlag("Linker Options")) {
634 MDNode *LinkerOptions = cast<MDNode>(Val);
635 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
636 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
637 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
638 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
639 StringRef Op = _linkeropt_strings.
640 GetOrCreateValue(MDOption->getString()).getKey();
641 StringRef DepLibName = _target->getTargetLowering()->
642 getObjFileLowering().getDepLibFromLinkerOpt(Op);
643 if (!DepLibName.empty())
644 _deplibs.push_back(DepLibName.data());
645 else if (!Op.empty())
646 _linkeropts.push_back(Op.data());
651 // Add other interesting metadata here.