LTOModule.cpp 23 KB

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