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