b56017db9355894d6803e872791767cfff21bb9b
[oota-llvm.git] / lib / MC / MCContext.cpp
1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
28 using namespace llvm;
29
30 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
31 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
32 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
33
34
35 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
36                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
37                      bool DoAutoReset) :
38   SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
39   Allocator(), Symbols(Allocator), UsedNames(Allocator),
40   NextUniqueID(0),
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) {
45
46   MachOUniquingMap = 0;
47   ELFUniquingMap = 0;
48   COFFUniquingMap = 0;
49
50   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
51   SecureLog = 0;
52   SecureLogUsed = false;
53
54   if (SrcMgr && SrcMgr->getNumBuffers() > 0)
55     MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
56   else
57     MainFileName = "";
58 }
59
60 MCContext::~MCContext() {
61
62   if (AutoReset)
63     reset();
64
65   // NOTE: The symbols are all allocated out of a bump pointer allocator,
66   // we don't need to free them here.
67   
68   // If the stream for the .secure_log_unique directive was created free it.
69   delete (raw_ostream*)SecureLog;
70 }
71
72 //===----------------------------------------------------------------------===//
73 // Module Lifetime Management
74 //===----------------------------------------------------------------------===//
75
76 void MCContext::reset() {
77   UsedNames.clear();
78   Symbols.clear();
79   Allocator.Reset();
80   Instances.clear();
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);
90
91   // If we have the MachO uniquing map, free it.
92   delete (MachOUniqueMapTy*)MachOUniquingMap;
93   delete (ELFUniqueMapTy*)ELFUniquingMap;
94   delete (COFFUniqueMapTy*)COFFUniquingMap;
95   MachOUniquingMap = 0;
96   ELFUniquingMap = 0;
97   COFFUniquingMap = 0;
98
99   NextUniqueID = 0;
100   AllowTemporaryLabels = true;
101   DwarfLocSeen = false;
102   GenDwarfForAssembly = false;
103   GenDwarfFileNumber = 0;
104 }
105
106 //===----------------------------------------------------------------------===//
107 // Symbol Manipulation
108 //===----------------------------------------------------------------------===//
109
110 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
111   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
112
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();
117
118   if (Sym)
119     return Sym;
120
121   Sym = CreateSymbol(Name);
122   Entry.setValue(Sym);
123   return Sym;
124 }
125
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());
131
132   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
133   if (NameEntry->getValue()) {
134     assert(isTemporary && "Cannot rename non temporary symbols");
135     SmallString<128> NewName = Name;
136     do {
137       NewName.resize(Name.size());
138       raw_svector_ostream(NewName) << NextUniqueID++;
139       NameEntry = &UsedNames.GetOrCreateValue(NewName);
140     } while (NameEntry->getValue());
141   }
142   NameEntry->setValue(true);
143
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);
147
148   return Result;
149 }
150
151 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
152   SmallString<128> NameSV;
153   Name.toVector(NameSV);
154   return GetOrCreateSymbol(NameSV.str());
155 }
156
157 MCSymbol *MCContext::CreateTempSymbol() {
158   SmallString<128> NameSV;
159   raw_svector_ostream(NameSV)
160     << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
161   return CreateSymbol(NameSV);
162 }
163
164 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
165   MCLabel *&Label = Instances[LocalLabelVal];
166   if (!Label)
167     Label = new (*this) MCLabel(0);
168   return Label->incInstance();
169 }
170
171 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
172   MCLabel *&Label = Instances[LocalLabelVal];
173   if (!Label)
174     Label = new (*this) MCLabel(0);
175   return Label->getInstance();
176 }
177
178 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
179   return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
180                            Twine(LocalLabelVal) +
181                            "\2" +
182                            Twine(NextInstance(LocalLabelVal)));
183 }
184 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
185                                                int bORf) {
186   return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
187                            Twine(LocalLabelVal) +
188                            "\2" +
189                            Twine(GetInstance(LocalLabelVal) + bORf));
190 }
191
192 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
193   return Symbols.lookup(Name);
194 }
195
196 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
197   SmallString<128> NameSV;
198   Name.toVector(NameSV);
199   return LookupSymbol(NameSV.str());
200 }
201
202 //===----------------------------------------------------------------------===//
203 // Section Management
204 //===----------------------------------------------------------------------===//
205
206 const MCSectionMachO *MCContext::
207 getMachOSection(StringRef Segment, StringRef Section,
208                 unsigned TypeAndAttributes,
209                 unsigned Reserved2, SectionKind Kind) {
210
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.
214
215   // Create the map if it doesn't already exist.
216   if (MachOUniquingMap == 0)
217     MachOUniquingMap = new MachOUniqueMapTy();
218   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
219
220   // Form the name to look up.
221   SmallString<64> Name;
222   Name += Segment;
223   Name.push_back(',');
224   Name += Section;
225
226   // Do the lookup, if we have a hit, return it.
227   const MCSectionMachO *&Entry = Map[Name.str()];
228   if (Entry) return Entry;
229
230   // Otherwise, return a new section.
231   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
232                                             Reserved2, Kind);
233 }
234
235 const MCSectionELF *MCContext::
236 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
237               SectionKind Kind) {
238   return getELFSection(Section, Type, Flags, Kind, 0, "");
239 }
240
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;
247
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();
251
252   // Possibly refine the entry size first.
253   if (!EntrySize) {
254     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
255   }
256
257   MCSymbol *GroupSym = NULL;
258   if (!Group.empty())
259     GroupSym = GetOrCreateSymbol(Group);
260
261   MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
262                                                   Kind, EntrySize, GroupSym);
263   Entry.setValue(Result);
264   return Result;
265 }
266
267 const MCSectionELF *MCContext::CreateELFGroupSection() {
268   MCSectionELF *Result =
269     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
270                              SectionKind::getReadOnly(), 4, NULL);
271   return Result;
272 }
273
274 const MCSection *MCContext::getCOFFSection(StringRef Section,
275                                            unsigned Characteristics,
276                                            int Selection,
277                                            SectionKind Kind) {
278   if (COFFUniquingMap == 0)
279     COFFUniquingMap = new COFFUniqueMapTy();
280   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
281
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();
285
286   MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
287                                                     Characteristics,
288                                                     Selection, Kind);
289
290   Entry.setValue(Result);
291   return Result;
292 }
293
294 //===----------------------------------------------------------------------===//
295 // Dwarf Management
296 //===----------------------------------------------------------------------===//
297
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.
307
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);
313   } else {
314     MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
315     if (ExistingFile)
316       // It is an error to use see the same number more than once.
317       return 0;
318   }
319
320   // Get the new MCDwarfFile slot for this FileNumber.
321   MCDwarfFile *&File = MCDwarfFiles[FileNumber];
322
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;
330     }
331   }
332
333   // Find or make a entry in the MCDwarfDirs vector for this Directory.
334   // Capture directory name.
335   unsigned DirIndex;
336   if (Directory.empty()) {
337     // For FileNames with no directories a DirIndex of 0 is used.
338     DirIndex = 0;
339   } else {
340     DirIndex = 0;
341     for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
342       if (Directory == MCDwarfDirs[DirIndex])
343         break;
344     }
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()));
349     }
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 .
354     DirIndex++;
355   }
356
357   // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
358   // vector.
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);
362
363   // return the allocated FileNumber.
364   return FileNumber;
365 }
366
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())
372     return false;
373
374   return MCDwarfFiles[FileNumber] != 0;
375 }
376
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);
382
383   // Use the source manager to print the message.
384   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
385
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();
390   exit(1);
391 }