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 15 #include "LTOModule.h" 16 #include "llvm/Constants.h" 17 #include "llvm/LLVMContext.h" 18 #include "llvm/Module.h" 19 #include "llvm/Bitcode/ReaderWriter.h" 20 #include "llvm/MC/MCExpr.h" 21 #include "llvm/MC/MCInst.h" 22 #include "llvm/MC/MCStreamer.h" 23 #include "llvm/MC/MCSubtargetInfo.h" 24 #include "llvm/MC/MCSymbol.h" 25 #include "llvm/MC/MCTargetAsmParser.h" 26 #include "llvm/MC/SubtargetFeature.h" 27 #include "llvm/MC/MCParser/MCAsmParser.h" 28 #include "llvm/Target/TargetRegisterInfo.h" 29 #include "llvm/Support/Host.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/SourceMgr.h" 33 #include "llvm/Support/TargetRegistry.h" 34 #include "llvm/Support/TargetSelect.h" 35 #include "llvm/Support/system_error.h" 36 #include "llvm/ADT/OwningPtr.h" 37 #include "llvm/ADT/Triple.h" 38 using namespace llvm; 39 40 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t) 41 : _module(m), _target(t), 42 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL), 43 _mangler(_context, *_target->getTargetData()) {} 44 45 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM 46 /// bitcode. 47 bool LTOModule::isBitcodeFile(const void *mem, size_t length) { 48 return llvm::sys::IdentifyFileType((char*)mem, length) 49 == llvm::sys::Bitcode_FileType; 50 } 51 52 bool LTOModule::isBitcodeFile(const char *path) { 53 return llvm::sys::Path(path).isBitcodeFile(); 54 } 55 56 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is 57 /// LLVM bitcode for the specified triple. 58 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length, 59 const char *triplePrefix) { 60 MemoryBuffer *buffer = makeBuffer(mem, length); 61 if (!buffer) 62 return false; 63 return isTargetMatch(buffer, triplePrefix); 64 } 65 66 bool LTOModule::isBitcodeFileForTarget(const char *path, 67 const char *triplePrefix) { 68 OwningPtr<MemoryBuffer> buffer; 69 if (MemoryBuffer::getFile(path, buffer)) 70 return false; 71 return isTargetMatch(buffer.take(), triplePrefix); 72 } 73 74 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified 75 /// target triple. 76 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) { 77 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext()); 78 delete buffer; 79 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0; 80 } 81 82 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of 83 /// the buffer. 84 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) { 85 OwningPtr<MemoryBuffer> buffer; 86 if (error_code ec = MemoryBuffer::getFile(path, buffer)) { 87 errMsg = ec.message(); 88 return NULL; 89 } 90 return makeLTOModule(buffer.take(), errMsg); 91 } 92 93 LTOModule *LTOModule::makeLTOModule(int fd, const char *path, 94 size_t size, std::string &errMsg) { 95 return makeLTOModule(fd, path, size, size, 0, errMsg); 96 } 97 98 LTOModule *LTOModule::makeLTOModule(int fd, const char *path, 99 size_t file_size, 100 size_t map_size, 101 off_t offset, 102 std::string &errMsg) { 103 OwningPtr<MemoryBuffer> buffer; 104 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size, 105 map_size, offset, false)) { 106 errMsg = ec.message(); 107 return NULL; 108 } 109 return makeLTOModule(buffer.take(), errMsg); 110 } 111 112 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length, 113 std::string &errMsg) { 114 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length)); 115 if (!buffer) 116 return NULL; 117 return makeLTOModule(buffer.take(), errMsg); 118 } 119 120 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer, 121 std::string &errMsg) { 122 static bool Initialized = false; 123 if (!Initialized) { 124 InitializeAllTargets(); 125 InitializeAllTargetMCs(); 126 InitializeAllAsmParsers(); 127 Initialized = true; 128 } 129 130 // parse bitcode buffer 131 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(), 132 &errMsg)); 133 if (!m) { 134 delete buffer; 135 return NULL; 136 } 137 138 std::string Triple = m->getTargetTriple(); 139 if (Triple.empty()) 140 Triple = sys::getDefaultTargetTriple(); 141 142 // find machine architecture for this module 143 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg); 144 if (!march) 145 return NULL; 146 147 // construct LTOModule, hand over ownership of module and target 148 SubtargetFeatures Features; 149 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple)); 150 std::string FeatureStr = Features.getString(); 151 std::string CPU; 152 TargetOptions Options; 153 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr, 154 Options); 155 LTOModule *Ret = new LTOModule(m.take(), target); 156 if (Ret->parseSymbols(errMsg)) { 157 delete Ret; 158 return NULL; 159 } 160 161 return Ret; 162 } 163 164 /// makeBuffer - Create a MemoryBuffer from a memory range. 165 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) { 166 const char *startPtr = (char*)mem; 167 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false); 168 } 169 170 /// objcClassNameFromExpression - Get string that the data pointer points to. 171 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) { 172 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) { 173 Constant *op = ce->getOperand(0); 174 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) { 175 Constant *cn = gvn->getInitializer(); 176 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) { 177 if (ca->isCString()) { 178 name = ".objc_class_name_" + ca->getAsCString().str(); 179 return true; 180 } 181 } 182 } 183 } 184 return false; 185 } 186 187 /// addObjCClass - Parse i386/ppc ObjC class data structure. 188 void LTOModule::addObjCClass(GlobalVariable *clgv) { 189 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 190 if (!c) return; 191 192 // second slot in __OBJC,__class is pointer to superclass name 193 std::string superclassName; 194 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) { 195 NameAndAttributes info; 196 StringMap<NameAndAttributes>::value_type &entry = 197 _undefines.GetOrCreateValue(superclassName); 198 if (!entry.getValue().name) { 199 const char *symbolName = entry.getKey().data(); 200 info.name = symbolName; 201 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 202 info.isFunction = false; 203 info.symbol = clgv; 204 entry.setValue(info); 205 } 206 } 207 208 // third slot in __OBJC,__class is pointer to class name 209 std::string className; 210 if (objcClassNameFromExpression(c->getOperand(2), className)) { 211 StringSet::value_type &entry = _defines.GetOrCreateValue(className); 212 entry.setValue(1); 213 214 NameAndAttributes info; 215 info.name = entry.getKey().data(); 216 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA | 217 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT; 218 info.isFunction = false; 219 info.symbol = clgv; 220 _symbols.push_back(info); 221 } 222 } 223 224 /// addObjCCategory - Parse i386/ppc ObjC category data structure. 225 void LTOModule::addObjCCategory(GlobalVariable *clgv) { 226 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 227 if (!c) return; 228 229 // second slot in __OBJC,__category is pointer to target class name 230 std::string targetclassName; 231 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName)) 232 return; 233 234 NameAndAttributes info; 235 StringMap<NameAndAttributes>::value_type &entry = 236 _undefines.GetOrCreateValue(targetclassName); 237 238 if (entry.getValue().name) 239 return; 240 241 const char *symbolName = entry.getKey().data(); 242 info.name = symbolName; 243 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 244 info.isFunction = false; 245 info.symbol = clgv; 246 entry.setValue(info); 247 } 248 249 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure. 250 void LTOModule::addObjCClassRef(GlobalVariable *clgv) { 251 std::string targetclassName; 252 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) 253 return; 254 255 NameAndAttributes info; 256 StringMap<NameAndAttributes>::value_type &entry = 257 _undefines.GetOrCreateValue(targetclassName); 258 if (entry.getValue().name) 259 return; 260 261 const char *symbolName = entry.getKey().data(); 262 info.name = symbolName; 263 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 264 info.isFunction = false; 265 info.symbol = clgv; 266 entry.setValue(info); 267 } 268 269 /// addDefinedDataSymbol - Add a data symbol as defined to the list. 270 void LTOModule::addDefinedDataSymbol(GlobalValue *v) { 271 // Add to list of defined symbols. 272 addDefinedSymbol(v, false); 273 274 // Special case i386/ppc ObjC data structures in magic sections: 275 // The issue is that the old ObjC object format did some strange 276 // contortions to avoid real linker symbols. For instance, the 277 // ObjC class data structure is allocated statically in the executable 278 // that defines that class. That data structures contains a pointer to 279 // its superclass. But instead of just initializing that part of the 280 // struct to the address of its superclass, and letting the static and 281 // dynamic linkers do the rest, the runtime works by having that field 282 // instead point to a C-string that is the name of the superclass. 283 // At runtime the objc initialization updates that pointer and sets 284 // it to point to the actual super class. As far as the linker 285 // knows it is just a pointer to a string. But then someone wanted the 286 // linker to issue errors at build time if the superclass was not found. 287 // So they figured out a way in mach-o object format to use an absolute 288 // symbols (.objc_class_name_Foo = 0) and a floating reference 289 // (.reference .objc_class_name_Bar) to cause the linker into erroring when 290 // a class was missing. 291 // The following synthesizes the implicit .objc_* symbols for the linker 292 // from the ObjC data structures generated by the front end. 293 if (v->hasSection() /* && isTargetDarwin */) { 294 // special case if this data blob is an ObjC class definition 295 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) { 296 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 297 addObjCClass(gv); 298 } 299 } 300 301 // special case if this data blob is an ObjC category definition 302 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) { 303 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 304 addObjCCategory(gv); 305 } 306 } 307 308 // special case if this data blob is the list of referenced classes 309 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) { 310 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 311 addObjCClassRef(gv); 312 } 313 } 314 } 315 } 316 317 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list. 318 void LTOModule::addDefinedFunctionSymbol(Function *f) { 319 // add to list of defined symbols 320 addDefinedSymbol(f, true); 321 } 322 323 /// addDefinedSymbol - Add a defined symbol to the list. 324 void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) { 325 // ignore all llvm.* symbols 326 if (def->getName().startswith("llvm.")) 327 return; 328 329 // string is owned by _defines 330 SmallString<64> Buffer; 331 _mangler.getNameWithPrefix(Buffer, def, false); 332 333 // set alignment part log2() can have rounding errors 334 uint32_t align = def->getAlignment(); 335 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0; 336 337 // set permissions part 338 if (isFunction) { 339 attr |= LTO_SYMBOL_PERMISSIONS_CODE; 340 } else { 341 GlobalVariable *gv = dyn_cast<GlobalVariable>(def); 342 if (gv && gv->isConstant()) 343 attr |= LTO_SYMBOL_PERMISSIONS_RODATA; 344 else 345 attr |= LTO_SYMBOL_PERMISSIONS_DATA; 346 } 347 348 // set definition part 349 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() || 350 def->hasLinkerPrivateWeakLinkage() || 351 def->hasLinkerPrivateWeakDefAutoLinkage()) 352 attr |= LTO_SYMBOL_DEFINITION_WEAK; 353 else if (def->hasCommonLinkage()) 354 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE; 355 else 356 attr |= LTO_SYMBOL_DEFINITION_REGULAR; 357 358 // set scope part 359 if (def->hasHiddenVisibility()) 360 attr |= LTO_SYMBOL_SCOPE_HIDDEN; 361 else if (def->hasProtectedVisibility()) 362 attr |= LTO_SYMBOL_SCOPE_PROTECTED; 363 else if (def->hasExternalLinkage() || def->hasWeakLinkage() || 364 def->hasLinkOnceLinkage() || def->hasCommonLinkage() || 365 def->hasLinkerPrivateWeakLinkage()) 366 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 367 else if (def->hasLinkerPrivateWeakDefAutoLinkage()) 368 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN; 369 else 370 attr |= LTO_SYMBOL_SCOPE_INTERNAL; 371 372 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer); 373 entry.setValue(1); 374 375 // fill information structure 376 NameAndAttributes info; 377 StringRef Name = entry.getKey(); 378 info.name = Name.data(); 379 assert(info.name[Name.size()] == '\0'); 380 info.attributes = attr; 381 info.isFunction = isFunction; 382 info.symbol = def; 383 384 // add to table of symbols 385 _symbols.push_back(info); 386 } 387 388 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the 389 /// defined list. 390 void LTOModule::addAsmGlobalSymbol(const char *name, 391 lto_symbol_attributes scope) { 392 StringSet::value_type &entry = _defines.GetOrCreateValue(name); 393 394 // only add new define if not already defined 395 if (entry.getValue()) 396 return; 397 398 entry.setValue(1); 399 400 NameAndAttributes &info = _undefines[entry.getKey().data()]; 401 402 if (info.symbol == 0) { 403 // FIXME: This is trying to take care of module ASM like this: 404 // 405 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0" 406 // 407 // but is gross and its mother dresses it funny. Have the ASM parser give us 408 // more details for this type of situation so that we're not guessing so 409 // much. 410 411 // fill information structure 412 info.name = name; 413 info.attributes = 414 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope; 415 info.isFunction = false; 416 info.symbol = 0; 417 418 // add to table of symbols 419 _symbols.push_back(info); 420 return; 421 } 422 423 if (info.isFunction) 424 addDefinedFunctionSymbol(cast<Function>(info.symbol)); 425 else 426 addDefinedDataSymbol(info.symbol); 427 428 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK; 429 _symbols.back().attributes |= scope; 430 } 431 432 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the 433 /// undefined list. 434 void LTOModule::addAsmGlobalSymbolUndef(const char *name) { 435 StringMap<NameAndAttributes>::value_type &entry = 436 _undefines.GetOrCreateValue(name); 437 438 _asm_undefines.push_back(entry.getKey().data()); 439 440 // we already have the symbol 441 if (entry.getValue().name) 442 return; 443 444 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;; 445 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 446 NameAndAttributes info; 447 info.name = entry.getKey().data(); 448 info.attributes = attr; 449 info.isFunction = false; 450 info.symbol = 0; 451 452 entry.setValue(info); 453 } 454 455 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a 456 /// list to be resolved later. 457 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) { 458 // ignore all llvm.* symbols 459 if (decl->getName().startswith("llvm.")) 460 return; 461 462 // ignore all aliases 463 if (isa<GlobalAlias>(decl)) 464 return; 465 466 SmallString<64> name; 467 _mangler.getNameWithPrefix(name, decl, false); 468 469 StringMap<NameAndAttributes>::value_type &entry = 470 _undefines.GetOrCreateValue(name); 471 472 // we already have the symbol 473 if (entry.getValue().name) 474 return; 475 476 NameAndAttributes info; 477 478 info.name = entry.getKey().data(); 479 480 if (decl->hasExternalWeakLinkage()) 481 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF; 482 else 483 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 484 485 info.isFunction = isFunc; 486 info.symbol = decl; 487 488 entry.setValue(info); 489 } 490 491 namespace { 492 class RecordStreamer : public MCStreamer { 493 public: 494 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used }; 495 496 private: 497 StringMap<State> Symbols; 498 499 void markDefined(const MCSymbol &Symbol) { 500 State &S = Symbols[Symbol.getName()]; 501 switch (S) { 502 case DefinedGlobal: 503 case Global: 504 S = DefinedGlobal; 505 break; 506 case NeverSeen: 507 case Defined: 508 case Used: 509 S = Defined; 510 break; 511 } 512 } 513 void markGlobal(const MCSymbol &Symbol) { 514 State &S = Symbols[Symbol.getName()]; 515 switch (S) { 516 case DefinedGlobal: 517 case Defined: 518 S = DefinedGlobal; 519 break; 520 521 case NeverSeen: 522 case Global: 523 case Used: 524 S = Global; 525 break; 526 } 527 } 528 void markUsed(const MCSymbol &Symbol) { 529 State &S = Symbols[Symbol.getName()]; 530 switch (S) { 531 case DefinedGlobal: 532 case Defined: 533 case Global: 534 break; 535 536 case NeverSeen: 537 case Used: 538 S = Used; 539 break; 540 } 541 } 542 543 // FIXME: mostly copied for the obj streamer. 544 void AddValueSymbols(const MCExpr *Value) { 545 switch (Value->getKind()) { 546 case MCExpr::Target: 547 // FIXME: What should we do in here? 548 break; 549 550 case MCExpr::Constant: 551 break; 552 553 case MCExpr::Binary: { 554 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value); 555 AddValueSymbols(BE->getLHS()); 556 AddValueSymbols(BE->getRHS()); 557 break; 558 } 559 560 case MCExpr::SymbolRef: 561 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol()); 562 break; 563 564 case MCExpr::Unary: 565 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr()); 566 break; 567 } 568 } 569 570 public: 571 typedef StringMap<State>::const_iterator const_iterator; 572 573 const_iterator begin() { 574 return Symbols.begin(); 575 } 576 577 const_iterator end() { 578 return Symbols.end(); 579 } 580 581 RecordStreamer(MCContext &Context) : MCStreamer(Context) {} 582 583 virtual void EmitInstruction(const MCInst &Inst) { 584 // Scan for values. 585 for (unsigned i = Inst.getNumOperands(); i--; ) 586 if (Inst.getOperand(i).isExpr()) 587 AddValueSymbols(Inst.getOperand(i).getExpr()); 588 } 589 virtual void EmitLabel(MCSymbol *Symbol) { 590 Symbol->setSection(*getCurrentSection()); 591 markDefined(*Symbol); 592 } 593 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { 594 // FIXME: should we handle aliases? 595 markDefined(*Symbol); 596 } 597 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) { 598 if (Attribute == MCSA_Global) 599 markGlobal(*Symbol); 600 } 601 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol, 602 unsigned Size , unsigned ByteAlignment) { 603 markDefined(*Symbol); 604 } 605 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, 606 unsigned ByteAlignment) { 607 markDefined(*Symbol); 608 } 609 610 // Noop calls. 611 virtual void ChangeSection(const MCSection *Section) {} 612 virtual void InitSections() {} 613 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {} 614 virtual void EmitThumbFunc(MCSymbol *Func) {} 615 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {} 616 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {} 617 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {} 618 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {} 619 virtual void EmitCOFFSymbolType(int Type) {} 620 virtual void EndCOFFSymbolDef() {} 621 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {} 622 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, 623 unsigned ByteAlignment) {} 624 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, 625 uint64_t Size, unsigned ByteAlignment) {} 626 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {} 627 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size, 628 unsigned AddrSpace) {} 629 virtual void EmitULEB128Value(const MCExpr *Value) {} 630 virtual void EmitSLEB128Value(const MCExpr *Value) {} 631 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, 632 unsigned ValueSize, 633 unsigned MaxBytesToEmit) {} 634 virtual void EmitCodeAlignment(unsigned ByteAlignment, 635 unsigned MaxBytesToEmit) {} 636 virtual bool EmitValueToOffset(const MCExpr *Offset, 637 unsigned char Value ) { return false; } 638 virtual void EmitFileDirective(StringRef Filename) {} 639 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta, 640 const MCSymbol *LastLabel, 641 const MCSymbol *Label, 642 unsigned PointerSize) {} 643 virtual void FinishImpl() {} 644 }; 645 } // end anonymous namespace 646 647 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the 648 /// defined or undefined lists. 649 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) { 650 const std::string &inlineAsm = _module->getModuleInlineAsm(); 651 if (inlineAsm.empty()) 652 return false; 653 654 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context)); 655 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm); 656 SourceMgr SrcMgr; 657 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 658 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, 659 _context, *Streamer, 660 *_target->getMCAsmInfo())); 661 OwningPtr<MCSubtargetInfo> STI(_target->getTarget(). 662 createMCSubtargetInfo(_target->getTargetTriple(), 663 _target->getTargetCPU(), 664 _target->getTargetFeatureString())); 665 OwningPtr<MCTargetAsmParser> 666 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get())); 667 if (!TAP) { 668 errMsg = "target " + std::string(_target->getTarget().getName()) + 669 " does not define AsmParser."; 670 return true; 671 } 672 673 Parser->setTargetParser(*TAP); 674 int Res = Parser->Run(false); 675 if (Res) 676 return true; 677 678 for (RecordStreamer::const_iterator i = Streamer->begin(), 679 e = Streamer->end(); i != e; ++i) { 680 StringRef Key = i->first(); 681 RecordStreamer::State Value = i->second; 682 if (Value == RecordStreamer::DefinedGlobal) 683 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT); 684 else if (Value == RecordStreamer::Defined) 685 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL); 686 else if (Value == RecordStreamer::Global || 687 Value == RecordStreamer::Used) 688 addAsmGlobalSymbolUndef(Key.data()); 689 } 690 return false; 691 } 692 693 /// isDeclaration - Return 'true' if the global value is a declaration. 694 static bool isDeclaration(const GlobalValue &V) { 695 if (V.hasAvailableExternallyLinkage()) 696 return true; 697 if (V.isMaterializable()) 698 return false; 699 return V.isDeclaration(); 700 } 701 702 /// parseSymbols - Parse the symbols from the module and model-level ASM and add 703 /// them to either the defined or undefined lists. 704 bool LTOModule::parseSymbols(std::string &errMsg) { 705 // add functions 706 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) { 707 if (isDeclaration(*f)) 708 addPotentialUndefinedSymbol(f, true); 709 else 710 addDefinedFunctionSymbol(f); 711 } 712 713 // add data 714 for (Module::global_iterator v = _module->global_begin(), 715 e = _module->global_end(); v != e; ++v) { 716 if (isDeclaration(*v)) 717 addPotentialUndefinedSymbol(v, false); 718 else 719 addDefinedDataSymbol(v); 720 } 721 722 // add asm globals 723 if (addAsmGlobalSymbols(errMsg)) 724 return true; 725 726 // add aliases 727 for (Module::alias_iterator a = _module->alias_begin(), 728 e = _module->alias_end(); a != e; ++a) { 729 if (isDeclaration(*a->getAliasedGlobal())) 730 // Is an alias to a declaration. 731 addPotentialUndefinedSymbol(a, false); 732 else 733 addDefinedDataSymbol(a); 734 } 735 736 // make symbols for all undefines 737 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(), 738 e = _undefines.end(); u != e; ++u) { 739 // If this symbol also has a definition, then don't make an undefine because 740 // it is a tentative definition. 741 if (_defines.count(u->getKey())) continue; 742 NameAndAttributes info = u->getValue(); 743 _symbols.push_back(info); 744 } 745 746 return false; 747 } 748