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/ELF.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
36 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
37 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
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) {
46 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
48 CompilationDir.clear();
50 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
52 SecureLogUsed = false;
54 if (SrcMgr && SrcMgr->getNumBuffers())
56 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
59 MCContext::~MCContext() {
63 // NOTE: The symbols are all allocated out of a bump pointer allocator,
64 // we don't need to free them here.
66 // If the stream for the .secure_log_unique directive was created free it.
67 delete (raw_ostream *)SecureLog;
70 //===----------------------------------------------------------------------===//
71 // Module Lifetime Management
72 //===----------------------------------------------------------------------===//
74 void MCContext::reset() {
75 // Call the destructors so the fragments are freed
76 for (auto &I : ELFUniquingMap)
77 I.second->~MCSectionELF();
78 for (auto &I : COFFUniquingMap)
79 I.second->~MCSectionCOFF();
80 for (auto &I : MachOUniquingMap)
81 I.second->~MCSectionMachO();
87 CompilationDir.clear();
89 MCDwarfLineTablesCUMap.clear();
90 SectionsForRanges.clear();
91 MCGenDwarfLabelEntries.clear();
92 DwarfDebugFlags = StringRef();
93 DwarfCompileUnitID = 0;
94 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
96 MachOUniquingMap.clear();
97 ELFUniquingMap.clear();
98 COFFUniquingMap.clear();
101 AllowTemporaryLabels = true;
102 DwarfLocSeen = false;
103 GenDwarfForAssembly = false;
104 GenDwarfFileNumber = 0;
107 //===----------------------------------------------------------------------===//
108 // Symbol Manipulation
109 //===----------------------------------------------------------------------===//
111 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
112 SmallString<128> NameSV;
113 StringRef NameRef = Name.toStringRef(NameSV);
115 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
117 MCSymbol *&Sym = Symbols[NameRef];
119 Sym = createSymbol(NameRef, false, false);
124 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
125 MCSymbolELF *&Sym = SectionSymbols[&Section];
129 StringRef Name = Section.getSectionName();
131 MCSymbol *&OldSym = Symbols[Name];
132 if (OldSym && OldSym->isUndefined()) {
133 Sym = cast<MCSymbolELF>(OldSym);
137 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
138 Sym = new (*this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
146 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
148 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
149 "$frame_escape_" + Twine(Idx));
152 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
153 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
154 "$parent_frame_offset");
157 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
158 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
162 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
165 switch (MOFI->getObjectFileType()) {
166 case MCObjectFileInfo::IsCOFF:
167 return new (*this) MCSymbolCOFF(Name, IsTemporary);
168 case MCObjectFileInfo::IsELF:
169 return new (*this) MCSymbolELF(Name, IsTemporary);
170 case MCObjectFileInfo::IsMachO:
171 return new (*this) MCSymbolMachO(Name, IsTemporary);
174 return new (*this) MCSymbol(MCSymbol::SymbolKindUnset, Name, IsTemporary);
177 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
179 if (IsTemporary && !UseNamesOnTempLabels)
180 return createSymbolImpl(nullptr, true);
182 // Determine whether this is an user writter assembler temporary or normal
185 if (AllowTemporaryLabels)
186 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
188 SmallString<128> NewName = Name;
189 bool AddSuffix = AlwaysAddSuffix;
190 unsigned &NextUniqueID = NextID[Name];
193 NewName.resize(Name.size());
194 raw_svector_ostream(NewName) << NextUniqueID++;
196 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
197 if (NameEntry.second) {
198 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
199 // of the string that is embedded in the UsedNames entry.
200 return createSymbolImpl(&*NameEntry.first, IsTemporary);
202 assert(IsTemporary && "Cannot rename non-temporary symbols");
205 llvm_unreachable("Infinite loop");
208 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
209 SmallString<128> NameSV;
210 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
211 return createSymbol(NameSV, AlwaysAddSuffix, true);
214 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
215 SmallString<128> NameSV;
216 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
217 return createSymbol(NameSV, true, false);
220 MCSymbol *MCContext::createTempSymbol() {
221 return createTempSymbol("tmp", true);
224 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
225 MCLabel *&Label = Instances[LocalLabelVal];
227 Label = new (*this) MCLabel(0);
228 return Label->incInstance();
231 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
232 MCLabel *&Label = Instances[LocalLabelVal];
234 Label = new (*this) MCLabel(0);
235 return Label->getInstance();
238 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
240 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
242 Sym = createTempSymbol();
246 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
247 unsigned Instance = NextInstance(LocalLabelVal);
248 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
251 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
253 unsigned Instance = GetInstance(LocalLabelVal);
256 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
259 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
260 SmallString<128> NameSV;
261 StringRef NameRef = Name.toStringRef(NameSV);
262 return Symbols.lookup(NameRef);
265 //===----------------------------------------------------------------------===//
266 // Section Management
267 //===----------------------------------------------------------------------===//
269 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
270 unsigned TypeAndAttributes,
271 unsigned Reserved2, SectionKind Kind,
272 const char *BeginSymName) {
274 // We unique sections by their segment/section pair. The returned section
275 // may not have the same flags as the requested section, if so this should be
276 // diagnosed by the client as an error.
278 // Form the name to look up.
279 SmallString<64> Name;
284 // Do the lookup, if we have a hit, return it.
285 MCSectionMachO *&Entry = MachOUniquingMap[Name];
289 MCSymbol *Begin = nullptr;
291 Begin = createTempSymbol(BeginSymName, false);
293 // Otherwise, return a new section.
294 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
295 Reserved2, Kind, Begin);
298 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
300 if (const MCSymbol *Group = Section->getGroup())
301 GroupName = Group->getName();
303 unsigned UniqueID = Section->getUniqueID();
304 ELFUniquingMap.erase(
305 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
306 auto I = ELFUniquingMap.insert(std::make_pair(
307 ELFSectionKey{Name, GroupName, UniqueID},
310 StringRef CachedName = I->first.SectionName;
311 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
314 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
315 unsigned Flags, unsigned EntrySize,
316 const MCSymbolELF *Group,
317 const MCSectionELF *Associated) {
318 StringMap<bool>::iterator I;
320 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
323 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
324 EntrySize, Group, true, nullptr, Associated);
327 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
328 unsigned Flags, unsigned EntrySize,
329 StringRef Group, unsigned UniqueID,
330 const char *BeginSymName) {
331 MCSymbolELF *GroupSym = nullptr;
333 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
335 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
336 BeginSymName, nullptr);
339 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
340 unsigned Flags, unsigned EntrySize,
341 const MCSymbolELF *GroupSym,
343 const char *BeginSymName,
344 const MCSectionELF *Associated) {
345 StringRef Group = "";
347 Group = GroupSym->getName();
348 // Do the lookup, if we have a hit, return it.
349 auto IterBool = ELFUniquingMap.insert(
350 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
351 auto &Entry = *IterBool.first;
352 if (!IterBool.second)
355 StringRef CachedName = Entry.first.SectionName;
358 if (Flags & ELF::SHF_EXECINSTR)
359 Kind = SectionKind::getText();
361 Kind = SectionKind::getReadOnly();
363 MCSymbol *Begin = nullptr;
365 Begin = createTempSymbol(BeginSymName, false);
367 MCSectionELF *Result =
368 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
369 GroupSym, UniqueID, Begin, Associated);
370 Entry.second = Result;
374 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
375 MCSectionELF *Result = new (*this)
376 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
377 Group, ~0, nullptr, nullptr);
381 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
382 unsigned Characteristics,
384 StringRef COMDATSymName, int Selection,
385 const char *BeginSymName) {
386 MCSymbol *COMDATSymbol = nullptr;
387 if (!COMDATSymName.empty()) {
388 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
389 COMDATSymName = COMDATSymbol->getName();
392 // Do the lookup, if we have a hit, return it.
393 COFFSectionKey T{Section, COMDATSymName, Selection};
394 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
395 auto Iter = IterBool.first;
396 if (!IterBool.second)
399 MCSymbol *Begin = nullptr;
401 Begin = createTempSymbol(BeginSymName, false);
403 StringRef CachedName = Iter->first.SectionName;
404 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
405 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
407 Iter->second = Result;
411 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
412 unsigned Characteristics,
414 const char *BeginSymName) {
415 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
418 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
419 COFFSectionKey T{Section, "", 0};
420 auto Iter = COFFUniquingMap.find(T);
421 if (Iter == COFFUniquingMap.end())
426 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
427 const MCSymbol *KeySym) {
428 // Return the normal section if we don't have to be associative.
432 // Make an associative section with the same name and kind as the normal
434 unsigned Characteristics =
435 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
436 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
438 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// getDwarfFile - takes a file name an number to place in the dwarf file and
446 /// directory tables. If the file number has already been allocated it is an
447 /// error and zero is returned and the client reports the error, else the
448 /// allocated file number is returned. The file numbers may be in any order.
449 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
450 unsigned FileNumber, unsigned CUID) {
451 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
452 return Table.getFile(Directory, FileName, FileNumber);
455 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
456 /// currently is assigned and false otherwise.
457 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
458 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
459 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
462 return !MCDwarfFiles[FileNumber].Name.empty();
465 /// Remove empty sections from SectionStartEndSyms, to avoid generating
466 /// useless debug info for them.
467 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
468 SectionsForRanges.remove_if(
469 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
472 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
473 // If we have a source manager and a location, use it. Otherwise just
474 // use the generic report_fatal_error().
475 if (!SrcMgr || Loc == SMLoc())
476 report_fatal_error(Msg, false);
478 // Use the source manager to print the message.
479 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
481 // If we reached here, we are failing ungracefully. Run the interrupt handlers
482 // to make sure any special cleanups get done, in particular that we remove
483 // files registered with RemoveFileOnSignal.
484 sys::RunInterruptHandlers();