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