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/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/Target/TargetSubtargetInfo.h"
44 #include "llvm/Transforms/Utils/GlobalStatus.h"
45 #include <system_error>
48 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
49 llvm::TargetMachine *TM)
50 : IRFile(std::move(Obj)), _target(TM) {}
52 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
54 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
55 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
56 sys::fs::file_magic::bitcode;
59 bool LTOModule::isBitcodeFile(const char *path) {
60 sys::fs::file_magic type;
61 if (sys::fs::identify_magic(path, type))
63 return type == sys::fs::file_magic::bitcode;
66 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
67 StringRef triplePrefix) {
68 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
69 return StringRef(Triple).startswith(triplePrefix);
72 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
73 std::string &errMsg) {
74 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
75 MemoryBuffer::getFile(path);
76 if (std::error_code EC = BufferOrErr.getError()) {
77 errMsg = EC.message();
80 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
83 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
84 TargetOptions options,
85 std::string &errMsg) {
86 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
89 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
90 size_t map_size, off_t offset,
91 TargetOptions options,
92 std::string &errMsg) {
93 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
94 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
95 if (std::error_code EC = BufferOrErr.getError()) {
96 errMsg = EC.message();
99 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
102 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
103 TargetOptions options,
104 std::string &errMsg, StringRef path) {
105 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
108 return makeLTOModule(std::move(buffer), options, errMsg);
111 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
112 TargetOptions options,
113 std::string &errMsg) {
114 ErrorOr<Module *> MOrErr =
115 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
116 if (std::error_code EC = MOrErr.getError()) {
117 errMsg = EC.message();
120 std::unique_ptr<Module> M(MOrErr.get());
122 std::string TripleStr = M->getTargetTriple();
123 if (TripleStr.empty())
124 TripleStr = sys::getDefaultTargetTriple();
125 llvm::Triple Triple(TripleStr);
127 // find machine architecture for this module
128 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
132 // construct LTOModule, hand over ownership of module and target
133 SubtargetFeatures Features;
134 Features.getDefaultSubtargetFeatures(Triple);
135 std::string FeatureStr = Features.getString();
136 // Set a default CPU for Darwin triples.
138 if (Triple.isOSDarwin()) {
139 if (Triple.getArch() == llvm::Triple::x86_64)
141 else if (Triple.getArch() == llvm::Triple::x86)
143 else if (Triple.getArch() == llvm::Triple::aarch64)
147 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
149 M->materializeAllPermanently(true);
150 M->setDataLayout(target->getSubtargetImpl()->getDataLayout());
152 std::unique_ptr<object::IRObjectFile> IRObj(
153 new object::IRObjectFile(std::move(Buffer), std::move(M)));
155 LTOModule *Ret = new LTOModule(std::move(IRObj), target);
157 if (Ret->parseSymbols(errMsg)) {
162 Ret->parseMetadata();
167 /// Create a MemoryBuffer from a memory range with an optional name.
168 std::unique_ptr<MemoryBuffer>
169 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
170 const char *startPtr = (const char*)mem;
171 return std::unique_ptr<MemoryBuffer>(
172 MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false));
175 /// objcClassNameFromExpression - Get string that the data pointer points to.
177 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
178 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
179 Constant *op = ce->getOperand(0);
180 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
181 Constant *cn = gvn->getInitializer();
182 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
183 if (ca->isCString()) {
184 name = ".objc_class_name_" + ca->getAsCString().str();
193 /// addObjCClass - Parse i386/ppc ObjC class data structure.
194 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
195 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
198 // second slot in __OBJC,__class is pointer to superclass name
199 std::string superclassName;
200 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
201 NameAndAttributes info;
202 StringMap<NameAndAttributes>::value_type &entry =
203 _undefines.GetOrCreateValue(superclassName);
204 if (!entry.getValue().name) {
205 const char *symbolName = entry.getKey().data();
206 info.name = symbolName;
207 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
208 info.isFunction = false;
210 entry.setValue(info);
214 // third slot in __OBJC,__class is pointer to class name
215 std::string className;
216 if (objcClassNameFromExpression(c->getOperand(2), className)) {
217 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
220 NameAndAttributes info;
221 info.name = entry.getKey().data();
222 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
223 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
224 info.isFunction = false;
226 _symbols.push_back(info);
230 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
231 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
232 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
235 // second slot in __OBJC,__category is pointer to target class name
236 std::string targetclassName;
237 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
240 NameAndAttributes info;
241 StringMap<NameAndAttributes>::value_type &entry =
242 _undefines.GetOrCreateValue(targetclassName);
244 if (entry.getValue().name)
247 const char *symbolName = entry.getKey().data();
248 info.name = symbolName;
249 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
250 info.isFunction = false;
252 entry.setValue(info);
255 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
256 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
257 std::string targetclassName;
258 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
261 NameAndAttributes info;
262 StringMap<NameAndAttributes>::value_type &entry =
263 _undefines.GetOrCreateValue(targetclassName);
264 if (entry.getValue().name)
267 const char *symbolName = entry.getKey().data();
268 info.name = symbolName;
269 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
270 info.isFunction = false;
272 entry.setValue(info);
275 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
276 SmallString<64> Buffer;
278 raw_svector_ostream OS(Buffer);
282 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
283 addDefinedDataSymbol(Buffer.c_str(), V);
286 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
287 // Add to list of defined symbols.
288 addDefinedSymbol(Name, 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 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
337 SmallString<64> Buffer;
339 raw_svector_ostream OS(Buffer);
344 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
345 addDefinedFunctionSymbol(Buffer.c_str(), F);
348 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
349 // add to list of defined symbols
350 addDefinedSymbol(Name, F, true);
353 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
355 // set alignment part log2() can have rounding errors
356 uint32_t align = def->getAlignment();
357 uint32_t attr = align ? countTrailingZeros(align) : 0;
359 // set permissions part
361 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
363 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
364 if (gv && gv->isConstant())
365 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
367 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
370 // set definition part
371 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
372 attr |= LTO_SYMBOL_DEFINITION_WEAK;
373 else if (def->hasCommonLinkage())
374 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
376 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
379 if (def->hasLocalLinkage())
380 // Ignore visibility if linkage is local.
381 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
382 else if (def->hasHiddenVisibility())
383 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
384 else if (def->hasProtectedVisibility())
385 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
386 else if (canBeOmittedFromSymbolTable(def))
387 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
389 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
391 StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
394 // fill information structure
395 NameAndAttributes info;
396 StringRef NameRef = entry.getKey();
397 info.name = NameRef.data();
398 assert(info.name[NameRef.size()] == '\0');
399 info.attributes = attr;
400 info.isFunction = isFunction;
403 // add to table of symbols
404 _symbols.push_back(info);
407 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
409 void LTOModule::addAsmGlobalSymbol(const char *name,
410 lto_symbol_attributes scope) {
411 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
413 // only add new define if not already defined
414 if (entry.getValue())
419 NameAndAttributes &info = _undefines[entry.getKey().data()];
421 if (info.symbol == nullptr) {
422 // FIXME: This is trying to take care of module ASM like this:
424 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
426 // but is gross and its mother dresses it funny. Have the ASM parser give us
427 // more details for this type of situation so that we're not guessing so
430 // fill information structure
431 info.name = entry.getKey().data();
433 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
434 info.isFunction = false;
435 info.symbol = nullptr;
437 // add to table of symbols
438 _symbols.push_back(info);
443 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
445 addDefinedDataSymbol(info.name, info.symbol);
447 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
448 _symbols.back().attributes |= scope;
451 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
453 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
454 StringMap<NameAndAttributes>::value_type &entry =
455 _undefines.GetOrCreateValue(name);
457 _asm_undefines.push_back(entry.getKey().data());
459 // we already have the symbol
460 if (entry.getValue().name)
463 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
464 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
465 NameAndAttributes info;
466 info.name = entry.getKey().data();
467 info.attributes = attr;
468 info.isFunction = false;
469 info.symbol = nullptr;
471 entry.setValue(info);
474 /// Add a symbol which isn't defined just yet to a list to be resolved later.
475 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
477 SmallString<64> name;
479 raw_svector_ostream OS(name);
483 StringMap<NameAndAttributes>::value_type &entry =
484 _undefines.GetOrCreateValue(name);
486 // we already have the symbol
487 if (entry.getValue().name)
490 NameAndAttributes info;
492 info.name = entry.getKey().data();
494 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
496 if (decl->hasExternalWeakLinkage())
497 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
499 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
501 info.isFunction = isFunc;
504 entry.setValue(info);
507 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
508 /// them to either the defined or undefined lists.
509 bool LTOModule::parseSymbols(std::string &errMsg) {
510 for (auto &Sym : IRFile->symbols()) {
511 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
512 uint32_t Flags = Sym.getFlags();
513 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
516 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
519 SmallString<64> Buffer;
521 raw_svector_ostream OS(Buffer);
524 const char *Name = Buffer.c_str();
527 addAsmGlobalSymbolUndef(Name);
528 else if (Flags & object::BasicSymbolRef::SF_Global)
529 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
531 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
535 auto *F = dyn_cast<Function>(GV);
537 addPotentialUndefinedSymbol(Sym, F != nullptr);
542 addDefinedFunctionSymbol(Sym);
546 if (isa<GlobalVariable>(GV)) {
547 addDefinedDataSymbol(Sym);
551 assert(isa<GlobalAlias>(GV));
552 addDefinedDataSymbol(Sym);
555 // make symbols for all undefines
556 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
557 e = _undefines.end(); u != e; ++u) {
558 // If this symbol also has a definition, then don't make an undefine because
559 // it is a tentative definition.
560 if (_defines.count(u->getKey())) continue;
561 NameAndAttributes info = u->getValue();
562 _symbols.push_back(info);
568 /// parseMetadata - Parse metadata from the module
569 void LTOModule::parseMetadata() {
571 if (Value *Val = getModule().getModuleFlag("Linker Options")) {
572 MDNode *LinkerOptions = cast<MDNode>(Val);
573 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
574 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
575 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
576 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
577 StringRef Op = _linkeropt_strings.
578 GetOrCreateValue(MDOption->getString()).getKey();
579 StringRef DepLibName = _target->getSubtargetImpl()
580 ->getTargetLowering()
581 ->getObjFileLowering()
582 .getDepLibFromLinkerOpt(Op);
583 if (!DepLibName.empty())
584 _deplibs.push_back(DepLibName.data());
585 else if (!Op.empty())
586 _linkeropts.push_back(Op.data());
591 // Add other interesting metadata here.