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/MCSymbol.h"
24 #include "llvm/Support/ELF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/SourceMgr.h"
34 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
35 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
37 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
38 Symbols(Allocator), UsedNames(Allocator),
39 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
40 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
41 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
42 AutoReset(DoAutoReset) {
44 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
46 CompilationDir.clear();
48 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
50 SecureLogUsed = false;
52 if (SrcMgr && SrcMgr->getNumBuffers())
54 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
57 MCContext::~MCContext() {
61 // NOTE: The symbols are all allocated out of a bump pointer allocator,
62 // we don't need to free them here.
64 // If the stream for the .secure_log_unique directive was created free it.
65 delete (raw_ostream *)SecureLog;
68 //===----------------------------------------------------------------------===//
69 // Module Lifetime Management
70 //===----------------------------------------------------------------------===//
72 void MCContext::reset() {
73 // Call the destructors so the fragments are freed
74 for (auto &I : ELFUniquingMap)
75 I.second->~MCSectionELF();
76 for (auto &I : COFFUniquingMap)
77 I.second->~MCSectionCOFF();
78 for (auto &I : MachOUniquingMap)
79 I.second->~MCSectionMachO();
85 CompilationDir.clear();
87 MCDwarfLineTablesCUMap.clear();
88 SectionsForRanges.clear();
89 MCGenDwarfLabelEntries.clear();
90 DwarfDebugFlags = StringRef();
91 DwarfCompileUnitID = 0;
92 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
94 MachOUniquingMap.clear();
95 ELFUniquingMap.clear();
96 COFFUniquingMap.clear();
99 AllowTemporaryLabels = true;
100 DwarfLocSeen = false;
101 GenDwarfForAssembly = false;
102 GenDwarfFileNumber = 0;
105 //===----------------------------------------------------------------------===//
106 // Symbol Manipulation
107 //===----------------------------------------------------------------------===//
109 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
110 SmallString<128> NameSV;
111 StringRef NameRef = Name.toStringRef(NameSV);
113 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
115 MCSymbol *&Sym = Symbols[NameRef];
117 Sym = CreateSymbol(NameRef, false);
122 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
123 MCSymbol *&Sym = SectionSymbols[&Section];
127 StringRef Name = Section.getSectionName();
129 MCSymbol *&OldSym = Symbols[Name];
130 if (OldSym && OldSym->isUndefined()) {
135 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
136 Sym = new (*this) MCSymbol(&*NameIter, /*isTemporary*/ false);
144 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
146 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
147 "$frame_escape_" + Twine(Idx));
150 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
151 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
152 "$parent_frame_offset");
155 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
156 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
160 MCSymbol *MCContext::CreateSymbol(StringRef Name, bool AlwaysAddSuffix) {
161 // Determine whether this is an assembler temporary or normal label, if used.
162 bool IsTemporary = false;
163 if (AllowTemporaryLabels)
164 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
166 if (IsTemporary && AlwaysAddSuffix && !UseNamesOnTempLabels)
167 return new (*this) MCSymbol(nullptr, true);
169 SmallString<128> NewName = Name;
170 bool AddSuffix = AlwaysAddSuffix;
171 unsigned &NextUniqueID = NextID[Name];
174 NewName.resize(Name.size());
175 raw_svector_ostream(NewName) << NextUniqueID++;
177 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
178 if (NameEntry.second) {
179 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
180 // of the string that is embedded in the UsedNames entry.
181 MCSymbol *Result = new (*this) MCSymbol(&*NameEntry.first, IsTemporary);
184 assert(IsTemporary && "Cannot rename non-temporary symbols");
187 llvm_unreachable("Infinite loop");
190 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
191 SmallString<128> NameSV;
192 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
193 return CreateSymbol(NameSV, AlwaysAddSuffix);
196 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
197 SmallString<128> NameSV;
198 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
199 return CreateSymbol(NameSV, true);
202 MCSymbol *MCContext::createTempSymbol() {
203 return createTempSymbol("tmp", true);
206 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
207 MCLabel *&Label = Instances[LocalLabelVal];
209 Label = new (*this) MCLabel(0);
210 return Label->incInstance();
213 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
214 MCLabel *&Label = Instances[LocalLabelVal];
216 Label = new (*this) MCLabel(0);
217 return Label->getInstance();
220 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
222 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
224 Sym = createTempSymbol();
228 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
229 unsigned Instance = NextInstance(LocalLabelVal);
230 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
233 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
235 unsigned Instance = GetInstance(LocalLabelVal);
238 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
241 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
242 SmallString<128> NameSV;
243 StringRef NameRef = Name.toStringRef(NameSV);
244 return Symbols.lookup(NameRef);
247 //===----------------------------------------------------------------------===//
248 // Section Management
249 //===----------------------------------------------------------------------===//
251 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
252 unsigned TypeAndAttributes,
253 unsigned Reserved2, SectionKind Kind,
254 const char *BeginSymName) {
256 // We unique sections by their segment/section pair. The returned section
257 // may not have the same flags as the requested section, if so this should be
258 // diagnosed by the client as an error.
260 // Form the name to look up.
261 SmallString<64> Name;
266 // Do the lookup, if we have a hit, return it.
267 MCSectionMachO *&Entry = MachOUniquingMap[Name];
271 MCSymbol *Begin = nullptr;
273 Begin = createTempSymbol(BeginSymName, false);
275 // Otherwise, return a new section.
276 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
277 Reserved2, Kind, Begin);
280 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
282 if (const MCSymbol *Group = Section->getGroup())
283 GroupName = Group->getName();
285 unsigned UniqueID = Section->getUniqueID();
286 ELFUniquingMap.erase(
287 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
288 auto I = ELFUniquingMap.insert(std::make_pair(
289 ELFSectionKey{Name, GroupName, UniqueID},
292 StringRef CachedName = I->first.SectionName;
293 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
296 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
297 unsigned Flags, unsigned EntrySize,
298 const MCSymbol *Group,
299 const MCSectionELF *Associated) {
300 StringMap<bool>::iterator I;
302 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
305 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
306 EntrySize, Group, true, nullptr, Associated);
309 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
310 unsigned Flags, unsigned EntrySize,
311 StringRef Group, unsigned UniqueID,
312 const char *BeginSymName) {
313 MCSymbol *GroupSym = nullptr;
315 GroupSym = getOrCreateSymbol(Group);
317 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
318 BeginSymName, nullptr);
321 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
322 unsigned Flags, unsigned EntrySize,
323 const MCSymbol *GroupSym,
325 const char *BeginSymName,
326 const MCSectionELF *Associated) {
327 StringRef Group = "";
329 Group = GroupSym->getName();
330 // Do the lookup, if we have a hit, return it.
331 auto IterBool = ELFUniquingMap.insert(
332 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
333 auto &Entry = *IterBool.first;
334 if (!IterBool.second)
337 StringRef CachedName = Entry.first.SectionName;
340 if (Flags & ELF::SHF_EXECINSTR)
341 Kind = SectionKind::getText();
343 Kind = SectionKind::getReadOnly();
345 MCSymbol *Begin = nullptr;
347 Begin = createTempSymbol(BeginSymName, false);
349 MCSectionELF *Result =
350 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
351 GroupSym, UniqueID, Begin, Associated);
352 Entry.second = Result;
356 MCSectionELF *MCContext::createELFGroupSection(const MCSymbol *Group) {
357 MCSectionELF *Result = new (*this)
358 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
359 Group, ~0, nullptr, nullptr);
363 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
364 unsigned Characteristics,
366 StringRef COMDATSymName, int Selection,
367 const char *BeginSymName) {
368 MCSymbol *COMDATSymbol = nullptr;
369 if (!COMDATSymName.empty()) {
370 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
371 COMDATSymName = COMDATSymbol->getName();
374 // Do the lookup, if we have a hit, return it.
375 COFFSectionKey T{Section, COMDATSymName, Selection};
376 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
377 auto Iter = IterBool.first;
378 if (!IterBool.second)
381 MCSymbol *Begin = nullptr;
383 Begin = createTempSymbol(BeginSymName, false);
385 StringRef CachedName = Iter->first.SectionName;
386 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
387 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
389 Iter->second = Result;
393 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
394 unsigned Characteristics,
396 const char *BeginSymName) {
397 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
400 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
401 COFFSectionKey T{Section, "", 0};
402 auto Iter = COFFUniquingMap.find(T);
403 if (Iter == COFFUniquingMap.end())
408 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
409 const MCSymbol *KeySym) {
410 // Return the normal section if we don't have to be associative.
414 // Make an associative section with the same name and kind as the normal
416 unsigned Characteristics =
417 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
418 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
420 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
423 //===----------------------------------------------------------------------===//
425 //===----------------------------------------------------------------------===//
427 /// getDwarfFile - takes a file name an number to place in the dwarf file and
428 /// directory tables. If the file number has already been allocated it is an
429 /// error and zero is returned and the client reports the error, else the
430 /// allocated file number is returned. The file numbers may be in any order.
431 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
432 unsigned FileNumber, unsigned CUID) {
433 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
434 return Table.getFile(Directory, FileName, FileNumber);
437 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
438 /// currently is assigned and false otherwise.
439 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
440 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
441 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
444 return !MCDwarfFiles[FileNumber].Name.empty();
447 /// Remove empty sections from SectionStartEndSyms, to avoid generating
448 /// useless debug info for them.
449 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
450 std::vector<MCSection *> Keep;
451 for (MCSection *Sec : SectionsForRanges) {
452 if (MCOS.mayHaveInstructions(*Sec))
455 SectionsForRanges.clear();
456 SectionsForRanges.insert(Keep.begin(), Keep.end());
459 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
460 // If we have a source manager and a location, use it. Otherwise just
461 // use the generic report_fatal_error().
462 if (!SrcMgr || Loc == SMLoc())
463 report_fatal_error(Msg, false);
465 // Use the source manager to print the message.
466 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
468 // If we reached here, we are failing ungracefully. Run the interrupt handlers
469 // to make sure any special cleanups get done, in particular that we remove
470 // files registered with RemoveFileOnSignal.
471 sys::RunInterruptHandlers();