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 typedef std::pair<std::string, std::string> SectionGroupPair;
34 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
35 typedef std::map<SectionGroupPair, const MCSectionELF *> ELFUniqueMapTy;
36 typedef std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniqueMapTy;
38 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
39 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
41 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
42 Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
43 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
44 GenDwarfForAssembly(false), GenDwarfFileNumber(0),
45 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
46 AutoReset(DoAutoReset) {
48 error_code EC = llvm::sys::fs::current_path(CompilationDir);
50 CompilationDir.clear();
56 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
58 SecureLogUsed = false;
60 if (SrcMgr && SrcMgr->getNumBuffers() > 0)
61 MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
64 MCContext::~MCContext() {
69 // NOTE: The symbols are all allocated out of a bump pointer allocator,
70 // we don't need to free them here.
72 // If the stream for the .secure_log_unique directive was created free it.
73 delete (raw_ostream*)SecureLog;
76 //===----------------------------------------------------------------------===//
77 // Module Lifetime Management
78 //===----------------------------------------------------------------------===//
80 void MCContext::reset() {
85 MCDwarfLineTablesCUMap.clear();
86 MCGenDwarfLabelEntries.clear();
87 DwarfDebugFlags = StringRef();
88 DwarfCompileUnitID = 0;
89 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
91 // If we have the MachO uniquing map, free it.
92 delete (MachOUniqueMapTy*)MachOUniquingMap;
93 delete (ELFUniqueMapTy*)ELFUniquingMap;
94 delete (COFFUniqueMapTy*)COFFUniquingMap;
100 AllowTemporaryLabels = true;
101 DwarfLocSeen = false;
102 GenDwarfForAssembly = false;
103 GenDwarfFileNumber = 0;
106 //===----------------------------------------------------------------------===//
107 // Symbol Manipulation
108 //===----------------------------------------------------------------------===//
110 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
111 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
113 // Do the lookup and get the entire StringMapEntry. We want access to the
114 // key if we are creating the entry.
115 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
116 MCSymbol *Sym = Entry.getValue();
121 Sym = CreateSymbol(Name);
126 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
127 // Determine whether this is an assembler temporary or normal label, if used.
128 bool isTemporary = false;
129 if (AllowTemporaryLabels)
130 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
132 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
133 if (NameEntry->getValue()) {
134 assert(isTemporary && "Cannot rename non-temporary symbols");
135 SmallString<128> NewName = Name;
137 NewName.resize(Name.size());
138 raw_svector_ostream(NewName) << NextUniqueID++;
139 NameEntry = &UsedNames.GetOrCreateValue(NewName);
140 } while (NameEntry->getValue());
142 NameEntry->setValue(true);
144 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
145 // to the copy of the string that is embedded in the UsedNames entry.
146 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
151 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
152 SmallString<128> NameSV;
153 return GetOrCreateSymbol(Name.toStringRef(NameSV));
156 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
157 SmallString<128> NameSV;
158 raw_svector_ostream(NameSV)
159 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
160 return CreateSymbol(NameSV);
163 MCSymbol *MCContext::CreateTempSymbol() {
164 SmallString<128> NameSV;
165 raw_svector_ostream(NameSV)
166 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
167 return CreateSymbol(NameSV);
170 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
171 MCLabel *&Label = Instances[LocalLabelVal];
173 Label = new (*this) MCLabel(0);
174 return Label->incInstance();
177 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
178 MCLabel *&Label = Instances[LocalLabelVal];
180 Label = new (*this) MCLabel(0);
181 return Label->getInstance();
184 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
186 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
188 Sym = CreateTempSymbol();
192 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
193 unsigned Instance = NextInstance(LocalLabelVal);
194 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
197 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
199 unsigned Instance = GetInstance(LocalLabelVal);
202 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
205 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
206 return Symbols.lookup(Name);
209 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
210 SmallString<128> NameSV;
211 Name.toVector(NameSV);
212 return LookupSymbol(NameSV.str());
215 //===----------------------------------------------------------------------===//
216 // Section Management
217 //===----------------------------------------------------------------------===//
219 const MCSectionMachO *MCContext::
220 getMachOSection(StringRef Segment, StringRef Section,
221 unsigned TypeAndAttributes,
222 unsigned Reserved2, SectionKind Kind) {
224 // We unique sections by their segment/section pair. The returned section
225 // may not have the same flags as the requested section, if so this should be
226 // diagnosed by the client as an error.
228 // Create the map if it doesn't already exist.
229 if (MachOUniquingMap == 0)
230 MachOUniquingMap = new MachOUniqueMapTy();
231 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
233 // Form the name to look up.
234 SmallString<64> Name;
239 // Do the lookup, if we have a hit, return it.
240 const MCSectionMachO *&Entry = Map[Name.str()];
241 if (Entry) return Entry;
243 // Otherwise, return a new section.
244 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
248 const MCSectionELF *MCContext::
249 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
251 return getELFSection(Section, Type, Flags, Kind, 0, "");
254 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
255 if (ELFUniquingMap == 0)
256 ELFUniquingMap = new ELFUniqueMapTy();
257 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
260 if (const MCSymbol *Group = Section->getGroup())
261 GroupName = Group->getName();
263 Map.erase(SectionGroupPair(Section->getSectionName(), GroupName));
264 auto I = Map.insert(std::make_pair(SectionGroupPair(Name, GroupName),
266 const_cast<MCSectionELF*>(Section)->setSectionName(I->first.first);
269 const MCSectionELF *MCContext::
270 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
271 SectionKind Kind, unsigned EntrySize, StringRef Group) {
272 if (ELFUniquingMap == 0)
273 ELFUniquingMap = new ELFUniqueMapTy();
274 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
276 // Do the lookup, if we have a hit, return it.
277 std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert(
278 std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0));
279 if (!Entry.second) return Entry.first->second;
281 // Possibly refine the entry size first.
283 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
286 MCSymbol *GroupSym = NULL;
288 GroupSym = GetOrCreateSymbol(Group);
290 MCSectionELF *Result = new (*this) MCSectionELF(
291 Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym);
292 Entry.first->second = Result;
296 const MCSectionELF *MCContext::CreateELFGroupSection() {
297 MCSectionELF *Result =
298 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
299 SectionKind::getReadOnly(), 4, NULL);
303 const MCSectionCOFF *
304 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
305 SectionKind Kind, StringRef COMDATSymName,
306 int Selection, const MCSectionCOFF *Assoc) {
307 if (COFFUniquingMap == 0)
308 COFFUniquingMap = new COFFUniqueMapTy();
309 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
311 // Do the lookup, if we have a hit, return it.
313 SectionGroupPair P(Section, COMDATSymName);
314 std::pair<COFFUniqueMapTy::iterator, bool> Entry =
315 Map.insert(std::make_pair(P, (MCSectionCOFF *)0));
316 COFFUniqueMapTy::iterator Iter = Entry.first;
320 const MCSymbol *COMDATSymbol = NULL;
321 if (!COMDATSymName.empty())
322 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
324 MCSectionCOFF *Result =
325 new (*this) MCSectionCOFF(Iter->first.first, Characteristics,
326 COMDATSymbol, Selection, Assoc, 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 if (COFFUniquingMap == 0)
340 COFFUniquingMap = new COFFUniqueMapTy();
341 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
343 SectionGroupPair P(Section, "");
344 COFFUniqueMapTy::iterator Iter = Map.find(P);
345 if (Iter == Map.end())
350 //===----------------------------------------------------------------------===//
352 //===----------------------------------------------------------------------===//
354 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
355 /// directory tables. If the file number has already been allocated it is an
356 /// error and zero is returned and the client reports the error, else the
357 /// allocated file number is returned. The file numbers may be in any order.
358 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
359 unsigned FileNumber, unsigned CUID) {
360 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
361 return Table.getFile(Directory, FileName, FileNumber);
364 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
365 /// currently is assigned and false otherwise.
366 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
367 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
368 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
371 return !MCDwarfFiles[FileNumber].Name.empty();
374 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
375 // If we have a source manager and a location, use it. Otherwise just
376 // use the generic report_fatal_error().
377 if (!SrcMgr || Loc == SMLoc())
378 report_fatal_error(Msg, false);
380 // Use the source manager to print the message.
381 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
383 // If we reached here, we are failing ungracefully. Run the interrupt handlers
384 // to make sure any special cleanups get done, in particular that we remove
385 // files registered with RemoveFileOnSignal.
386 sys::RunInterruptHandlers();