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 COFFAllocator.DestroyAll();
78 ELFAllocator.DestroyAll();
79 MachOAllocator.DestroyAll();
83 SectionSymbols.clear();
86 CompilationDir.clear();
88 MCDwarfLineTablesCUMap.clear();
89 SectionsForRanges.clear();
90 MCGenDwarfLabelEntries.clear();
91 DwarfDebugFlags = StringRef();
92 DwarfCompileUnitID = 0;
93 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
95 MachOUniquingMap.clear();
96 ELFUniquingMap.clear();
97 COFFUniquingMap.clear();
100 AllowTemporaryLabels = true;
101 DwarfLocSeen = false;
102 GenDwarfForAssembly = false;
103 GenDwarfFileNumber = 0;
106 //===----------------------------------------------------------------------===//
107 // Symbol Manipulation
108 //===----------------------------------------------------------------------===//
110 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
111 SmallString<128> NameSV;
112 StringRef NameRef = Name.toStringRef(NameSV);
114 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
116 MCSymbol *&Sym = Symbols[NameRef];
118 Sym = createSymbol(NameRef, false, false);
123 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
124 MCSymbolELF *&Sym = SectionSymbols[&Section];
128 StringRef Name = Section.getSectionName();
130 MCSymbol *&OldSym = Symbols[Name];
131 if (OldSym && OldSym->isUndefined()) {
132 Sym = cast<MCSymbolELF>(OldSym);
136 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
137 Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
145 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
147 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
148 "$frame_escape_" + Twine(Idx));
151 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
152 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
153 "$parent_frame_offset");
156 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
157 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
161 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
164 switch (MOFI->getObjectFileType()) {
165 case MCObjectFileInfo::IsCOFF:
166 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
167 case MCObjectFileInfo::IsELF:
168 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
169 case MCObjectFileInfo::IsMachO:
170 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
173 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
177 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
179 if (CanBeUnnamed && !UseNamesOnTempLabels)
180 return createSymbolImpl(nullptr, true);
182 // Determine whether this is an user writter assembler temporary or normal
184 bool IsTemporary = CanBeUnnamed;
185 if (AllowTemporaryLabels && !IsTemporary)
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,
210 SmallString<128> NameSV;
211 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
212 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
215 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
216 SmallString<128> NameSV;
217 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
218 return createSymbol(NameSV, true, false);
221 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
222 return createTempSymbol("tmp", true, CanBeUnnamed);
225 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
226 MCLabel *&Label = Instances[LocalLabelVal];
228 Label = new (*this) MCLabel(0);
229 return Label->incInstance();
232 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
233 MCLabel *&Label = Instances[LocalLabelVal];
235 Label = new (*this) MCLabel(0);
236 return Label->getInstance();
239 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
241 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
243 Sym = createTempSymbol(false);
247 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
248 unsigned Instance = NextInstance(LocalLabelVal);
249 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
252 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
254 unsigned Instance = GetInstance(LocalLabelVal);
257 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
260 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
261 SmallString<128> NameSV;
262 StringRef NameRef = Name.toStringRef(NameSV);
263 return Symbols.lookup(NameRef);
266 //===----------------------------------------------------------------------===//
267 // Section Management
268 //===----------------------------------------------------------------------===//
270 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
271 unsigned TypeAndAttributes,
272 unsigned Reserved2, SectionKind Kind,
273 const char *BeginSymName) {
275 // We unique sections by their segment/section pair. The returned section
276 // may not have the same flags as the requested section, if so this should be
277 // diagnosed by the client as an error.
279 // Form the name to look up.
280 SmallString<64> Name;
285 // Do the lookup, if we have a hit, return it.
286 MCSectionMachO *&Entry = MachOUniquingMap[Name];
290 MCSymbol *Begin = nullptr;
292 Begin = createTempSymbol(BeginSymName, false);
294 // Otherwise, return a new section.
295 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
296 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
299 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
301 if (const MCSymbol *Group = Section->getGroup())
302 GroupName = Group->getName();
304 unsigned UniqueID = Section->getUniqueID();
305 ELFUniquingMap.erase(
306 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
307 auto I = ELFUniquingMap.insert(std::make_pair(
308 ELFSectionKey{Name, GroupName, UniqueID},
311 StringRef CachedName = I->first.SectionName;
312 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
315 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
316 unsigned Flags, unsigned EntrySize,
317 const MCSymbolELF *Group,
318 const MCSectionELF *Associated) {
319 StringMap<bool>::iterator I;
321 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
323 return new (ELFAllocator.Allocate())
324 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
325 EntrySize, Group, true, nullptr, Associated);
328 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
329 unsigned Flags, unsigned EntrySize,
330 StringRef Group, unsigned UniqueID,
331 const char *BeginSymName) {
332 MCSymbolELF *GroupSym = nullptr;
334 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
336 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
337 BeginSymName, nullptr);
340 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
341 unsigned Flags, unsigned EntrySize,
342 const MCSymbolELF *GroupSym,
344 const char *BeginSymName,
345 const MCSectionELF *Associated) {
346 StringRef Group = "";
348 Group = GroupSym->getName();
349 // Do the lookup, if we have a hit, return it.
350 auto IterBool = ELFUniquingMap.insert(
351 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
352 auto &Entry = *IterBool.first;
353 if (!IterBool.second)
356 StringRef CachedName = Entry.first.SectionName;
359 if (Flags & ELF::SHF_EXECINSTR)
360 Kind = SectionKind::getText();
362 Kind = SectionKind::getReadOnly();
364 MCSymbol *Begin = nullptr;
366 Begin = createTempSymbol(BeginSymName, false);
368 MCSectionELF *Result = new (ELFAllocator.Allocate())
369 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID,
371 Entry.second = Result;
375 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
376 MCSectionELF *Result = new (ELFAllocator.Allocate())
377 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
378 Group, ~0, nullptr, nullptr);
382 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
383 unsigned Characteristics,
385 StringRef COMDATSymName, int Selection,
386 const char *BeginSymName) {
387 MCSymbol *COMDATSymbol = nullptr;
388 if (!COMDATSymName.empty()) {
389 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
390 COMDATSymName = COMDATSymbol->getName();
393 // Do the lookup, if we have a hit, return it.
394 COFFSectionKey T{Section, COMDATSymName, Selection};
395 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
396 auto Iter = IterBool.first;
397 if (!IterBool.second)
400 MCSymbol *Begin = nullptr;
402 Begin = createTempSymbol(BeginSymName, false);
404 StringRef CachedName = Iter->first.SectionName;
405 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
406 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
408 Iter->second = Result;
412 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
413 unsigned Characteristics,
415 const char *BeginSymName) {
416 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
419 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
420 COFFSectionKey T{Section, "", 0};
421 auto Iter = COFFUniquingMap.find(T);
422 if (Iter == COFFUniquingMap.end())
427 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
428 const MCSymbol *KeySym) {
429 // Return the normal section if we don't have to be associative.
433 // Make an associative section with the same name and kind as the normal
435 unsigned Characteristics =
436 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
437 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
439 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
442 //===----------------------------------------------------------------------===//
444 //===----------------------------------------------------------------------===//
446 /// getDwarfFile - takes a file name an number to place in the dwarf file and
447 /// directory tables. If the file number has already been allocated it is an
448 /// error and zero is returned and the client reports the error, else the
449 /// allocated file number is returned. The file numbers may be in any order.
450 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
451 unsigned FileNumber, unsigned CUID) {
452 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
453 return Table.getFile(Directory, FileName, FileNumber);
456 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
457 /// currently is assigned and false otherwise.
458 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
459 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
460 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
463 return !MCDwarfFiles[FileNumber].Name.empty();
466 /// Remove empty sections from SectionStartEndSyms, to avoid generating
467 /// useless debug info for them.
468 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
469 SectionsForRanges.remove_if(
470 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
473 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
474 // If we have a source manager and a location, use it. Otherwise just
475 // use the generic report_fatal_error().
476 if (!SrcMgr || Loc == SMLoc())
477 report_fatal_error(Msg, false);
479 // Use the source manager to print the message.
480 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
482 // If we reached here, we are failing ungracefully. Run the interrupt handlers
483 // to make sure any special cleanups get done, in particular that we remove
484 // files registered with RemoveFileOnSignal.
485 sys::RunInterruptHandlers();