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),
42 Allocator(), Symbols(Allocator), UsedNames(Allocator),
44 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
45 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
46 AllowTemporaryLabels(true), DwarfCompileUnitID(0), 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();
66 MCContext::~MCContext() {
71 // NOTE: The symbols are all allocated out of a bump pointer allocator,
72 // we don't need to free them here.
74 // If the stream for the .secure_log_unique directive was created free it.
75 delete (raw_ostream*)SecureLog;
78 //===----------------------------------------------------------------------===//
79 // Module Lifetime Management
80 //===----------------------------------------------------------------------===//
82 void MCContext::reset() {
87 MCDwarfFilesCUMap.clear();
88 MCDwarfDirsCUMap.clear();
89 MCGenDwarfLabelEntries.clear();
90 DwarfDebugFlags = StringRef();
91 MCLineSections.clear();
92 MCLineSectionOrder.clear();
93 DwarfCompileUnitID = 0;
94 MCLineTableSymbols.clear();
95 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
97 // If we have the MachO uniquing map, free it.
98 delete (MachOUniqueMapTy*)MachOUniquingMap;
99 delete (ELFUniqueMapTy*)ELFUniquingMap;
100 delete (COFFUniqueMapTy*)COFFUniquingMap;
101 MachOUniquingMap = 0;
106 AllowTemporaryLabels = true;
107 DwarfLocSeen = false;
108 GenDwarfForAssembly = false;
109 GenDwarfFileNumber = 0;
112 //===----------------------------------------------------------------------===//
113 // Symbol Manipulation
114 //===----------------------------------------------------------------------===//
116 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
117 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
119 // Do the lookup and get the entire StringMapEntry. We want access to the
120 // key if we are creating the entry.
121 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
122 MCSymbol *Sym = Entry.getValue();
127 Sym = CreateSymbol(Name);
132 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
133 // Determine whether this is an assembler temporary or normal label, if used.
134 bool isTemporary = false;
135 if (AllowTemporaryLabels)
136 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
138 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
139 if (NameEntry->getValue()) {
140 assert(isTemporary && "Cannot rename non-temporary symbols");
141 SmallString<128> NewName = Name;
143 NewName.resize(Name.size());
144 raw_svector_ostream(NewName) << NextUniqueID++;
145 NameEntry = &UsedNames.GetOrCreateValue(NewName);
146 } while (NameEntry->getValue());
148 NameEntry->setValue(true);
150 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
151 // to the copy of the string that is embedded in the UsedNames entry.
152 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
157 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
158 SmallString<128> NameSV;
159 return GetOrCreateSymbol(Name.toStringRef(NameSV));
162 MCSymbol *MCContext::CreateTempSymbol() {
163 SmallString<128> NameSV;
164 raw_svector_ostream(NameSV)
165 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
166 return CreateSymbol(NameSV);
169 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
170 MCLabel *&Label = Instances[LocalLabelVal];
172 Label = new (*this) MCLabel(0);
173 return Label->incInstance();
176 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
177 MCLabel *&Label = Instances[LocalLabelVal];
179 Label = new (*this) MCLabel(0);
180 return Label->getInstance();
183 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
184 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
185 Twine(LocalLabelVal) +
187 Twine(NextInstance(LocalLabelVal)));
189 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
191 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
192 Twine(LocalLabelVal) +
194 Twine(GetInstance(LocalLabelVal) + bORf));
197 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
198 return Symbols.lookup(Name);
201 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
202 SmallString<128> NameSV;
203 Name.toVector(NameSV);
204 return LookupSymbol(NameSV.str());
207 //===----------------------------------------------------------------------===//
208 // Section Management
209 //===----------------------------------------------------------------------===//
211 const MCSectionMachO *MCContext::
212 getMachOSection(StringRef Segment, StringRef Section,
213 unsigned TypeAndAttributes,
214 unsigned Reserved2, SectionKind Kind) {
216 // We unique sections by their segment/section pair. The returned section
217 // may not have the same flags as the requested section, if so this should be
218 // diagnosed by the client as an error.
220 // Create the map if it doesn't already exist.
221 if (MachOUniquingMap == 0)
222 MachOUniquingMap = new MachOUniqueMapTy();
223 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
225 // Form the name to look up.
226 SmallString<64> Name;
231 // Do the lookup, if we have a hit, return it.
232 const MCSectionMachO *&Entry = Map[Name.str()];
233 if (Entry) return Entry;
235 // Otherwise, return a new section.
236 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
240 const MCSectionELF *MCContext::
241 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
243 return getELFSection(Section, Type, Flags, Kind, 0, "");
246 const MCSectionELF *MCContext::
247 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
248 SectionKind Kind, unsigned EntrySize, StringRef Group) {
249 if (ELFUniquingMap == 0)
250 ELFUniquingMap = new ELFUniqueMapTy();
251 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
253 // Do the lookup, if we have a hit, return it.
254 std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert(
255 std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0));
256 if (!Entry.second) return Entry.first->second;
258 // Possibly refine the entry size first.
260 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
263 MCSymbol *GroupSym = NULL;
265 GroupSym = GetOrCreateSymbol(Group);
267 MCSectionELF *Result = new (*this) MCSectionELF(
268 Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym);
269 Entry.first->second = Result;
273 const MCSectionELF *MCContext::CreateELFGroupSection() {
274 MCSectionELF *Result =
275 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
276 SectionKind::getReadOnly(), 4, NULL);
280 const MCSectionCOFF *
281 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
282 SectionKind Kind, StringRef COMDATSymName,
283 int Selection, const MCSectionCOFF *Assoc) {
284 if (COFFUniquingMap == 0)
285 COFFUniquingMap = new COFFUniqueMapTy();
286 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
288 // Do the lookup, if we have a hit, return it.
290 SectionGroupPair P(Section, COMDATSymName);
291 std::pair<COFFUniqueMapTy::iterator, bool> Entry =
292 Map.insert(std::make_pair(P, (MCSectionCOFF *)0));
293 COFFUniqueMapTy::iterator Iter = Entry.first;
297 const MCSymbol *COMDATSymbol = NULL;
298 if (!COMDATSymName.empty())
299 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
301 MCSectionCOFF *Result =
302 new (*this) MCSectionCOFF(Iter->first.first, Characteristics,
303 COMDATSymbol, Selection, Assoc, Kind);
305 Iter->second = Result;
309 const MCSectionCOFF *
310 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
312 return getCOFFSection(Section, Characteristics, Kind, "", 0);
315 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
316 if (COFFUniquingMap == 0)
317 COFFUniquingMap = new COFFUniqueMapTy();
318 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
320 SectionGroupPair P(Section, "");
321 COFFUniqueMapTy::iterator Iter = Map.find(P);
322 if (Iter == Map.end())
327 //===----------------------------------------------------------------------===//
329 //===----------------------------------------------------------------------===//
331 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
332 /// directory tables. If the file number has already been allocated it is an
333 /// error and zero is returned and the client reports the error, else the
334 /// allocated file number is returned. The file numbers may be in any order.
335 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
336 unsigned FileNumber, unsigned CUID) {
337 // TODO: a FileNumber of zero says to use the next available file number.
338 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
339 // to not be less than one. This needs to be change to be not less than zero.
341 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
342 SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
343 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
344 if (FileNumber >= MCDwarfFiles.size()) {
345 MCDwarfFiles.resize(FileNumber + 1);
347 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
349 // It is an error to use see the same number more than once.
353 // Get the new MCDwarfFile slot for this FileNumber.
354 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
356 if (Directory.empty()) {
357 // Separate the directory part from the basename of the FileName.
358 StringRef tFileName = sys::path::filename(FileName);
359 if (!tFileName.empty()) {
360 Directory = sys::path::parent_path(FileName);
361 if (!Directory.empty())
362 FileName = tFileName;
366 // Find or make a entry in the MCDwarfDirs vector for this Directory.
367 // Capture directory name.
369 if (Directory.empty()) {
370 // For FileNames with no directories a DirIndex of 0 is used.
374 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
375 if (Directory == MCDwarfDirs[DirIndex])
378 if (DirIndex >= MCDwarfDirs.size()) {
379 char *Buf = static_cast<char *>(Allocate(Directory.size()));
380 memcpy(Buf, Directory.data(), Directory.size());
381 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
383 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
384 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
385 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
386 // are stored at MCDwarfFiles[FileNumber].Name .
390 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
392 char *Buf = static_cast<char *>(Allocate(FileName.size()));
393 memcpy(Buf, FileName.data(), FileName.size());
394 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
396 // return the allocated FileNumber.
400 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
401 /// currently is assigned and false otherwise.
402 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
403 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
404 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
407 return MCDwarfFiles[FileNumber] != 0;
410 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
411 // If we have a source manager and a location, use it. Otherwise just
412 // use the generic report_fatal_error().
413 if (!SrcMgr || Loc == SMLoc())
414 report_fatal_error(Msg);
416 // Use the source manager to print the message.
417 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
419 // If we reached here, we are failing ungracefully. Run the interrupt handlers
420 // to make sure any special cleanups get done, in particular that we remove
421 // files registered with RemoveFileOnSignal.
422 sys::RunInterruptHandlers();