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/MCAsmInfo.h"
14 #include "llvm/MC/MCDwarf.h"
15 #include "llvm/MC/MCLabel.h"
16 #include "llvm/MC/MCObjectFileInfo.h"
17 #include "llvm/MC/MCRegisterInfo.h"
18 #include "llvm/MC/MCSectionCOFF.h"
19 #include "llvm/MC/MCSectionELF.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/SourceMgr.h"
32 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
33 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
35 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
36 Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
37 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
38 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
39 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
40 AutoReset(DoAutoReset) {
42 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
44 CompilationDir.clear();
46 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
48 SecureLogUsed = false;
50 if (SrcMgr && SrcMgr->getNumBuffers())
52 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
55 MCContext::~MCContext() {
60 // NOTE: The symbols are all allocated out of a bump pointer allocator,
61 // we don't need to free them here.
63 // If the stream for the .secure_log_unique directive was created free it.
64 delete (raw_ostream*)SecureLog;
67 //===----------------------------------------------------------------------===//
68 // Module Lifetime Management
69 //===----------------------------------------------------------------------===//
71 void MCContext::reset() {
76 CompilationDir.clear();
78 MCDwarfLineTablesCUMap.clear();
79 SectionStartEndSyms.clear();
80 MCGenDwarfLabelEntries.clear();
81 DwarfDebugFlags = StringRef();
82 DwarfCompileUnitID = 0;
83 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
85 MachOUniquingMap.clear();
86 ELFUniquingMap.clear();
87 COFFUniquingMap.clear();
90 AllowTemporaryLabels = true;
92 GenDwarfForAssembly = false;
93 GenDwarfFileNumber = 0;
96 //===----------------------------------------------------------------------===//
97 // Symbol Manipulation
98 //===----------------------------------------------------------------------===//
100 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
101 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
103 MCSymbol *&Sym = Symbols[Name];
106 Sym = CreateSymbol(Name);
111 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
112 MCSymbol *&Sym = SectionSymbols[&Section];
116 StringRef Name = Section.getSectionName();
118 MCSymbol *&OldSym = Symbols[Name];
119 if (OldSym && OldSym->isUndefined()) {
124 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
125 Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
133 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName) {
134 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
135 "frameallocation_" + FuncName);
138 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
139 // Determine whether this is an assembler temporary or normal label, if used.
140 bool isTemporary = false;
141 if (AllowTemporaryLabels)
142 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
144 auto NameEntry = UsedNames.insert(std::make_pair(Name, true));
145 if (!NameEntry.second) {
146 assert(isTemporary && "Cannot rename non-temporary symbols");
147 SmallString<128> NewName = Name;
149 NewName.resize(Name.size());
150 raw_svector_ostream(NewName) << NextUniqueID++;
151 NameEntry = UsedNames.insert(std::make_pair(NewName, true));
152 } while (!NameEntry.second);
155 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
156 // to the copy of the string that is embedded in the UsedNames entry.
158 new (*this) MCSymbol(NameEntry.first->getKey(), isTemporary);
163 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
164 SmallString<128> NameSV;
165 return GetOrCreateSymbol(Name.toStringRef(NameSV));
168 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
169 SmallString<128> NameSV;
170 raw_svector_ostream(NameSV)
171 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
172 return CreateSymbol(NameSV);
175 MCSymbol *MCContext::CreateTempSymbol() {
176 SmallString<128> NameSV;
177 raw_svector_ostream(NameSV)
178 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
179 return CreateSymbol(NameSV);
182 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
183 MCLabel *&Label = Instances[LocalLabelVal];
185 Label = new (*this) MCLabel(0);
186 return Label->incInstance();
189 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
190 MCLabel *&Label = Instances[LocalLabelVal];
192 Label = new (*this) MCLabel(0);
193 return Label->getInstance();
196 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
198 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
200 Sym = CreateTempSymbol();
204 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
205 unsigned Instance = NextInstance(LocalLabelVal);
206 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
209 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
211 unsigned Instance = GetInstance(LocalLabelVal);
214 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
217 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
218 return Symbols.lookup(Name);
221 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
222 SmallString<128> NameSV;
223 Name.toVector(NameSV);
224 return LookupSymbol(NameSV.str());
227 //===----------------------------------------------------------------------===//
228 // Section Management
229 //===----------------------------------------------------------------------===//
231 const MCSectionMachO *MCContext::
232 getMachOSection(StringRef Segment, StringRef Section,
233 unsigned TypeAndAttributes,
234 unsigned Reserved2, SectionKind Kind) {
236 // We unique sections by their segment/section pair. The returned section
237 // may not have the same flags as the requested section, if so this should be
238 // diagnosed by the client as an error.
240 // Form the name to look up.
241 SmallString<64> Name;
246 // Do the lookup, if we have a hit, return it.
247 const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
248 if (Entry) return Entry;
250 // Otherwise, return a new section.
251 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
255 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
257 return getELFSection(Section, Type, Flags, 0, "");
260 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
262 if (const MCSymbol *Group = Section->getGroup())
263 GroupName = Group->getName();
265 ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
267 ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
269 StringRef CachedName = I->first.first;
270 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
273 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
274 unsigned Flags, unsigned EntrySize,
276 // Do the lookup, if we have a hit, return it.
277 auto IterBool = ELFUniquingMap.insert(
278 std::make_pair(SectionGroupPair(Section, Group), nullptr));
279 auto &Entry = *IterBool.first;
280 if (!IterBool.second) return Entry.second;
282 MCSymbol *GroupSym = nullptr;
284 GroupSym = GetOrCreateSymbol(Group);
286 StringRef CachedName = Entry.first.first;
289 if (Flags & ELF::SHF_EXECINSTR)
290 Kind = SectionKind::getText();
292 Kind = SectionKind::getReadOnly();
294 MCSectionELF *Result = new (*this)
295 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym);
296 Entry.second = Result;
300 const MCSectionELF *MCContext::CreateELFGroupSection() {
301 MCSectionELF *Result =
302 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
303 SectionKind::getReadOnly(), 4, nullptr);
307 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
308 unsigned Characteristics,
310 StringRef COMDATSymName,
312 // Do the lookup, if we have a hit, return it.
314 SectionGroupTriple T(Section, COMDATSymName, Selection);
315 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
316 auto Iter = IterBool.first;
317 if (!IterBool.second)
320 MCSymbol *COMDATSymbol = nullptr;
321 if (!COMDATSymName.empty())
322 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
324 StringRef CachedName = std::get<0>(Iter->first);
325 MCSectionCOFF *Result = new (*this)
326 MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
328 Iter->second = Result;
332 const MCSectionCOFF *
333 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
335 return getCOFFSection(Section, Characteristics, Kind, "", 0);
338 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
339 SectionGroupTriple T(Section, "", 0);
340 auto Iter = COFFUniquingMap.find(T);
341 if (Iter == COFFUniquingMap.end())
346 const MCSectionCOFF *
347 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
348 const MCSymbol *KeySym) {
349 // Return the normal section if we don't have to be associative.
353 // Make an associative section with the same name and kind as the normal
355 unsigned Characteristics =
356 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
357 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
359 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
362 //===----------------------------------------------------------------------===//
364 //===----------------------------------------------------------------------===//
366 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
367 /// directory tables. If the file number has already been allocated it is an
368 /// error and zero is returned and the client reports the error, else the
369 /// allocated file number is returned. The file numbers may be in any order.
370 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
371 unsigned FileNumber, unsigned CUID) {
372 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
373 return Table.getFile(Directory, FileName, FileNumber);
376 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
377 /// currently is assigned and false otherwise.
378 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
379 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
380 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
383 return !MCDwarfFiles[FileNumber].Name.empty();
386 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
387 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
388 /// useless debug info for them.
389 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
390 MCContext &context = MCOS.getContext();
392 auto sec = SectionStartEndSyms.begin();
393 while (sec != SectionStartEndSyms.end()) {
394 assert(sec->second.first && "Start symbol must be set by now");
395 MCOS.SwitchSection(sec->first);
396 if (MCOS.mayHaveInstructions()) {
397 MCSymbol *SectionEndSym = context.CreateTempSymbol();
398 MCOS.EmitLabel(SectionEndSym);
399 sec->second.second = SectionEndSym;
402 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
404 sec = SectionStartEndSyms.erase(to_erase);
409 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
410 // If we have a source manager and a location, use it. Otherwise just
411 // use the generic report_fatal_error().
412 if (!SrcMgr || Loc == SMLoc())
413 report_fatal_error(Msg, false);
415 // Use the source manager to print the message.
416 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
418 // If we reached here, we are failing ungracefully. Run the interrupt handlers
419 // to make sure any special cleanups get done, in particular that we remove
420 // files registered with RemoveFileOnSignal.
421 sys::RunInterruptHandlers();