1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// 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 #include "llvm/MC/MCContext.h" 10 #include "llvm/ADT/Optional.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/SmallVector.h" 13 #include "llvm/ADT/StringMap.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/Twine.h" 16 #include "llvm/BinaryFormat/COFF.h" 17 #include "llvm/BinaryFormat/ELF.h" 18 #include "llvm/BinaryFormat/XCOFF.h" 19 #include "llvm/MC/MCAsmInfo.h" 20 #include "llvm/MC/MCCodeView.h" 21 #include "llvm/MC/MCDwarf.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCFragment.h" 24 #include "llvm/MC/MCLabel.h" 25 #include "llvm/MC/MCObjectFileInfo.h" 26 #include "llvm/MC/MCSectionCOFF.h" 27 #include "llvm/MC/MCSectionELF.h" 28 #include "llvm/MC/MCSectionMachO.h" 29 #include "llvm/MC/MCSectionWasm.h" 30 #include "llvm/MC/MCSectionXCOFF.h" 31 #include "llvm/MC/MCStreamer.h" 32 #include "llvm/MC/MCSymbol.h" 33 #include "llvm/MC/MCSymbolCOFF.h" 34 #include "llvm/MC/MCSymbolELF.h" 35 #include "llvm/MC/MCSymbolMachO.h" 36 #include "llvm/MC/MCSymbolWasm.h" 37 #include "llvm/MC/MCSymbolXCOFF.h" 38 #include "llvm/MC/SectionKind.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/MemoryBuffer.h" 43 #include "llvm/Support/Path.h" 44 #include "llvm/Support/Signals.h" 45 #include "llvm/Support/SourceMgr.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <cassert> 48 #include <cstdlib> 49 #include <tuple> 50 #include <utility> 51 52 using namespace llvm; 53 54 static cl::opt<char*> 55 AsSecureLogFileName("as-secure-log-file-name", 56 cl::desc("As secure log file name (initialized from " 57 "AS_SECURE_LOG_FILE env variable)"), 58 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden); 59 60 static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &, 61 std::vector<const MDNode *> &) { 62 SMD.print(nullptr, errs()); 63 } 64 65 MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai, 66 const MCRegisterInfo *mri, const MCObjectFileInfo *mofi, 67 const MCSubtargetInfo *msti, const SourceMgr *mgr, 68 MCTargetOptions const *TargetOpts, bool DoAutoReset) 69 : TT(TheTriple), SrcMgr(mgr), InlineSrcMgr(nullptr), 70 DiagHandler(defaultDiagHandler), MAI(mai), MRI(mri), MOFI(mofi), 71 MSTI(msti), Symbols(Allocator), UsedNames(Allocator), 72 InlineAsmUsedLabelNames(Allocator), 73 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), 74 AutoReset(DoAutoReset), TargetOptions(TargetOpts) { 75 SecureLogFile = AsSecureLogFileName; 76 77 if (SrcMgr && SrcMgr->getNumBuffers()) 78 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID()) 79 ->getBufferIdentifier()); 80 81 switch (TheTriple.getObjectFormat()) { 82 case Triple::MachO: 83 Env = IsMachO; 84 break; 85 case Triple::COFF: 86 if (!TheTriple.isOSWindows()) 87 report_fatal_error( 88 "Cannot initialize MC for non-Windows COFF object files."); 89 90 Env = IsCOFF; 91 break; 92 case Triple::ELF: 93 Env = IsELF; 94 break; 95 case Triple::Wasm: 96 Env = IsWasm; 97 break; 98 case Triple::XCOFF: 99 Env = IsXCOFF; 100 break; 101 case Triple::GOFF: 102 report_fatal_error("Cannot initialize MC for GOFF object file format"); 103 break; 104 case Triple::UnknownObjectFormat: 105 report_fatal_error("Cannot initialize MC for unknown object file format."); 106 break; 107 } 108 } 109 110 MCContext::~MCContext() { 111 if (AutoReset) 112 reset(); 113 114 // NOTE: The symbols are all allocated out of a bump pointer allocator, 115 // we don't need to free them here. 116 } 117 118 void MCContext::initInlineSourceManager() { 119 if (!InlineSrcMgr) 120 InlineSrcMgr.reset(new SourceMgr()); 121 } 122 123 //===----------------------------------------------------------------------===// 124 // Module Lifetime Management 125 //===----------------------------------------------------------------------===// 126 127 void MCContext::reset() { 128 SrcMgr = nullptr; 129 InlineSrcMgr.reset(); 130 LocInfos.clear(); 131 DiagHandler = defaultDiagHandler; 132 133 // Call the destructors so the fragments are freed 134 COFFAllocator.DestroyAll(); 135 ELFAllocator.DestroyAll(); 136 MachOAllocator.DestroyAll(); 137 XCOFFAllocator.DestroyAll(); 138 MCInstAllocator.DestroyAll(); 139 140 MCSubtargetAllocator.DestroyAll(); 141 InlineAsmUsedLabelNames.clear(); 142 UsedNames.clear(); 143 Symbols.clear(); 144 Allocator.Reset(); 145 Instances.clear(); 146 CompilationDir.clear(); 147 MainFileName.clear(); 148 MCDwarfLineTablesCUMap.clear(); 149 SectionsForRanges.clear(); 150 MCGenDwarfLabelEntries.clear(); 151 DwarfDebugFlags = StringRef(); 152 DwarfCompileUnitID = 0; 153 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); 154 155 CVContext.reset(); 156 157 MachOUniquingMap.clear(); 158 ELFUniquingMap.clear(); 159 COFFUniquingMap.clear(); 160 WasmUniquingMap.clear(); 161 XCOFFUniquingMap.clear(); 162 163 ELFEntrySizeMap.clear(); 164 ELFSeenGenericMergeableSections.clear(); 165 166 NextID.clear(); 167 AllowTemporaryLabels = true; 168 DwarfLocSeen = false; 169 GenDwarfForAssembly = false; 170 GenDwarfFileNumber = 0; 171 172 HadError = false; 173 } 174 175 //===----------------------------------------------------------------------===// 176 // MCInst Management 177 //===----------------------------------------------------------------------===// 178 179 MCInst *MCContext::createMCInst() { 180 return new (MCInstAllocator.Allocate()) MCInst; 181 } 182 183 //===----------------------------------------------------------------------===// 184 // Symbol Manipulation 185 //===----------------------------------------------------------------------===// 186 187 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { 188 SmallString<128> NameSV; 189 StringRef NameRef = Name.toStringRef(NameSV); 190 191 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!"); 192 193 MCSymbol *&Sym = Symbols[NameRef]; 194 if (!Sym) 195 Sym = createSymbol(NameRef, false, false); 196 197 return Sym; 198 } 199 200 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName, 201 unsigned Idx) { 202 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 203 "$frame_escape_" + Twine(Idx)); 204 } 205 206 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) { 207 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 208 "$parent_frame_offset"); 209 } 210 211 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) { 212 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" + 213 FuncName); 214 } 215 216 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name, 217 bool IsTemporary) { 218 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(), 219 "MCSymbol classes must be trivially destructible"); 220 static_assert(std::is_trivially_destructible<MCSymbolELF>(), 221 "MCSymbol classes must be trivially destructible"); 222 static_assert(std::is_trivially_destructible<MCSymbolMachO>(), 223 "MCSymbol classes must be trivially destructible"); 224 static_assert(std::is_trivially_destructible<MCSymbolWasm>(), 225 "MCSymbol classes must be trivially destructible"); 226 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(), 227 "MCSymbol classes must be trivially destructible"); 228 229 switch (getObjectFileType()) { 230 case MCContext::IsCOFF: 231 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); 232 case MCContext::IsELF: 233 return new (Name, *this) MCSymbolELF(Name, IsTemporary); 234 case MCContext::IsMachO: 235 return new (Name, *this) MCSymbolMachO(Name, IsTemporary); 236 case MCContext::IsWasm: 237 return new (Name, *this) MCSymbolWasm(Name, IsTemporary); 238 case MCContext::IsXCOFF: 239 return createXCOFFSymbolImpl(Name, IsTemporary); 240 } 241 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name, 242 IsTemporary); 243 } 244 245 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix, 246 bool CanBeUnnamed) { 247 if (CanBeUnnamed && !UseNamesOnTempLabels) 248 return createSymbolImpl(nullptr, true); 249 250 // Determine whether this is a user written assembler temporary or normal 251 // label, if used. 252 bool IsTemporary = CanBeUnnamed; 253 if (AllowTemporaryLabels && !IsTemporary) 254 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); 255 256 SmallString<128> NewName = Name; 257 bool AddSuffix = AlwaysAddSuffix; 258 unsigned &NextUniqueID = NextID[Name]; 259 while (true) { 260 if (AddSuffix) { 261 NewName.resize(Name.size()); 262 raw_svector_ostream(NewName) << NextUniqueID++; 263 } 264 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true)); 265 if (NameEntry.second || !NameEntry.first->second) { 266 // Ok, we found a name. 267 // Mark it as used for a non-section symbol. 268 NameEntry.first->second = true; 269 // Have the MCSymbol object itself refer to the copy of the string that is 270 // embedded in the UsedNames entry. 271 return createSymbolImpl(&*NameEntry.first, IsTemporary); 272 } 273 assert(IsTemporary && "Cannot rename non-temporary symbols"); 274 AddSuffix = true; 275 } 276 llvm_unreachable("Infinite loop"); 277 } 278 279 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) { 280 SmallString<128> NameSV; 281 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 282 return createSymbol(NameSV, AlwaysAddSuffix, true); 283 } 284 285 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) { 286 SmallString<128> NameSV; 287 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 288 return createSymbol(NameSV, true, false); 289 } 290 291 MCSymbol *MCContext::createLinkerPrivateTempSymbol() { 292 SmallString<128> NameSV; 293 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp"; 294 return createSymbol(NameSV, true, false); 295 } 296 297 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); } 298 299 MCSymbol *MCContext::createNamedTempSymbol() { 300 return createNamedTempSymbol("tmp"); 301 } 302 303 unsigned MCContext::NextInstance(unsigned LocalLabelVal) { 304 MCLabel *&Label = Instances[LocalLabelVal]; 305 if (!Label) 306 Label = new (*this) MCLabel(0); 307 return Label->incInstance(); 308 } 309 310 unsigned MCContext::GetInstance(unsigned LocalLabelVal) { 311 MCLabel *&Label = Instances[LocalLabelVal]; 312 if (!Label) 313 Label = new (*this) MCLabel(0); 314 return Label->getInstance(); 315 } 316 317 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, 318 unsigned Instance) { 319 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; 320 if (!Sym) 321 Sym = createNamedTempSymbol(); 322 return Sym; 323 } 324 325 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { 326 unsigned Instance = NextInstance(LocalLabelVal); 327 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 328 } 329 330 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, 331 bool Before) { 332 unsigned Instance = GetInstance(LocalLabelVal); 333 if (!Before) 334 ++Instance; 335 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 336 } 337 338 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { 339 SmallString<128> NameSV; 340 StringRef NameRef = Name.toStringRef(NameSV); 341 return Symbols.lookup(NameRef); 342 } 343 344 void MCContext::setSymbolValue(MCStreamer &Streamer, 345 StringRef Sym, 346 uint64_t Val) { 347 auto Symbol = getOrCreateSymbol(Sym); 348 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this)); 349 } 350 351 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) { 352 InlineAsmUsedLabelNames[Sym->getName()] = Sym; 353 } 354 355 MCSymbolXCOFF * 356 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name, 357 bool IsTemporary) { 358 if (!Name) 359 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary); 360 361 StringRef OriginalName = Name->first(); 362 if (OriginalName.startswith("._Renamed..") || 363 OriginalName.startswith("_Renamed..")) 364 reportError(SMLoc(), "invalid symbol name from source"); 365 366 if (MAI->isValidUnquotedName(OriginalName)) 367 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary); 368 369 // Now we have a name that contains invalid character(s) for XCOFF symbol. 370 // Let's replace with something valid, but save the original name so that 371 // we could still use the original name in the symbol table. 372 SmallString<128> InvalidName(OriginalName); 373 374 // If it's an entry point symbol, we will keep the '.' 375 // in front for the convention purpose. Otherwise, add "_Renamed.." 376 // as prefix to signal this is an renamed symbol. 377 const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.'; 378 SmallString<128> ValidName = 379 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed.."); 380 381 // Append the hex values of '_' and invalid characters with "_Renamed.."; 382 // at the same time replace invalid characters with '_'. 383 for (size_t I = 0; I < InvalidName.size(); ++I) { 384 if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') { 385 raw_svector_ostream(ValidName).write_hex(InvalidName[I]); 386 InvalidName[I] = '_'; 387 } 388 } 389 390 // Skip entry point symbol's '.' as we already have a '.' in front of 391 // "_Renamed". 392 if (IsEntryPoint) 393 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1)); 394 else 395 ValidName.append(InvalidName); 396 397 auto NameEntry = UsedNames.insert(std::make_pair(ValidName, true)); 398 assert((NameEntry.second || !NameEntry.first->second) && 399 "This name is used somewhere else."); 400 // Mark the name as used for a non-section symbol. 401 NameEntry.first->second = true; 402 // Have the MCSymbol object itself refer to the copy of the string 403 // that is embedded in the UsedNames entry. 404 MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this) 405 MCSymbolXCOFF(&*NameEntry.first, IsTemporary); 406 XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName)); 407 return XSym; 408 } 409 410 //===----------------------------------------------------------------------===// 411 // Section Management 412 //===----------------------------------------------------------------------===// 413 414 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, 415 unsigned TypeAndAttributes, 416 unsigned Reserved2, SectionKind Kind, 417 const char *BeginSymName) { 418 // We unique sections by their segment/section pair. The returned section 419 // may not have the same flags as the requested section, if so this should be 420 // diagnosed by the client as an error. 421 422 // Form the name to look up. 423 assert(Section.size() <= 16 && "section name is too long"); 424 assert(!memchr(Section.data(), '\0', Section.size()) && 425 "section name cannot contain NUL"); 426 427 // Do the lookup, if we have a hit, return it. 428 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str()); 429 if (!R.second) 430 return R.first->second; 431 432 MCSymbol *Begin = nullptr; 433 if (BeginSymName) 434 Begin = createTempSymbol(BeginSymName, false); 435 436 // Otherwise, return a new section. 437 StringRef Name = R.first->first(); 438 R.first->second = new (MachOAllocator.Allocate()) 439 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()), 440 TypeAndAttributes, Reserved2, Kind, Begin); 441 return R.first->second; 442 } 443 444 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) { 445 StringRef GroupName; 446 if (const MCSymbol *Group = Section->getGroup()) 447 GroupName = Group->getName(); 448 449 // This function is only used by .debug*, which should not have the 450 // SHF_LINK_ORDER flag. 451 unsigned UniqueID = Section->getUniqueID(); 452 ELFUniquingMap.erase( 453 ELFSectionKey{Section->getName(), GroupName, "", UniqueID}); 454 auto I = ELFUniquingMap 455 .insert(std::make_pair( 456 ELFSectionKey{Name, GroupName, "", UniqueID}, Section)) 457 .first; 458 StringRef CachedName = I->first.SectionName; 459 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName); 460 } 461 462 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type, 463 unsigned Flags, SectionKind K, 464 unsigned EntrySize, 465 const MCSymbolELF *Group, 466 bool Comdat, unsigned UniqueID, 467 const MCSymbolELF *LinkedToSym) { 468 MCSymbolELF *R; 469 MCSymbol *&Sym = Symbols[Section]; 470 // A section symbol can not redefine regular symbols. There may be multiple 471 // sections with the same name, in which case the first such section wins. 472 if (Sym && Sym->isDefined() && 473 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) 474 reportError(SMLoc(), "invalid symbol redefinition"); 475 if (Sym && Sym->isUndefined()) { 476 R = cast<MCSymbolELF>(Sym); 477 } else { 478 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first; 479 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false); 480 if (!Sym) 481 Sym = R; 482 } 483 R->setBinding(ELF::STB_LOCAL); 484 R->setType(ELF::STT_SECTION); 485 486 auto *Ret = new (ELFAllocator.Allocate()) 487 MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID, 488 R, LinkedToSym); 489 490 auto *F = new MCDataFragment(); 491 Ret->getFragmentList().insert(Ret->begin(), F); 492 F->setParent(Ret); 493 R->setFragment(F); 494 495 return Ret; 496 } 497 498 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type, 499 unsigned Flags, unsigned EntrySize, 500 const MCSymbolELF *Group, 501 const MCSectionELF *RelInfoSection) { 502 StringMap<bool>::iterator I; 503 bool Inserted; 504 std::tie(I, Inserted) = 505 RelSecNames.insert(std::make_pair(Name.str(), true)); 506 507 return createELFSectionImpl( 508 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group, 509 true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol())); 510 } 511 512 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix, 513 const Twine &Suffix, unsigned Type, 514 unsigned Flags, 515 unsigned EntrySize) { 516 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix, 517 /*IsComdat=*/true); 518 } 519 520 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 521 unsigned Flags, unsigned EntrySize, 522 const Twine &Group, bool IsComdat, 523 unsigned UniqueID, 524 const MCSymbolELF *LinkedToSym) { 525 MCSymbolELF *GroupSym = nullptr; 526 if (!Group.isTriviallyEmpty() && !Group.str().empty()) 527 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group)); 528 529 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat, 530 UniqueID, LinkedToSym); 531 } 532 533 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type, 534 unsigned Flags, unsigned EntrySize, 535 const MCSymbolELF *GroupSym, 536 bool IsComdat, unsigned UniqueID, 537 const MCSymbolELF *LinkedToSym) { 538 StringRef Group = ""; 539 if (GroupSym) 540 Group = GroupSym->getName(); 541 assert(!(LinkedToSym && LinkedToSym->getName().empty())); 542 // Do the lookup, if we have a hit, return it. 543 auto IterBool = ELFUniquingMap.insert(std::make_pair( 544 ELFSectionKey{Section.str(), Group, 545 LinkedToSym ? LinkedToSym->getName() : "", UniqueID}, 546 nullptr)); 547 auto &Entry = *IterBool.first; 548 if (!IterBool.second) 549 return Entry.second; 550 551 StringRef CachedName = Entry.first.SectionName; 552 553 SectionKind Kind; 554 if (Flags & ELF::SHF_ARM_PURECODE) 555 Kind = SectionKind::getExecuteOnly(); 556 else if (Flags & ELF::SHF_EXECINSTR) 557 Kind = SectionKind::getText(); 558 else 559 Kind = SectionKind::getReadOnly(); 560 561 MCSectionELF *Result = 562 createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym, 563 IsComdat, UniqueID, LinkedToSym); 564 Entry.second = Result; 565 566 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(), 567 Result->getUniqueID(), Result->getEntrySize()); 568 569 return Result; 570 } 571 572 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group, 573 bool IsComdat) { 574 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 575 SectionKind::getReadOnly(), 4, Group, IsComdat, 576 MCSection::NonUniqueID, nullptr); 577 } 578 579 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName, 580 unsigned Flags, unsigned UniqueID, 581 unsigned EntrySize) { 582 bool IsMergeable = Flags & ELF::SHF_MERGE; 583 if (IsMergeable && (UniqueID == GenericSectionID)) 584 ELFSeenGenericMergeableSections.insert(SectionName); 585 586 // For mergeable sections or non-mergeable sections with a generic mergeable 587 // section name we enter their Unique ID into the ELFEntrySizeMap so that 588 // compatible globals can be assigned to the same section. 589 if (IsMergeable || isELFGenericMergeableSection(SectionName)) { 590 ELFEntrySizeMap.insert(std::make_pair( 591 ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID)); 592 } 593 } 594 595 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) { 596 return SectionName.startswith(".rodata.str") || 597 SectionName.startswith(".rodata.cst"); 598 } 599 600 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) { 601 return isELFImplicitMergeableSectionNamePrefix(SectionName) || 602 ELFSeenGenericMergeableSections.count(SectionName); 603 } 604 605 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName, 606 unsigned Flags, 607 unsigned EntrySize) { 608 auto I = ELFEntrySizeMap.find( 609 MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize}); 610 return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None; 611 } 612 613 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 614 unsigned Characteristics, 615 SectionKind Kind, 616 StringRef COMDATSymName, int Selection, 617 unsigned UniqueID, 618 const char *BeginSymName) { 619 MCSymbol *COMDATSymbol = nullptr; 620 if (!COMDATSymName.empty()) { 621 COMDATSymbol = getOrCreateSymbol(COMDATSymName); 622 COMDATSymName = COMDATSymbol->getName(); 623 } 624 625 626 // Do the lookup, if we have a hit, return it. 627 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID}; 628 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr)); 629 auto Iter = IterBool.first; 630 if (!IterBool.second) 631 return Iter->second; 632 633 MCSymbol *Begin = nullptr; 634 if (BeginSymName) 635 Begin = createTempSymbol(BeginSymName, false); 636 637 StringRef CachedName = Iter->first.SectionName; 638 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( 639 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin); 640 641 Iter->second = Result; 642 return Result; 643 } 644 645 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 646 unsigned Characteristics, 647 SectionKind Kind, 648 const char *BeginSymName) { 649 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID, 650 BeginSymName); 651 } 652 653 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, 654 const MCSymbol *KeySym, 655 unsigned UniqueID) { 656 // Return the normal section if we don't have to be associative or unique. 657 if (!KeySym && UniqueID == GenericSectionID) 658 return Sec; 659 660 // If we have a key symbol, make an associative section with the same name and 661 // kind as the normal section. 662 unsigned Characteristics = Sec->getCharacteristics(); 663 if (KeySym) { 664 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 665 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), 666 KeySym->getName(), 667 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 668 } 669 670 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0, 671 UniqueID); 672 } 673 674 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K, 675 const Twine &Group, unsigned UniqueID, 676 const char *BeginSymName) { 677 MCSymbolWasm *GroupSym = nullptr; 678 if (!Group.isTriviallyEmpty() && !Group.str().empty()) { 679 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group)); 680 GroupSym->setComdat(true); 681 } 682 683 return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName); 684 } 685 686 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind, 687 const MCSymbolWasm *GroupSym, 688 unsigned UniqueID, 689 const char *BeginSymName) { 690 StringRef Group = ""; 691 if (GroupSym) 692 Group = GroupSym->getName(); 693 // Do the lookup, if we have a hit, return it. 694 auto IterBool = WasmUniquingMap.insert( 695 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr)); 696 auto &Entry = *IterBool.first; 697 if (!IterBool.second) 698 return Entry.second; 699 700 StringRef CachedName = Entry.first.SectionName; 701 702 MCSymbol *Begin = createSymbol(CachedName, true, false); 703 Symbols[Begin->getName()] = Begin; 704 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION); 705 706 MCSectionWasm *Result = new (WasmAllocator.Allocate()) 707 MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin); 708 Entry.second = Result; 709 710 auto *F = new MCDataFragment(); 711 Result->getFragmentList().insert(Result->begin(), F); 712 F->setParent(Result); 713 Begin->setFragment(F); 714 715 return Result; 716 } 717 718 MCSectionXCOFF *MCContext::getXCOFFSection( 719 StringRef Section, SectionKind Kind, 720 Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed, 721 const char *BeginSymName, 722 Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) { 723 bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue(); 724 assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!"); 725 726 // Do the lookup. If we have a hit, return it. 727 auto IterBool = XCOFFUniquingMap.insert(std::make_pair( 728 IsDwarfSec 729 ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue()) 730 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass), 731 nullptr)); 732 auto &Entry = *IterBool.first; 733 if (!IterBool.second) { 734 MCSectionXCOFF *ExistedEntry = Entry.second; 735 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed) 736 report_fatal_error("section's multiply symbols policy does not match"); 737 738 return ExistedEntry; 739 } 740 741 // Otherwise, return a new section. 742 StringRef CachedName = Entry.first.SectionName; 743 MCSymbolXCOFF *QualName = nullptr; 744 // Debug section don't have storage class attribute. 745 if (IsDwarfSec) 746 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName)); 747 else 748 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol( 749 CachedName + "[" + 750 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]")); 751 752 MCSymbol *Begin = nullptr; 753 if (BeginSymName) 754 Begin = createTempSymbol(BeginSymName, false); 755 756 // QualName->getUnqualifiedName() and CachedName are the same except when 757 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol. 758 MCSectionXCOFF *Result = nullptr; 759 if (IsDwarfSec) 760 Result = new (XCOFFAllocator.Allocate()) 761 MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName, 762 DwarfSectionSubtypeFlags.getValue(), Begin, CachedName, 763 MultiSymbolsAllowed); 764 else 765 Result = new (XCOFFAllocator.Allocate()) 766 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass, 767 CsectProp->Type, Kind, QualName, Begin, CachedName, 768 MultiSymbolsAllowed); 769 770 Entry.second = Result; 771 772 auto *F = new MCDataFragment(); 773 Result->getFragmentList().insert(Result->begin(), F); 774 F->setParent(Result); 775 776 if (Begin) 777 Begin->setFragment(F); 778 779 return Result; 780 } 781 782 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { 783 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); 784 } 785 786 void MCContext::addDebugPrefixMapEntry(const std::string &From, 787 const std::string &To) { 788 DebugPrefixMap.insert(std::make_pair(From, To)); 789 } 790 791 void MCContext::RemapDebugPaths() { 792 const auto &DebugPrefixMap = this->DebugPrefixMap; 793 if (DebugPrefixMap.empty()) 794 return; 795 796 const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) { 797 SmallString<256> P(Path); 798 for (const auto &Entry : DebugPrefixMap) { 799 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) { 800 Path = P.str().str(); 801 break; 802 } 803 } 804 }; 805 806 // Remap compilation directory. 807 std::string CompDir = std::string(CompilationDir.str()); 808 RemapDebugPath(CompDir); 809 CompilationDir = CompDir; 810 811 // Remap MCDwarfDirs in all compilation units. 812 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) 813 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) 814 RemapDebugPath(Dir); 815 } 816 817 //===----------------------------------------------------------------------===// 818 // Dwarf Management 819 //===----------------------------------------------------------------------===// 820 821 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) { 822 // MCDwarf needs the root file as well as the compilation directory. 823 // If we find a '.file 0' directive that will supersede these values. 824 Optional<MD5::MD5Result> Cksum; 825 if (getDwarfVersion() >= 5) { 826 MD5 Hash; 827 MD5::MD5Result Sum; 828 Hash.update(Buffer); 829 Hash.final(Sum); 830 Cksum = Sum; 831 } 832 // Canonicalize the root filename. It cannot be empty, and should not 833 // repeat the compilation dir. 834 // The MCContext ctor initializes MainFileName to the name associated with 835 // the SrcMgr's main file ID, which might be the same as InputFileName (and 836 // possibly include directory components). 837 // Or, MainFileName might have been overridden by a -main-file-name option, 838 // which is supposed to be just a base filename with no directory component. 839 // So, if the InputFileName and MainFileName are not equal, assume 840 // MainFileName is a substitute basename and replace the last component. 841 SmallString<1024> FileNameBuf = InputFileName; 842 if (FileNameBuf.empty() || FileNameBuf == "-") 843 FileNameBuf = "<stdin>"; 844 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) { 845 llvm::sys::path::remove_filename(FileNameBuf); 846 llvm::sys::path::append(FileNameBuf, getMainFileName()); 847 } 848 StringRef FileName = FileNameBuf; 849 if (FileName.consume_front(getCompilationDir())) 850 if (llvm::sys::path::is_separator(FileName.front())) 851 FileName = FileName.drop_front(); 852 assert(!FileName.empty()); 853 setMCLineTableRootFile( 854 /*CUID=*/0, getCompilationDir(), FileName, Cksum, None); 855 } 856 857 /// getDwarfFile - takes a file name and number to place in the dwarf file and 858 /// directory tables. If the file number has already been allocated it is an 859 /// error and zero is returned and the client reports the error, else the 860 /// allocated file number is returned. The file numbers may be in any order. 861 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory, 862 StringRef FileName, 863 unsigned FileNumber, 864 Optional<MD5::MD5Result> Checksum, 865 Optional<StringRef> Source, 866 unsigned CUID) { 867 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; 868 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 869 FileNumber); 870 } 871 872 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it 873 /// currently is assigned and false otherwise. 874 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { 875 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID); 876 if (FileNumber == 0) 877 return getDwarfVersion() >= 5; 878 if (FileNumber >= LineTable.getMCDwarfFiles().size()) 879 return false; 880 881 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty(); 882 } 883 884 /// Remove empty sections from SectionsForRanges, to avoid generating 885 /// useless debug info for them. 886 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { 887 SectionsForRanges.remove_if( 888 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); }); 889 } 890 891 CodeViewContext &MCContext::getCVContext() { 892 if (!CVContext.get()) 893 CVContext.reset(new CodeViewContext); 894 return *CVContext.get(); 895 } 896 897 //===----------------------------------------------------------------------===// 898 // Error Reporting 899 //===----------------------------------------------------------------------===// 900 901 void MCContext::diagnose(const SMDiagnostic &SMD) { 902 assert(DiagHandler && "MCContext::DiagHandler is not set"); 903 bool UseInlineSrcMgr = false; 904 const SourceMgr *SMP = nullptr; 905 if (SrcMgr) { 906 SMP = SrcMgr; 907 } else if (InlineSrcMgr) { 908 SMP = InlineSrcMgr.get(); 909 UseInlineSrcMgr = true; 910 } else 911 llvm_unreachable("Either SourceMgr should be available"); 912 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos); 913 } 914 915 void MCContext::reportCommon( 916 SMLoc Loc, 917 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) { 918 // * MCContext::SrcMgr is null when the MC layer emits machine code for input 919 // other than assembly file, say, for .c/.cpp/.ll/.bc. 920 // * MCContext::InlineSrcMgr is null when the inline asm is not used. 921 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr 922 // and MCContext::InlineSrcMgr are null. 923 SourceMgr SM; 924 const SourceMgr *SMP = &SM; 925 bool UseInlineSrcMgr = false; 926 927 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr. 928 // For MC-only execution, only SrcMgr is used; 929 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is 930 // inline asm in the IR. 931 if (Loc.isValid()) { 932 if (SrcMgr) { 933 SMP = SrcMgr; 934 } else if (InlineSrcMgr) { 935 SMP = InlineSrcMgr.get(); 936 UseInlineSrcMgr = true; 937 } else 938 llvm_unreachable("Either SourceMgr should be available"); 939 } 940 941 SMDiagnostic D; 942 GetMessage(D, SMP); 943 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos); 944 } 945 946 void MCContext::reportError(SMLoc Loc, const Twine &Msg) { 947 HadError = true; 948 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) { 949 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg); 950 }); 951 } 952 953 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) { 954 if (TargetOptions && TargetOptions->MCNoWarn) 955 return; 956 if (TargetOptions && TargetOptions->MCFatalWarnings) { 957 reportError(Loc, Msg); 958 } else { 959 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) { 960 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg); 961 }); 962 } 963 } 964 965 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) { 966 reportError(Loc, Msg); 967 968 // If we reached here, we are failing ungracefully. Run the interrupt handlers 969 // to make sure any special cleanups get done, in particular that we remove 970 // files registered with RemoveFileOnSignal. 971 sys::RunInterruptHandlers(); 972 exit(1); 973 } 974