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/Signals.h"
25 #include "llvm/Support/SourceMgr.h"
28 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
29 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
30 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
33 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
34 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
36 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
37 Allocator(), Symbols(Allocator), UsedNames(Allocator),
39 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
40 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
41 AllowTemporaryLabels(true), AutoReset(DoAutoReset) {
47 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
49 SecureLogUsed = false;
52 MCContext::~MCContext() {
57 // NOTE: The symbols are all allocated out of a bump pointer allocator,
58 // we don't need to free them here.
60 // If the stream for the .secure_log_unique directive was created free it.
61 delete (raw_ostream*)SecureLog;
64 //===----------------------------------------------------------------------===//
65 // Module Lifetime Management
66 //===----------------------------------------------------------------------===//
68 void MCContext::reset() {
75 MCGenDwarfLabelEntries.clear();
76 DwarfDebugFlags = StringRef();
77 MCLineSections.clear();
78 MCLineSectionOrder.clear();
79 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
81 // If we have the MachO uniquing map, free it.
82 delete (MachOUniqueMapTy*)MachOUniquingMap;
83 delete (ELFUniqueMapTy*)ELFUniquingMap;
84 delete (COFFUniqueMapTy*)COFFUniquingMap;
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::CreateSymbol(StringRef Name) {
117 // Determine whether this is an assembler temporary or normal label, if used.
118 bool isTemporary = false;
119 if (AllowTemporaryLabels)
120 isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
122 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
123 if (NameEntry->getValue()) {
124 assert(isTemporary && "Cannot rename non temporary symbols");
125 SmallString<128> NewName = Name;
127 NewName.resize(Name.size());
128 raw_svector_ostream(NewName) << NextUniqueID++;
129 NameEntry = &UsedNames.GetOrCreateValue(NewName);
130 } while (NameEntry->getValue());
132 NameEntry->setValue(true);
134 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
135 // to the copy of the string that is embedded in the UsedNames entry.
136 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
141 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
142 SmallString<128> NameSV;
143 Name.toVector(NameSV);
144 return GetOrCreateSymbol(NameSV.str());
147 MCSymbol *MCContext::CreateTempSymbol() {
148 SmallString<128> NameSV;
149 raw_svector_ostream(NameSV)
150 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
151 return CreateSymbol(NameSV);
154 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
155 MCLabel *&Label = Instances[LocalLabelVal];
157 Label = new (*this) MCLabel(0);
158 return Label->incInstance();
161 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
162 MCLabel *&Label = Instances[LocalLabelVal];
164 Label = new (*this) MCLabel(0);
165 return Label->getInstance();
168 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
169 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
170 Twine(LocalLabelVal) +
172 Twine(NextInstance(LocalLabelVal)));
174 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
176 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
177 Twine(LocalLabelVal) +
179 Twine(GetInstance(LocalLabelVal) + bORf));
182 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
183 return Symbols.lookup(Name);
186 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
187 SmallString<128> NameSV;
188 Name.toVector(NameSV);
189 return LookupSymbol(NameSV.str());
192 //===----------------------------------------------------------------------===//
193 // Section Management
194 //===----------------------------------------------------------------------===//
196 const MCSectionMachO *MCContext::
197 getMachOSection(StringRef Segment, StringRef Section,
198 unsigned TypeAndAttributes,
199 unsigned Reserved2, SectionKind Kind) {
201 // We unique sections by their segment/section pair. The returned section
202 // may not have the same flags as the requested section, if so this should be
203 // diagnosed by the client as an error.
205 // Create the map if it doesn't already exist.
206 if (MachOUniquingMap == 0)
207 MachOUniquingMap = new MachOUniqueMapTy();
208 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
210 // Form the name to look up.
211 SmallString<64> Name;
216 // Do the lookup, if we have a hit, return it.
217 const MCSectionMachO *&Entry = Map[Name.str()];
218 if (Entry) return Entry;
220 // Otherwise, return a new section.
221 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
225 const MCSectionELF *MCContext::
226 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
228 return getELFSection(Section, Type, Flags, Kind, 0, "");
231 const MCSectionELF *MCContext::
232 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
233 SectionKind Kind, unsigned EntrySize, StringRef Group) {
234 if (ELFUniquingMap == 0)
235 ELFUniquingMap = new ELFUniqueMapTy();
236 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
238 // Do the lookup, if we have a hit, return it.
239 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
240 if (Entry.getValue()) return Entry.getValue();
242 // Possibly refine the entry size first.
244 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
247 MCSymbol *GroupSym = NULL;
249 GroupSym = GetOrCreateSymbol(Group);
251 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
252 Kind, EntrySize, GroupSym);
253 Entry.setValue(Result);
257 const MCSectionELF *MCContext::CreateELFGroupSection() {
258 MCSectionELF *Result =
259 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
260 SectionKind::getReadOnly(), 4, NULL);
264 const MCSection *MCContext::getCOFFSection(StringRef Section,
265 unsigned Characteristics,
268 if (COFFUniquingMap == 0)
269 COFFUniquingMap = new COFFUniqueMapTy();
270 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
272 // Do the lookup, if we have a hit, return it.
273 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
274 if (Entry.getValue()) return Entry.getValue();
276 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
280 Entry.setValue(Result);
284 //===----------------------------------------------------------------------===//
286 //===----------------------------------------------------------------------===//
288 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
289 /// directory tables. If the file number has already been allocated it is an
290 /// error and zero is returned and the client reports the error, else the
291 /// allocated file number is returned. The file numbers may be in any order.
292 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
293 unsigned FileNumber) {
294 // TODO: a FileNumber of zero says to use the next available file number.
295 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
296 // to not be less than one. This needs to be change to be not less than zero.
298 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
299 if (FileNumber >= MCDwarfFiles.size()) {
300 MCDwarfFiles.resize(FileNumber + 1);
302 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
304 // It is an error to use see the same number more than once.
308 // Get the new MCDwarfFile slot for this FileNumber.
309 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
311 if (Directory.empty()) {
312 // Separate the directory part from the basename of the FileName.
313 StringRef tFileName = sys::path::filename(FileName);
314 if (!tFileName.empty()) {
315 Directory = sys::path::parent_path(FileName);
316 if (!Directory.empty())
317 FileName = tFileName;
321 // Find or make a entry in the MCDwarfDirs vector for this Directory.
322 // Capture directory name.
324 if (Directory.empty()) {
325 // For FileNames with no directories a DirIndex of 0 is used.
329 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
330 if (Directory == MCDwarfDirs[DirIndex])
333 if (DirIndex >= MCDwarfDirs.size()) {
334 char *Buf = static_cast<char *>(Allocate(Directory.size()));
335 memcpy(Buf, Directory.data(), Directory.size());
336 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
338 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
339 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
340 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
341 // are stored at MCDwarfFiles[FileNumber].Name .
345 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
347 char *Buf = static_cast<char *>(Allocate(FileName.size()));
348 memcpy(Buf, FileName.data(), FileName.size());
349 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
351 // return the allocated FileNumber.
355 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
356 /// currently is assigned and false otherwise.
357 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
358 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
361 return MCDwarfFiles[FileNumber] != 0;
364 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
365 // If we have a source manager and a location, use it. Otherwise just
366 // use the generic report_fatal_error().
367 if (!SrcMgr || Loc == SMLoc())
368 report_fatal_error(Msg);
370 // Use the source manager to print the message.
371 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
373 // If we reached here, we are failing ungracefully. Run the interrupt handlers
374 // to make sure any special cleanups get done, in particular that we remove
375 // files registered with RemoveFileOnSignal.
376 sys::RunInterruptHandlers();