LTOModule.cpp 22 KB

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