1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCLabel.h"
17 #include "llvm/MC/MCObjectFileInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCSectionCOFF.h"
20 #include "llvm/MC/MCSectionELF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbolCOFF.h"
24 #include "llvm/MC/MCSymbolELF.h"
25 #include "llvm/MC/MCSymbolMachO.h"
26 #include "llvm/Support/COFF.h"
27 #include "llvm/Support/ELF.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/SourceMgr.h"
37 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
38 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
40 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
41 Symbols(Allocator), UsedNames(Allocator),
42 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
43 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
44 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
45 AutoReset(DoAutoReset) {
47 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
49 CompilationDir.clear();
51 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
53 SecureLogUsed = false;
55 if (SrcMgr && SrcMgr->getNumBuffers())
57 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
60 MCContext::~MCContext() {
64 // NOTE: The symbols are all allocated out of a bump pointer allocator,
65 // we don't need to free them here.
67 // If the stream for the .secure_log_unique directive was created free it.
68 delete (raw_ostream *)SecureLog;
71 //===----------------------------------------------------------------------===//
72 // Module Lifetime Management
73 //===----------------------------------------------------------------------===//
75 void MCContext::reset() {
76 // Call the destructors so the fragments are freed
77 for (auto &I : ELFUniquingMap)
78 I.second->~MCSectionELF();
79 for (auto &I : COFFUniquingMap)
80 I.second->~MCSectionCOFF();
81 for (auto &I : MachOUniquingMap)
82 I.second->~MCSectionMachO();
88 CompilationDir.clear();
90 MCDwarfLineTablesCUMap.clear();
91 SectionsForRanges.clear();
92 MCGenDwarfLabelEntries.clear();
93 DwarfDebugFlags = StringRef();
94 DwarfCompileUnitID = 0;
95 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
97 MachOUniquingMap.clear();
98 ELFUniquingMap.clear();
99 COFFUniquingMap.clear();
102 AllowTemporaryLabels = true;
103 DwarfLocSeen = false;
104 GenDwarfForAssembly = false;
105 GenDwarfFileNumber = 0;
108 //===----------------------------------------------------------------------===//
109 // Symbol Manipulation
110 //===----------------------------------------------------------------------===//
112 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
113 SmallString<128> NameSV;
114 StringRef NameRef = Name.toStringRef(NameSV);
116 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
118 MCSymbol *&Sym = Symbols[NameRef];
120 Sym = createSymbol(NameRef, false, false);
125 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
126 MCSymbolELF *&Sym = SectionSymbols[&Section];
130 StringRef Name = Section.getSectionName();
132 MCSymbol *&OldSym = Symbols[Name];
133 if (OldSym && OldSym->isUndefined()) {
134 Sym = cast<MCSymbolELF>(OldSym);
138 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
139 Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
147 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
149 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
150 "$frame_escape_" + Twine(Idx));
153 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
154 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
155 "$parent_frame_offset");
158 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
159 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
163 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
166 switch (MOFI->getObjectFileType()) {
167 case MCObjectFileInfo::IsCOFF:
168 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
169 case MCObjectFileInfo::IsELF:
170 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
171 case MCObjectFileInfo::IsMachO:
172 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
175 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
179 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
181 if (CanBeUnnamed && !UseNamesOnTempLabels)
182 return createSymbolImpl(nullptr, true);
184 // Determine whether this is an user writter assembler temporary or normal
186 bool IsTemporary = CanBeUnnamed;
187 if (AllowTemporaryLabels && !IsTemporary)
188 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
190 SmallString<128> NewName = Name;
191 bool AddSuffix = AlwaysAddSuffix;
192 unsigned &NextUniqueID = NextID[Name];
195 NewName.resize(Name.size());
196 raw_svector_ostream(NewName) << NextUniqueID++;
198 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
199 if (NameEntry.second) {
200 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
201 // of the string that is embedded in the UsedNames entry.
202 return createSymbolImpl(&*NameEntry.first, IsTemporary);
204 assert(IsTemporary && "Cannot rename non-temporary symbols");
207 llvm_unreachable("Infinite loop");
210 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
212 SmallString<128> NameSV;
213 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
214 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
217 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
218 SmallString<128> NameSV;
219 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
220 return createSymbol(NameSV, true, false);
223 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
224 return createTempSymbol("tmp", true, CanBeUnnamed);
227 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
228 MCLabel *&Label = Instances[LocalLabelVal];
230 Label = new (*this) MCLabel(0);
231 return Label->incInstance();
234 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
235 MCLabel *&Label = Instances[LocalLabelVal];
237 Label = new (*this) MCLabel(0);
238 return Label->getInstance();
241 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
243 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
245 Sym = createTempSymbol(false);
249 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
250 unsigned Instance = NextInstance(LocalLabelVal);
251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
254 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
256 unsigned Instance = GetInstance(LocalLabelVal);
259 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
262 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
263 SmallString<128> NameSV;
264 StringRef NameRef = Name.toStringRef(NameSV);
265 return Symbols.lookup(NameRef);
268 //===----------------------------------------------------------------------===//
269 // Section Management
270 //===----------------------------------------------------------------------===//
272 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
273 unsigned TypeAndAttributes,
274 unsigned Reserved2, SectionKind Kind,
275 const char *BeginSymName) {
277 // We unique sections by their segment/section pair. The returned section
278 // may not have the same flags as the requested section, if so this should be
279 // diagnosed by the client as an error.
281 // Form the name to look up.
282 SmallString<64> Name;
287 // Do the lookup, if we have a hit, return it.
288 MCSectionMachO *&Entry = MachOUniquingMap[Name];
292 MCSymbol *Begin = nullptr;
294 Begin = createTempSymbol(BeginSymName, false);
296 // Otherwise, return a new section.
297 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
298 Reserved2, Kind, Begin);
301 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
303 if (const MCSymbol *Group = Section->getGroup())
304 GroupName = Group->getName();
306 unsigned UniqueID = Section->getUniqueID();
307 ELFUniquingMap.erase(
308 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
309 auto I = ELFUniquingMap.insert(std::make_pair(
310 ELFSectionKey{Name, GroupName, UniqueID},
313 StringRef CachedName = I->first.SectionName;
314 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
317 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
318 unsigned Flags, unsigned EntrySize,
319 const MCSymbolELF *Group,
320 const MCSectionELF *Associated) {
321 StringMap<bool>::iterator I;
323 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
326 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
327 EntrySize, Group, true, nullptr, Associated);
330 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
331 unsigned Flags, unsigned EntrySize,
332 StringRef Group, unsigned UniqueID,
333 const char *BeginSymName) {
334 MCSymbolELF *GroupSym = nullptr;
336 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
338 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
339 BeginSymName, nullptr);
342 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
343 unsigned Flags, unsigned EntrySize,
344 const MCSymbolELF *GroupSym,
346 const char *BeginSymName,
347 const MCSectionELF *Associated) {
348 StringRef Group = "";
350 Group = GroupSym->getName();
351 // Do the lookup, if we have a hit, return it.
352 auto IterBool = ELFUniquingMap.insert(
353 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
354 auto &Entry = *IterBool.first;
355 if (!IterBool.second)
358 StringRef CachedName = Entry.first.SectionName;
361 if (Flags & ELF::SHF_EXECINSTR)
362 Kind = SectionKind::getText();
364 Kind = SectionKind::getReadOnly();
366 MCSymbol *Begin = nullptr;
368 Begin = createTempSymbol(BeginSymName, false);
370 MCSectionELF *Result =
371 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
372 GroupSym, UniqueID, Begin, Associated);
373 Entry.second = Result;
377 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
378 MCSectionELF *Result = new (*this)
379 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
380 Group, ~0, nullptr, nullptr);
384 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
385 unsigned Characteristics,
387 StringRef COMDATSymName, int Selection,
388 const char *BeginSymName) {
389 MCSymbol *COMDATSymbol = nullptr;
390 if (!COMDATSymName.empty()) {
391 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
392 COMDATSymName = COMDATSymbol->getName();
395 // Do the lookup, if we have a hit, return it.
396 COFFSectionKey T{Section, COMDATSymName, Selection};
397 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
398 auto Iter = IterBool.first;
399 if (!IterBool.second)
402 MCSymbol *Begin = nullptr;
404 Begin = createTempSymbol(BeginSymName, false);
406 StringRef CachedName = Iter->first.SectionName;
407 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
408 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
410 Iter->second = Result;
414 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
415 unsigned Characteristics,
417 const char *BeginSymName) {
418 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
421 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
422 COFFSectionKey T{Section, "", 0};
423 auto Iter = COFFUniquingMap.find(T);
424 if (Iter == COFFUniquingMap.end())
429 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
430 const MCSymbol *KeySym) {
431 // Return the normal section if we don't have to be associative.
435 // Make an associative section with the same name and kind as the normal
437 unsigned Characteristics =
438 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
439 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
441 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
444 //===----------------------------------------------------------------------===//
446 //===----------------------------------------------------------------------===//
448 /// getDwarfFile - takes a file name an number to place in the dwarf file and
449 /// directory tables. If the file number has already been allocated it is an
450 /// error and zero is returned and the client reports the error, else the
451 /// allocated file number is returned. The file numbers may be in any order.
452 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
453 unsigned FileNumber, unsigned CUID) {
454 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
455 return Table.getFile(Directory, FileName, FileNumber);
458 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
459 /// currently is assigned and false otherwise.
460 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
461 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
462 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
465 return !MCDwarfFiles[FileNumber].Name.empty();
468 /// Remove empty sections from SectionStartEndSyms, to avoid generating
469 /// useless debug info for them.
470 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
471 SectionsForRanges.remove_if(
472 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
475 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
476 // If we have a source manager and a location, use it. Otherwise just
477 // use the generic report_fatal_error().
478 if (!SrcMgr || Loc == SMLoc())
479 report_fatal_error(Msg, false);
481 // Use the source manager to print the message.
482 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
484 // If we reached here, we are failing ungracefully. Run the interrupt handlers
485 // to make sure any special cleanups get done, in particular that we remove
486 // files registered with RemoveFileOnSignal.
487 sys::RunInterruptHandlers();