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) {
69 getBitcodeTargetTriple(buffer->getMemBufferRef(), getGlobalContext());
70 return StringRef(Triple).startswith(triplePrefix);
73 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
74 std::string &errMsg) {
75 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
76 MemoryBuffer::getFile(path);
77 if (std::error_code EC = BufferOrErr.getError()) {
78 errMsg = EC.message();
81 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
82 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg);
85 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
86 TargetOptions options,
87 std::string &errMsg) {
88 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
91 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
92 size_t map_size, off_t offset,
93 TargetOptions options,
94 std::string &errMsg) {
95 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
96 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
97 if (std::error_code EC = BufferOrErr.getError()) {
98 errMsg = EC.message();
101 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
102 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg);
105 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
106 TargetOptions options,
107 std::string &errMsg, StringRef path) {
108 StringRef Data((const char *)mem, length);
109 MemoryBufferRef Buffer(Data, path);
110 return makeLTOModule(Buffer, options, errMsg);
113 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
114 TargetOptions options,
115 std::string &errMsg) {
116 ErrorOr<Module *> MOrErr = parseBitcodeFile(Buffer, getGlobalContext());
117 if (std::error_code EC = MOrErr.getError()) {
118 errMsg = EC.message();
121 std::unique_ptr<Module> M(MOrErr.get());
123 std::string TripleStr = M->getTargetTriple();
124 if (TripleStr.empty())
125 TripleStr = sys::getDefaultTargetTriple();
126 llvm::Triple Triple(TripleStr);
128 // find machine architecture for this module
129 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
133 // construct LTOModule, hand over ownership of module and target
134 SubtargetFeatures Features;
135 Features.getDefaultSubtargetFeatures(Triple);
136 std::string FeatureStr = Features.getString();
137 // Set a default CPU for Darwin triples.
139 if (Triple.isOSDarwin()) {
140 if (Triple.getArch() == llvm::Triple::x86_64)
142 else if (Triple.getArch() == llvm::Triple::x86)
144 else if (Triple.getArch() == llvm::Triple::aarch64)
148 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
150 M->setDataLayout(target->getSubtargetImpl()->getDataLayout());
152 std::unique_ptr<object::IRObjectFile> IRObj(
153 new object::IRObjectFile(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 MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
174 /// objcClassNameFromExpression - Get string that the data pointer points to.
176 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
177 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
178 Constant *op = ce->getOperand(0);
179 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
180 Constant *cn = gvn->getInitializer();
181 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
182 if (ca->isCString()) {
183 name = ".objc_class_name_" + ca->getAsCString().str();
192 /// addObjCClass - Parse i386/ppc ObjC class data structure.
193 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
194 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
197 // second slot in __OBJC,__class is pointer to superclass name
198 std::string superclassName;
199 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
200 NameAndAttributes info;
201 StringMap<NameAndAttributes>::value_type &entry =
202 _undefines.GetOrCreateValue(superclassName);
203 if (!entry.getValue().name) {
204 const char *symbolName = entry.getKey().data();
205 info.name = symbolName;
206 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
207 info.isFunction = false;
209 entry.setValue(info);
213 // third slot in __OBJC,__class is pointer to class name
214 std::string className;
215 if (objcClassNameFromExpression(c->getOperand(2), className)) {
216 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
219 NameAndAttributes info;
220 info.name = entry.getKey().data();
221 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
222 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
223 info.isFunction = false;
225 _symbols.push_back(info);
229 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
230 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
231 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
234 // second slot in __OBJC,__category is pointer to target class name
235 std::string targetclassName;
236 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
239 NameAndAttributes info;
240 StringMap<NameAndAttributes>::value_type &entry =
241 _undefines.GetOrCreateValue(targetclassName);
243 if (entry.getValue().name)
246 const char *symbolName = entry.getKey().data();
247 info.name = symbolName;
248 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
249 info.isFunction = false;
251 entry.setValue(info);
254 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
255 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
256 std::string targetclassName;
257 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
260 NameAndAttributes info;
261 StringMap<NameAndAttributes>::value_type &entry =
262 _undefines.GetOrCreateValue(targetclassName);
263 if (entry.getValue().name)
266 const char *symbolName = entry.getKey().data();
267 info.name = symbolName;
268 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
269 info.isFunction = false;
271 entry.setValue(info);
274 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
275 SmallString<64> Buffer;
277 raw_svector_ostream OS(Buffer);
281 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
282 addDefinedDataSymbol(Buffer.c_str(), V);
285 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
286 // Add to list of defined symbols.
287 addDefinedSymbol(Name, v, false);
289 if (!v->hasSection() /* || !isTargetDarwin */)
292 // Special case i386/ppc ObjC data structures in magic sections:
293 // The issue is that the old ObjC object format did some strange
294 // contortions to avoid real linker symbols. For instance, the
295 // ObjC class data structure is allocated statically in the executable
296 // that defines that class. That data structures contains a pointer to
297 // its superclass. But instead of just initializing that part of the
298 // struct to the address of its superclass, and letting the static and
299 // dynamic linkers do the rest, the runtime works by having that field
300 // instead point to a C-string that is the name of the superclass.
301 // At runtime the objc initialization updates that pointer and sets
302 // it to point to the actual super class. As far as the linker
303 // knows it is just a pointer to a string. But then someone wanted the
304 // linker to issue errors at build time if the superclass was not found.
305 // So they figured out a way in mach-o object format to use an absolute
306 // symbols (.objc_class_name_Foo = 0) and a floating reference
307 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
308 // a class was missing.
309 // The following synthesizes the implicit .objc_* symbols for the linker
310 // from the ObjC data structures generated by the front end.
312 // special case if this data blob is an ObjC class definition
313 std::string Section = v->getSection();
314 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
315 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320 // special case if this data blob is an ObjC category definition
321 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
322 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
327 // special case if this data blob is the list of referenced classes
328 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
329 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
335 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
336 SmallString<64> Buffer;
338 raw_svector_ostream OS(Buffer);
343 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
344 addDefinedFunctionSymbol(Buffer.c_str(), F);
347 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
348 // add to list of defined symbols
349 addDefinedSymbol(Name, F, true);
352 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
354 // set alignment part log2() can have rounding errors
355 uint32_t align = def->getAlignment();
356 uint32_t attr = align ? countTrailingZeros(align) : 0;
358 // set permissions part
360 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
362 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
363 if (gv && gv->isConstant())
364 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
366 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
369 // set definition part
370 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
371 attr |= LTO_SYMBOL_DEFINITION_WEAK;
372 else if (def->hasCommonLinkage())
373 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
375 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
378 if (def->hasLocalLinkage())
379 // Ignore visibility if linkage is local.
380 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
381 else if (def->hasHiddenVisibility())
382 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
383 else if (def->hasProtectedVisibility())
384 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
385 else if (canBeOmittedFromSymbolTable(def))
386 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
388 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
390 StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
393 // fill information structure
394 NameAndAttributes info;
395 StringRef NameRef = entry.getKey();
396 info.name = NameRef.data();
397 assert(info.name[NameRef.size()] == '\0');
398 info.attributes = attr;
399 info.isFunction = isFunction;
402 // add to table of symbols
403 _symbols.push_back(info);
406 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
408 void LTOModule::addAsmGlobalSymbol(const char *name,
409 lto_symbol_attributes scope) {
410 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
412 // only add new define if not already defined
413 if (entry.getValue())
418 NameAndAttributes &info = _undefines[entry.getKey().data()];
420 if (info.symbol == nullptr) {
421 // FIXME: This is trying to take care of module ASM like this:
423 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
425 // but is gross and its mother dresses it funny. Have the ASM parser give us
426 // more details for this type of situation so that we're not guessing so
429 // fill information structure
430 info.name = entry.getKey().data();
432 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
433 info.isFunction = false;
434 info.symbol = nullptr;
436 // add to table of symbols
437 _symbols.push_back(info);
442 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
444 addDefinedDataSymbol(info.name, info.symbol);
446 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
447 _symbols.back().attributes |= scope;
450 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
452 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
453 StringMap<NameAndAttributes>::value_type &entry =
454 _undefines.GetOrCreateValue(name);
456 _asm_undefines.push_back(entry.getKey().data());
458 // we already have the symbol
459 if (entry.getValue().name)
462 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
463 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
464 NameAndAttributes info;
465 info.name = entry.getKey().data();
466 info.attributes = attr;
467 info.isFunction = false;
468 info.symbol = nullptr;
470 entry.setValue(info);
473 /// Add a symbol which isn't defined just yet to a list to be resolved later.
474 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
476 SmallString<64> name;
478 raw_svector_ostream OS(name);
482 StringMap<NameAndAttributes>::value_type &entry =
483 _undefines.GetOrCreateValue(name);
485 // we already have the symbol
486 if (entry.getValue().name)
489 NameAndAttributes info;
491 info.name = entry.getKey().data();
493 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
495 if (decl->hasExternalWeakLinkage())
496 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
498 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
500 info.isFunction = isFunc;
503 entry.setValue(info);
506 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
507 /// them to either the defined or undefined lists.
508 bool LTOModule::parseSymbols(std::string &errMsg) {
509 for (auto &Sym : IRFile->symbols()) {
510 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
511 uint32_t Flags = Sym.getFlags();
512 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
515 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
518 SmallString<64> Buffer;
520 raw_svector_ostream OS(Buffer);
523 const char *Name = Buffer.c_str();
526 addAsmGlobalSymbolUndef(Name);
527 else if (Flags & object::BasicSymbolRef::SF_Global)
528 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
530 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
534 auto *F = dyn_cast<Function>(GV);
536 addPotentialUndefinedSymbol(Sym, F != nullptr);
541 addDefinedFunctionSymbol(Sym);
545 if (isa<GlobalVariable>(GV)) {
546 addDefinedDataSymbol(Sym);
550 assert(isa<GlobalAlias>(GV));
551 addDefinedDataSymbol(Sym);
554 // make symbols for all undefines
555 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
556 e = _undefines.end(); u != e; ++u) {
557 // If this symbol also has a definition, then don't make an undefine because
558 // it is a tentative definition.
559 if (_defines.count(u->getKey())) continue;
560 NameAndAttributes info = u->getValue();
561 _symbols.push_back(info);
567 /// parseMetadata - Parse metadata from the module
568 void LTOModule::parseMetadata() {
570 if (Value *Val = getModule().getModuleFlag("Linker Options")) {
571 MDNode *LinkerOptions = cast<MDNode>(Val);
572 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
573 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
574 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
575 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
576 StringRef Op = _linkeropt_strings.
577 GetOrCreateValue(MDOption->getString()).getKey();
578 StringRef DepLibName = _target->getSubtargetImpl()
579 ->getTargetLowering()
580 ->getObjFileLowering()
581 .getDepLibFromLinkerOpt(Op);
582 if (!DepLibName.empty())
583 _deplibs.push_back(DepLibName.data());
584 else if (!Op.empty())
585 _linkeropts.push_back(Op.data());
590 // Add other interesting metadata here.