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/MemoryBuffer.h"
25 #include "llvm/Support/PathV1.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/SourceMgr.h"
30 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
31 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
32 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
35 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
36 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
38 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
39 Allocator(), Symbols(Allocator), UsedNames(Allocator),
41 CompilationDir(llvm::sys::Path::GetCurrentDirectory().str()),
42 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
43 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
44 AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
50 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
52 SecureLogUsed = false;
54 if (SrcMgr && SrcMgr->getNumBuffers() > 0)
55 MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
60 MCContext::~MCContext() {
65 // NOTE: The symbols are all allocated out of a bump pointer allocator,
66 // we don't need to free them here.
68 // If the stream for the .secure_log_unique directive was created free it.
69 delete (raw_ostream*)SecureLog;
72 //===----------------------------------------------------------------------===//
73 // Module Lifetime Management
74 //===----------------------------------------------------------------------===//
76 void MCContext::reset() {
81 MCDwarfFilesCUMap.clear();
82 MCDwarfDirsCUMap.clear();
83 MCGenDwarfLabelEntries.clear();
84 DwarfDebugFlags = StringRef();
85 MCLineSections.clear();
86 MCLineSectionOrder.clear();
87 DwarfCompileUnitID = 0;
88 MCLineTableSymbols.clear();
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 Name.toVector(NameSV);
154 return GetOrCreateSymbol(NameSV.str());
157 MCSymbol *MCContext::CreateTempSymbol() {
158 SmallString<128> NameSV;
159 raw_svector_ostream(NameSV)
160 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
161 return CreateSymbol(NameSV);
164 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
165 MCLabel *&Label = Instances[LocalLabelVal];
167 Label = new (*this) MCLabel(0);
168 return Label->incInstance();
171 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
172 MCLabel *&Label = Instances[LocalLabelVal];
174 Label = new (*this) MCLabel(0);
175 return Label->getInstance();
178 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
179 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
180 Twine(LocalLabelVal) +
182 Twine(NextInstance(LocalLabelVal)));
184 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
186 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
187 Twine(LocalLabelVal) +
189 Twine(GetInstance(LocalLabelVal) + bORf));
192 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
193 return Symbols.lookup(Name);
196 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
197 SmallString<128> NameSV;
198 Name.toVector(NameSV);
199 return LookupSymbol(NameSV.str());
202 //===----------------------------------------------------------------------===//
203 // Section Management
204 //===----------------------------------------------------------------------===//
206 const MCSectionMachO *MCContext::
207 getMachOSection(StringRef Segment, StringRef Section,
208 unsigned TypeAndAttributes,
209 unsigned Reserved2, SectionKind Kind) {
211 // We unique sections by their segment/section pair. The returned section
212 // may not have the same flags as the requested section, if so this should be
213 // diagnosed by the client as an error.
215 // Create the map if it doesn't already exist.
216 if (MachOUniquingMap == 0)
217 MachOUniquingMap = new MachOUniqueMapTy();
218 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
220 // Form the name to look up.
221 SmallString<64> Name;
226 // Do the lookup, if we have a hit, return it.
227 const MCSectionMachO *&Entry = Map[Name.str()];
228 if (Entry) return Entry;
230 // Otherwise, return a new section.
231 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
235 const MCSectionELF *MCContext::
236 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
238 return getELFSection(Section, Type, Flags, Kind, 0, "");
241 const MCSectionELF *MCContext::
242 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
243 SectionKind Kind, unsigned EntrySize, StringRef Group) {
244 if (ELFUniquingMap == 0)
245 ELFUniquingMap = new ELFUniqueMapTy();
246 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
248 // Do the lookup, if we have a hit, return it.
249 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
250 if (Entry.getValue()) return Entry.getValue();
252 // Possibly refine the entry size first.
254 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
257 MCSymbol *GroupSym = NULL;
259 GroupSym = GetOrCreateSymbol(Group);
261 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
262 Kind, EntrySize, GroupSym);
263 Entry.setValue(Result);
267 const MCSectionELF *MCContext::CreateELFGroupSection() {
268 MCSectionELF *Result =
269 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
270 SectionKind::getReadOnly(), 4, NULL);
274 const MCSection *MCContext::getCOFFSection(StringRef Section,
275 unsigned Characteristics,
278 if (COFFUniquingMap == 0)
279 COFFUniquingMap = new COFFUniqueMapTy();
280 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
282 // Do the lookup, if we have a hit, return it.
283 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
284 if (Entry.getValue()) return Entry.getValue();
286 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
290 Entry.setValue(Result);
294 //===----------------------------------------------------------------------===//
296 //===----------------------------------------------------------------------===//
298 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
299 /// directory tables. If the file number has already been allocated it is an
300 /// error and zero is returned and the client reports the error, else the
301 /// allocated file number is returned. The file numbers may be in any order.
302 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
303 unsigned FileNumber, unsigned CUID) {
304 // TODO: a FileNumber of zero says to use the next available file number.
305 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
306 // to not be less than one. This needs to be change to be not less than zero.
308 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
309 SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
310 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
311 if (FileNumber >= MCDwarfFiles.size()) {
312 MCDwarfFiles.resize(FileNumber + 1);
314 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
316 // It is an error to use see the same number more than once.
320 // Get the new MCDwarfFile slot for this FileNumber.
321 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
323 if (Directory.empty()) {
324 // Separate the directory part from the basename of the FileName.
325 StringRef tFileName = sys::path::filename(FileName);
326 if (!tFileName.empty()) {
327 Directory = sys::path::parent_path(FileName);
328 if (!Directory.empty())
329 FileName = tFileName;
333 // Find or make a entry in the MCDwarfDirs vector for this Directory.
334 // Capture directory name.
336 if (Directory.empty()) {
337 // For FileNames with no directories a DirIndex of 0 is used.
341 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
342 if (Directory == MCDwarfDirs[DirIndex])
345 if (DirIndex >= MCDwarfDirs.size()) {
346 char *Buf = static_cast<char *>(Allocate(Directory.size()));
347 memcpy(Buf, Directory.data(), Directory.size());
348 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
350 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
351 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
352 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
353 // are stored at MCDwarfFiles[FileNumber].Name .
357 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
359 char *Buf = static_cast<char *>(Allocate(FileName.size()));
360 memcpy(Buf, FileName.data(), FileName.size());
361 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
363 // return the allocated FileNumber.
367 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
368 /// currently is assigned and false otherwise.
369 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
370 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
371 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
374 return MCDwarfFiles[FileNumber] != 0;
377 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
378 // If we have a source manager and a location, use it. Otherwise just
379 // use the generic report_fatal_error().
380 if (!SrcMgr || Loc == SMLoc())
381 report_fatal_error(Msg);
383 // Use the source manager to print the message.
384 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
386 // If we reached here, we are failing ungracefully. Run the interrupt handlers
387 // to make sure any special cleanups get done, in particular that we remove
388 // files registered with RemoveFileOnSignal.
389 sys::RunInterruptHandlers();