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 (&*NameIter, *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 (Name, *this) MCSymbolCOFF(Name, IsTemporary);
168 case MCObjectFileInfo::IsELF:
169 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
170 case MCObjectFileInfo::IsMachO:
171 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
174 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
178 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
180 if (CanBeUnnamed && !UseNamesOnTempLabels)
181 return createSymbolImpl(nullptr, true);
183 // Determine whether this is an user writter assembler temporary or normal
185 bool IsTemporary = CanBeUnnamed;
186 if (AllowTemporaryLabels && !IsTemporary)
187 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
189 SmallString<128> NewName = Name;
190 bool AddSuffix = AlwaysAddSuffix;
191 unsigned &NextUniqueID = NextID[Name];
194 NewName.resize(Name.size());
195 raw_svector_ostream(NewName) << NextUniqueID++;
197 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
198 if (NameEntry.second) {
199 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
200 // of the string that is embedded in the UsedNames entry.
201 return createSymbolImpl(&*NameEntry.first, IsTemporary);
203 assert(IsTemporary && "Cannot rename non-temporary symbols");
206 llvm_unreachable("Infinite loop");
209 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
211 SmallString<128> NameSV;
212 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
213 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
216 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
217 SmallString<128> NameSV;
218 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
219 return createSymbol(NameSV, true, false);
222 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
223 return createTempSymbol("tmp", true, CanBeUnnamed);
226 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
227 MCLabel *&Label = Instances[LocalLabelVal];
229 Label = new (*this) MCLabel(0);
230 return Label->incInstance();
233 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
234 MCLabel *&Label = Instances[LocalLabelVal];
236 Label = new (*this) MCLabel(0);
237 return Label->getInstance();
240 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
242 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
244 Sym = createTempSymbol(false);
248 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
249 unsigned Instance = NextInstance(LocalLabelVal);
250 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
253 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
255 unsigned Instance = GetInstance(LocalLabelVal);
258 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
261 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
262 SmallString<128> NameSV;
263 StringRef NameRef = Name.toStringRef(NameSV);
264 return Symbols.lookup(NameRef);
267 //===----------------------------------------------------------------------===//
268 // Section Management
269 //===----------------------------------------------------------------------===//
271 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
272 unsigned TypeAndAttributes,
273 unsigned Reserved2, SectionKind Kind,
274 const char *BeginSymName) {
276 // We unique sections by their segment/section pair. The returned section
277 // may not have the same flags as the requested section, if so this should be
278 // diagnosed by the client as an error.
280 // Form the name to look up.
281 SmallString<64> Name;
286 // Do the lookup, if we have a hit, return it.
287 MCSectionMachO *&Entry = MachOUniquingMap[Name];
291 MCSymbol *Begin = nullptr;
293 Begin = createTempSymbol(BeginSymName, false);
295 // Otherwise, return a new section.
296 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
297 Reserved2, Kind, Begin);
300 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
302 if (const MCSymbol *Group = Section->getGroup())
303 GroupName = Group->getName();
305 unsigned UniqueID = Section->getUniqueID();
306 ELFUniquingMap.erase(
307 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
308 auto I = ELFUniquingMap.insert(std::make_pair(
309 ELFSectionKey{Name, GroupName, UniqueID},
312 StringRef CachedName = I->first.SectionName;
313 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
316 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
317 unsigned Flags, unsigned EntrySize,
318 const MCSymbolELF *Group,
319 const MCSectionELF *Associated) {
320 StringMap<bool>::iterator I;
322 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
325 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
326 EntrySize, Group, true, nullptr, Associated);
329 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
330 unsigned Flags, unsigned EntrySize,
331 StringRef Group, unsigned UniqueID,
332 const char *BeginSymName) {
333 MCSymbolELF *GroupSym = nullptr;
335 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
337 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
338 BeginSymName, nullptr);
341 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
342 unsigned Flags, unsigned EntrySize,
343 const MCSymbolELF *GroupSym,
345 const char *BeginSymName,
346 const MCSectionELF *Associated) {
347 StringRef Group = "";
349 Group = GroupSym->getName();
350 // Do the lookup, if we have a hit, return it.
351 auto IterBool = ELFUniquingMap.insert(
352 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
353 auto &Entry = *IterBool.first;
354 if (!IterBool.second)
357 StringRef CachedName = Entry.first.SectionName;
360 if (Flags & ELF::SHF_EXECINSTR)
361 Kind = SectionKind::getText();
363 Kind = SectionKind::getReadOnly();
365 MCSymbol *Begin = nullptr;
367 Begin = createTempSymbol(BeginSymName, false);
369 MCSectionELF *Result =
370 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
371 GroupSym, UniqueID, Begin, Associated);
372 Entry.second = Result;
376 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
377 MCSectionELF *Result = new (*this)
378 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
379 Group, ~0, nullptr, nullptr);
383 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
384 unsigned Characteristics,
386 StringRef COMDATSymName, int Selection,
387 const char *BeginSymName) {
388 MCSymbol *COMDATSymbol = nullptr;
389 if (!COMDATSymName.empty()) {
390 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
391 COMDATSymName = COMDATSymbol->getName();
394 // Do the lookup, if we have a hit, return it.
395 COFFSectionKey T{Section, COMDATSymName, Selection};
396 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
397 auto Iter = IterBool.first;
398 if (!IterBool.second)
401 MCSymbol *Begin = nullptr;
403 Begin = createTempSymbol(BeginSymName, false);
405 StringRef CachedName = Iter->first.SectionName;
406 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
407 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
409 Iter->second = Result;
413 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
414 unsigned Characteristics,
416 const char *BeginSymName) {
417 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
420 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
421 COFFSectionKey T{Section, "", 0};
422 auto Iter = COFFUniquingMap.find(T);
423 if (Iter == COFFUniquingMap.end())
428 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
429 const MCSymbol *KeySym) {
430 // Return the normal section if we don't have to be associative.
434 // Make an associative section with the same name and kind as the normal
436 unsigned Characteristics =
437 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
438 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
440 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
443 //===----------------------------------------------------------------------===//
445 //===----------------------------------------------------------------------===//
447 /// getDwarfFile - takes a file name an number to place in the dwarf file and
448 /// directory tables. If the file number has already been allocated it is an
449 /// error and zero is returned and the client reports the error, else the
450 /// allocated file number is returned. The file numbers may be in any order.
451 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
452 unsigned FileNumber, unsigned CUID) {
453 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
454 return Table.getFile(Directory, FileName, FileNumber);
457 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
458 /// currently is assigned and false otherwise.
459 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
460 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
461 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
464 return !MCDwarfFiles[FileNumber].Name.empty();
467 /// Remove empty sections from SectionStartEndSyms, to avoid generating
468 /// useless debug info for them.
469 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
470 SectionsForRanges.remove_if(
471 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
474 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
475 // If we have a source manager and a location, use it. Otherwise just
476 // use the generic report_fatal_error().
477 if (!SrcMgr || Loc == SMLoc())
478 report_fatal_error(Msg, false);
480 // Use the source manager to print the message.
481 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
483 // If we reached here, we are failing ungracefully. Run the interrupt handlers
484 // to make sure any special cleanups get done, in particular that we remove
485 // files registered with RemoveFileOnSignal.
486 sys::RunInterruptHandlers();