1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/MC/MCContext.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/Twine.h" 13 #include "llvm/MC/MCAsmInfo.h" 14 #include "llvm/MC/MCAssembler.h" 15 #include "llvm/MC/MCCodeView.h" 16 #include "llvm/MC/MCDwarf.h" 17 #include "llvm/MC/MCLabel.h" 18 #include "llvm/MC/MCObjectFileInfo.h" 19 #include "llvm/MC/MCRegisterInfo.h" 20 #include "llvm/MC/MCSectionCOFF.h" 21 #include "llvm/MC/MCSectionELF.h" 22 #include "llvm/MC/MCSectionMachO.h" 23 #include "llvm/MC/MCStreamer.h" 24 #include "llvm/MC/MCSymbolCOFF.h" 25 #include "llvm/MC/MCSymbolELF.h" 26 #include "llvm/MC/MCSymbolMachO.h" 27 #include "llvm/Support/COFF.h" 28 #include "llvm/Support/ELF.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/Signals.h" 32 #include "llvm/Support/SourceMgr.h" 33 34 using namespace llvm; 35 36 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri, 37 const MCObjectFileInfo *mofi, const SourceMgr *mgr, 38 bool DoAutoReset) 39 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(), 40 Symbols(Allocator), UsedNames(Allocator), 41 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false), 42 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4), 43 AllowTemporaryLabels(true), DwarfCompileUnitID(0), 44 AutoReset(DoAutoReset), HadError(false) { 45 SecureLogFile = getenv("AS_SECURE_LOG_FILE"); 46 SecureLog = nullptr; 47 SecureLogUsed = false; 48 49 if (SrcMgr && SrcMgr->getNumBuffers()) 50 MainFileName = 51 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier(); 52 } 53 54 MCContext::~MCContext() { 55 if (AutoReset) 56 reset(); 57 58 // NOTE: The symbols are all allocated out of a bump pointer allocator, 59 // we don't need to free them here. 60 } 61 62 //===----------------------------------------------------------------------===// 63 // Module Lifetime Management 64 //===----------------------------------------------------------------------===// 65 66 void MCContext::reset() { 67 // Call the destructors so the fragments are freed 68 COFFAllocator.DestroyAll(); 69 ELFAllocator.DestroyAll(); 70 MachOAllocator.DestroyAll(); 71 72 MCSubtargetAllocator.DestroyAll(); 73 UsedNames.clear(); 74 Symbols.clear(); 75 SectionSymbols.clear(); 76 Allocator.Reset(); 77 Instances.clear(); 78 CompilationDir.clear(); 79 MainFileName.clear(); 80 MCDwarfLineTablesCUMap.clear(); 81 SectionsForRanges.clear(); 82 MCGenDwarfLabelEntries.clear(); 83 DwarfDebugFlags = StringRef(); 84 DwarfCompileUnitID = 0; 85 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0); 86 87 CVContext.reset(); 88 89 MachOUniquingMap.clear(); 90 ELFUniquingMap.clear(); 91 COFFUniquingMap.clear(); 92 93 NextID.clear(); 94 AllowTemporaryLabels = true; 95 DwarfLocSeen = false; 96 GenDwarfForAssembly = false; 97 GenDwarfFileNumber = 0; 98 99 HadError = false; 100 } 101 102 //===----------------------------------------------------------------------===// 103 // Symbol Manipulation 104 //===----------------------------------------------------------------------===// 105 106 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) { 107 SmallString<128> NameSV; 108 StringRef NameRef = Name.toStringRef(NameSV); 109 110 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!"); 111 112 MCSymbol *&Sym = Symbols[NameRef]; 113 if (!Sym) 114 Sym = createSymbol(NameRef, false, false); 115 116 return Sym; 117 } 118 119 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) { 120 MCSymbolELF *&Sym = SectionSymbols[&Section]; 121 if (Sym) 122 return Sym; 123 124 StringRef Name = Section.getSectionName(); 125 auto NameIter = UsedNames.insert(std::make_pair(Name, false)).first; 126 Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false); 127 128 return Sym; 129 } 130 131 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName, 132 unsigned Idx) { 133 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 134 "$frame_escape_" + Twine(Idx)); 135 } 136 137 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) { 138 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName + 139 "$parent_frame_offset"); 140 } 141 142 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) { 143 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" + 144 FuncName); 145 } 146 147 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name, 148 bool IsTemporary) { 149 if (MOFI) { 150 switch (MOFI->getObjectFileType()) { 151 case MCObjectFileInfo::IsCOFF: 152 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary); 153 case MCObjectFileInfo::IsELF: 154 return new (Name, *this) MCSymbolELF(Name, IsTemporary); 155 case MCObjectFileInfo::IsMachO: 156 return new (Name, *this) MCSymbolMachO(Name, IsTemporary); 157 } 158 } 159 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name, 160 IsTemporary); 161 } 162 163 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix, 164 bool CanBeUnnamed) { 165 if (CanBeUnnamed && !UseNamesOnTempLabels) 166 return createSymbolImpl(nullptr, true); 167 168 // Determine whether this is an user writter assembler temporary or normal 169 // label, if used. 170 bool IsTemporary = CanBeUnnamed; 171 if (AllowTemporaryLabels && !IsTemporary) 172 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix()); 173 174 SmallString<128> NewName = Name; 175 bool AddSuffix = AlwaysAddSuffix; 176 unsigned &NextUniqueID = NextID[Name]; 177 for (;;) { 178 if (AddSuffix) { 179 NewName.resize(Name.size()); 180 raw_svector_ostream(NewName) << NextUniqueID++; 181 } 182 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true)); 183 if (NameEntry.second || !NameEntry.first->second) { 184 // Ok, we found a name. 185 // Mark it as used for a non-section symbol. 186 NameEntry.first->second = true; 187 // Have the MCSymbol object itself refer to the copy of the string that is 188 // embedded in the UsedNames entry. 189 return createSymbolImpl(&*NameEntry.first, IsTemporary); 190 } 191 assert(IsTemporary && "Cannot rename non-temporary symbols"); 192 AddSuffix = true; 193 } 194 llvm_unreachable("Infinite loop"); 195 } 196 197 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix, 198 bool CanBeUnnamed) { 199 SmallString<128> NameSV; 200 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name; 201 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed); 202 } 203 204 MCSymbol *MCContext::createLinkerPrivateTempSymbol() { 205 SmallString<128> NameSV; 206 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp"; 207 return createSymbol(NameSV, true, false); 208 } 209 210 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) { 211 return createTempSymbol("tmp", true, CanBeUnnamed); 212 } 213 214 unsigned MCContext::NextInstance(unsigned LocalLabelVal) { 215 MCLabel *&Label = Instances[LocalLabelVal]; 216 if (!Label) 217 Label = new (*this) MCLabel(0); 218 return Label->incInstance(); 219 } 220 221 unsigned MCContext::GetInstance(unsigned LocalLabelVal) { 222 MCLabel *&Label = Instances[LocalLabelVal]; 223 if (!Label) 224 Label = new (*this) MCLabel(0); 225 return Label->getInstance(); 226 } 227 228 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, 229 unsigned Instance) { 230 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)]; 231 if (!Sym) 232 Sym = createTempSymbol(false); 233 return Sym; 234 } 235 236 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) { 237 unsigned Instance = NextInstance(LocalLabelVal); 238 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 239 } 240 241 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal, 242 bool Before) { 243 unsigned Instance = GetInstance(LocalLabelVal); 244 if (!Before) 245 ++Instance; 246 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance); 247 } 248 249 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const { 250 SmallString<128> NameSV; 251 StringRef NameRef = Name.toStringRef(NameSV); 252 return Symbols.lookup(NameRef); 253 } 254 255 //===----------------------------------------------------------------------===// 256 // Section Management 257 //===----------------------------------------------------------------------===// 258 259 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section, 260 unsigned TypeAndAttributes, 261 unsigned Reserved2, SectionKind Kind, 262 const char *BeginSymName) { 263 264 // We unique sections by their segment/section pair. The returned section 265 // may not have the same flags as the requested section, if so this should be 266 // diagnosed by the client as an error. 267 268 // Form the name to look up. 269 SmallString<64> Name; 270 Name += Segment; 271 Name.push_back(','); 272 Name += Section; 273 274 // Do the lookup, if we have a hit, return it. 275 MCSectionMachO *&Entry = MachOUniquingMap[Name]; 276 if (Entry) 277 return Entry; 278 279 MCSymbol *Begin = nullptr; 280 if (BeginSymName) 281 Begin = createTempSymbol(BeginSymName, false); 282 283 // Otherwise, return a new section. 284 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO( 285 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin); 286 } 287 288 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) { 289 StringRef GroupName; 290 if (const MCSymbol *Group = Section->getGroup()) 291 GroupName = Group->getName(); 292 293 unsigned UniqueID = Section->getUniqueID(); 294 ELFUniquingMap.erase( 295 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID}); 296 auto I = ELFUniquingMap.insert(std::make_pair( 297 ELFSectionKey{Name, GroupName, UniqueID}, 298 Section)) 299 .first; 300 StringRef CachedName = I->first.SectionName; 301 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName); 302 } 303 304 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type, 305 unsigned Flags, unsigned EntrySize, 306 const MCSymbolELF *Group, 307 const MCSectionELF *Associated) { 308 StringMap<bool>::iterator I; 309 bool Inserted; 310 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true)); 311 312 return new (ELFAllocator.Allocate()) 313 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(), 314 EntrySize, Group, true, nullptr, Associated); 315 } 316 317 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type, 318 unsigned Flags, unsigned EntrySize, 319 StringRef Group, unsigned UniqueID, 320 const char *BeginSymName) { 321 MCSymbolELF *GroupSym = nullptr; 322 if (!Group.empty()) 323 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group)); 324 325 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID, 326 BeginSymName, nullptr); 327 } 328 329 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type, 330 unsigned Flags, unsigned EntrySize, 331 const MCSymbolELF *GroupSym, 332 unsigned UniqueID, 333 const char *BeginSymName, 334 const MCSectionELF *Associated) { 335 StringRef Group = ""; 336 if (GroupSym) 337 Group = GroupSym->getName(); 338 // Do the lookup, if we have a hit, return it. 339 auto IterBool = ELFUniquingMap.insert( 340 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr)); 341 auto &Entry = *IterBool.first; 342 if (!IterBool.second) 343 return Entry.second; 344 345 StringRef CachedName = Entry.first.SectionName; 346 347 SectionKind Kind; 348 if (Flags & ELF::SHF_EXECINSTR) 349 Kind = SectionKind::getText(); 350 else 351 Kind = SectionKind::getReadOnly(); 352 353 MCSymbol *Begin = nullptr; 354 if (BeginSymName) 355 Begin = createTempSymbol(BeginSymName, false); 356 357 MCSectionELF *Result = new (ELFAllocator.Allocate()) 358 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, 359 Begin, Associated); 360 Entry.second = Result; 361 return Result; 362 } 363 364 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) { 365 MCSectionELF *Result = new (ELFAllocator.Allocate()) 366 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4, 367 Group, ~0, nullptr, nullptr); 368 return Result; 369 } 370 371 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 372 unsigned Characteristics, 373 SectionKind Kind, 374 StringRef COMDATSymName, int Selection, 375 const char *BeginSymName) { 376 MCSymbol *COMDATSymbol = nullptr; 377 if (!COMDATSymName.empty()) { 378 COMDATSymbol = getOrCreateSymbol(COMDATSymName); 379 COMDATSymName = COMDATSymbol->getName(); 380 } 381 382 // Do the lookup, if we have a hit, return it. 383 COFFSectionKey T{Section, COMDATSymName, Selection}; 384 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr)); 385 auto Iter = IterBool.first; 386 if (!IterBool.second) 387 return Iter->second; 388 389 MCSymbol *Begin = nullptr; 390 if (BeginSymName) 391 Begin = createTempSymbol(BeginSymName, false); 392 393 StringRef CachedName = Iter->first.SectionName; 394 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF( 395 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin); 396 397 Iter->second = Result; 398 return Result; 399 } 400 401 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section, 402 unsigned Characteristics, 403 SectionKind Kind, 404 const char *BeginSymName) { 405 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName); 406 } 407 408 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) { 409 COFFSectionKey T{Section, "", 0}; 410 auto Iter = COFFUniquingMap.find(T); 411 if (Iter == COFFUniquingMap.end()) 412 return nullptr; 413 return Iter->second; 414 } 415 416 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec, 417 const MCSymbol *KeySym) { 418 // Return the normal section if we don't have to be associative. 419 if (!KeySym) 420 return Sec; 421 422 // Make an associative section with the same name and kind as the normal 423 // section. 424 unsigned Characteristics = 425 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT; 426 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(), 427 KeySym->getName(), 428 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE); 429 } 430 431 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) { 432 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Dwarf Management 437 //===----------------------------------------------------------------------===// 438 439 /// getDwarfFile - takes a file name an number to place in the dwarf file and 440 /// directory tables. If the file number has already been allocated it is an 441 /// error and zero is returned and the client reports the error, else the 442 /// allocated file number is returned. The file numbers may be in any order. 443 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName, 444 unsigned FileNumber, unsigned CUID) { 445 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID]; 446 return Table.getFile(Directory, FileName, FileNumber); 447 } 448 449 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it 450 /// currently is assigned and false otherwise. 451 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) { 452 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID); 453 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size()) 454 return false; 455 456 return !MCDwarfFiles[FileNumber].Name.empty(); 457 } 458 459 /// Remove empty sections from SectionStartEndSyms, to avoid generating 460 /// useless debug info for them. 461 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) { 462 SectionsForRanges.remove_if( 463 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); }); 464 } 465 466 CodeViewContext &MCContext::getCVContext() { 467 if (!CVContext.get()) 468 CVContext.reset(new CodeViewContext); 469 return *CVContext.get(); 470 } 471 472 unsigned MCContext::getCVFile(StringRef FileName, unsigned FileNumber) { 473 return getCVContext().addFile(FileNumber, FileName) ? FileNumber : 0; 474 } 475 476 bool MCContext::isValidCVFileNumber(unsigned FileNumber) { 477 return getCVContext().isValidFileNumber(FileNumber); 478 } 479 480 //===----------------------------------------------------------------------===// 481 // Error Reporting 482 //===----------------------------------------------------------------------===// 483 484 void MCContext::reportError(SMLoc Loc, const Twine &Msg) { 485 HadError = true; 486 487 // If we have a source manager use it. Otherwise just use the generic 488 // report_fatal_error(). 489 if (!SrcMgr) 490 report_fatal_error(Msg, false); 491 492 // Use the source manager to print the message. 493 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg); 494 } 495 496 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) { 497 reportError(Loc, Msg); 498 499 // If we reached here, we are failing ungracefully. Run the interrupt handlers 500 // to make sure any special cleanups get done, in particular that we remove 501 // files registered with RemoveFileOnSignal. 502 sys::RunInterruptHandlers(); 503 exit(1); 504 } 505