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 // Do the lookup and get the entire StringMapEntry. We want access to the
104 // key if we are creating the entry.
105 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
106 MCSymbol *Sym = Entry.getValue();
111 Sym = CreateSymbol(Name);
116 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
117 MCSymbol *&Sym = SectionSymbols[&Section];
121 StringRef Name = Section.getSectionName();
122 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
123 NameEntry->setValue(true);
124 Sym = new (*this) MCSymbol(NameEntry->getKey(), /*isTemporary*/ false);
126 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
127 if (!Entry.getValue())
133 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
134 // Determine whether this is an assembler temporary or normal label, if used.
135 bool isTemporary = false;
136 if (AllowTemporaryLabels)
137 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
139 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
140 if (NameEntry->getValue()) {
141 assert(isTemporary && "Cannot rename non-temporary symbols");
142 SmallString<128> NewName = Name;
144 NewName.resize(Name.size());
145 raw_svector_ostream(NewName) << NextUniqueID++;
146 NameEntry = &UsedNames.GetOrCreateValue(NewName);
147 } while (NameEntry->getValue());
149 NameEntry->setValue(true);
151 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
152 // to the copy of the string that is embedded in the UsedNames entry.
153 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
158 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
159 SmallString<128> NameSV;
160 return GetOrCreateSymbol(Name.toStringRef(NameSV));
163 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
164 SmallString<128> NameSV;
165 raw_svector_ostream(NameSV)
166 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
167 return CreateSymbol(NameSV);
170 MCSymbol *MCContext::CreateTempSymbol() {
171 SmallString<128> NameSV;
172 raw_svector_ostream(NameSV)
173 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
174 return CreateSymbol(NameSV);
177 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
178 MCLabel *&Label = Instances[LocalLabelVal];
180 Label = new (*this) MCLabel(0);
181 return Label->incInstance();
184 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
185 MCLabel *&Label = Instances[LocalLabelVal];
187 Label = new (*this) MCLabel(0);
188 return Label->getInstance();
191 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
193 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
195 Sym = CreateTempSymbol();
199 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
200 unsigned Instance = NextInstance(LocalLabelVal);
201 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
204 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
206 unsigned Instance = GetInstance(LocalLabelVal);
209 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
212 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
213 return Symbols.lookup(Name);
216 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
217 SmallString<128> NameSV;
218 Name.toVector(NameSV);
219 return LookupSymbol(NameSV.str());
222 //===----------------------------------------------------------------------===//
223 // Section Management
224 //===----------------------------------------------------------------------===//
226 const MCSectionMachO *MCContext::
227 getMachOSection(StringRef Segment, StringRef Section,
228 unsigned TypeAndAttributes,
229 unsigned Reserved2, SectionKind Kind) {
231 // We unique sections by their segment/section pair. The returned section
232 // may not have the same flags as the requested section, if so this should be
233 // diagnosed by the client as an error.
235 // Form the name to look up.
236 SmallString<64> Name;
241 // Do the lookup, if we have a hit, return it.
242 const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
243 if (Entry) return Entry;
245 // Otherwise, return a new section.
246 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
250 const MCSectionELF *MCContext::
251 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
253 return getELFSection(Section, Type, Flags, Kind, 0, "");
256 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
258 if (const MCSymbol *Group = Section->getGroup())
259 GroupName = Group->getName();
261 ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
263 ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
265 StringRef CachedName = I->first.first;
266 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
269 const MCSectionELF *MCContext::
270 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
271 SectionKind Kind, unsigned EntrySize, StringRef Group) {
272 // Do the lookup, if we have a hit, return it.
273 auto IterBool = ELFUniquingMap.insert(
274 std::make_pair(SectionGroupPair(Section, Group), nullptr));
275 auto &Entry = *IterBool.first;
276 if (!IterBool.second) return Entry.second;
278 // Possibly refine the entry size first.
280 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
283 MCSymbol *GroupSym = nullptr;
285 GroupSym = GetOrCreateSymbol(Group);
287 StringRef CachedName = Entry.first.first;
288 MCSectionELF *Result = new (*this)
289 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym);
290 Entry.second = Result;
294 const MCSectionELF *MCContext::CreateELFGroupSection() {
295 MCSectionELF *Result =
296 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
297 SectionKind::getReadOnly(), 4, nullptr);
301 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
302 unsigned Characteristics,
304 StringRef COMDATSymName,
306 // Do the lookup, if we have a hit, return it.
308 SectionGroupTriple T(Section, COMDATSymName, Selection);
309 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
310 auto Iter = IterBool.first;
311 if (!IterBool.second)
314 MCSymbol *COMDATSymbol = nullptr;
315 if (!COMDATSymName.empty())
316 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
318 StringRef CachedName = std::get<0>(Iter->first);
319 MCSectionCOFF *Result = new (*this)
320 MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
322 Iter->second = Result;
326 const MCSectionCOFF *
327 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
329 return getCOFFSection(Section, Characteristics, Kind, "", 0);
332 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
333 SectionGroupTriple T(Section, "", 0);
334 auto Iter = COFFUniquingMap.find(T);
335 if (Iter == COFFUniquingMap.end())
340 const MCSectionCOFF *
341 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
342 const MCSymbol *KeySym) {
343 // Return the normal section if we don't have to be associative.
347 // Make an associative section with the same name and kind as the normal
349 unsigned Characteristics =
350 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
351 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
353 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
356 //===----------------------------------------------------------------------===//
358 //===----------------------------------------------------------------------===//
360 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
361 /// directory tables. If the file number has already been allocated it is an
362 /// error and zero is returned and the client reports the error, else the
363 /// allocated file number is returned. The file numbers may be in any order.
364 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
365 unsigned FileNumber, unsigned CUID) {
366 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
367 return Table.getFile(Directory, FileName, FileNumber);
370 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
371 /// currently is assigned and false otherwise.
372 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
373 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
374 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
377 return !MCDwarfFiles[FileNumber].Name.empty();
380 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
381 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
382 /// useless debug info for them.
383 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
384 MCContext &context = MCOS.getContext();
386 auto sec = SectionStartEndSyms.begin();
387 while (sec != SectionStartEndSyms.end()) {
388 assert(sec->second.first && "Start symbol must be set by now");
389 MCOS.SwitchSection(sec->first);
390 if (MCOS.mayHaveInstructions()) {
391 MCSymbol *SectionEndSym = context.CreateTempSymbol();
392 MCOS.EmitLabel(SectionEndSym);
393 sec->second.second = SectionEndSym;
396 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
398 sec = SectionStartEndSyms.erase(to_erase);
403 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
404 // If we have a source manager and a location, use it. Otherwise just
405 // use the generic report_fatal_error().
406 if (!SrcMgr || Loc == SMLoc())
407 report_fatal_error(Msg, false);
409 // Use the source manager to print the message.
410 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
412 // If we reached here, we are failing ungracefully. Run the interrupt handlers
413 // to make sure any special cleanups get done, in particular that we remove
414 // files registered with RemoveFileOnSignal.
415 sys::RunInterruptHandlers();