Replace use of PathV1.h in MCContext.cpp.
[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/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.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   CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0), 
42   DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
43   AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
44
45   error_code EC = llvm::sys::fs::current_path(CompilationDir);
46   assert(!EC && "Could not determine the current directory");
47
48   MachOUniquingMap = 0;
49   ELFUniquingMap = 0;
50   COFFUniquingMap = 0;
51
52   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
53   SecureLog = 0;
54   SecureLogUsed = false;
55
56   if (SrcMgr && SrcMgr->getNumBuffers() > 0)
57     MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
58   else
59     MainFileName = "";
60 }
61
62 MCContext::~MCContext() {
63
64   if (AutoReset)
65     reset();
66
67   // NOTE: The symbols are all allocated out of a bump pointer allocator,
68   // we don't need to free them here.
69   
70   // If the stream for the .secure_log_unique directive was created free it.
71   delete (raw_ostream*)SecureLog;
72 }
73
74 //===----------------------------------------------------------------------===//
75 // Module Lifetime Management
76 //===----------------------------------------------------------------------===//
77
78 void MCContext::reset() {
79   UsedNames.clear();
80   Symbols.clear();
81   Allocator.Reset();
82   Instances.clear();
83   MCDwarfFilesCUMap.clear();
84   MCDwarfDirsCUMap.clear();
85   MCGenDwarfLabelEntries.clear();
86   DwarfDebugFlags = StringRef();
87   MCLineSections.clear();
88   MCLineSectionOrder.clear();
89   DwarfCompileUnitID = 0;
90   MCLineTableSymbols.clear();
91   CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
92
93   // If we have the MachO uniquing map, free it.
94   delete (MachOUniqueMapTy*)MachOUniquingMap;
95   delete (ELFUniqueMapTy*)ELFUniquingMap;
96   delete (COFFUniqueMapTy*)COFFUniquingMap;
97   MachOUniquingMap = 0;
98   ELFUniquingMap = 0;
99   COFFUniquingMap = 0;
100
101   NextUniqueID = 0;
102   AllowTemporaryLabels = true;
103   DwarfLocSeen = false;
104   GenDwarfForAssembly = false;
105   GenDwarfFileNumber = 0;
106 }
107
108 //===----------------------------------------------------------------------===//
109 // Symbol Manipulation
110 //===----------------------------------------------------------------------===//
111
112 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
113   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
114
115   // Do the lookup and get the entire StringMapEntry.  We want access to the
116   // key if we are creating the entry.
117   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
118   MCSymbol *Sym = Entry.getValue();
119
120   if (Sym)
121     return Sym;
122
123   Sym = CreateSymbol(Name);
124   Entry.setValue(Sym);
125   return Sym;
126 }
127
128 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
129   // Determine whether this is an assembler temporary or normal label, if used.
130   bool isTemporary = false;
131   if (AllowTemporaryLabels)
132     isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
133
134   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
135   if (NameEntry->getValue()) {
136     assert(isTemporary && "Cannot rename non temporary symbols");
137     SmallString<128> NewName = Name;
138     do {
139       NewName.resize(Name.size());
140       raw_svector_ostream(NewName) << NextUniqueID++;
141       NameEntry = &UsedNames.GetOrCreateValue(NewName);
142     } while (NameEntry->getValue());
143   }
144   NameEntry->setValue(true);
145
146   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
147   // to the copy of the string that is embedded in the UsedNames entry.
148   MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
149
150   return Result;
151 }
152
153 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
154   SmallString<128> NameSV;
155   Name.toVector(NameSV);
156   return GetOrCreateSymbol(NameSV.str());
157 }
158
159 MCSymbol *MCContext::CreateTempSymbol() {
160   SmallString<128> NameSV;
161   raw_svector_ostream(NameSV)
162     << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
163   return CreateSymbol(NameSV);
164 }
165
166 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
167   MCLabel *&Label = Instances[LocalLabelVal];
168   if (!Label)
169     Label = new (*this) MCLabel(0);
170   return Label->incInstance();
171 }
172
173 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
174   MCLabel *&Label = Instances[LocalLabelVal];
175   if (!Label)
176     Label = new (*this) MCLabel(0);
177   return Label->getInstance();
178 }
179
180 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
181   return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
182                            Twine(LocalLabelVal) +
183                            "\2" +
184                            Twine(NextInstance(LocalLabelVal)));
185 }
186 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
187                                                int bORf) {
188   return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
189                            Twine(LocalLabelVal) +
190                            "\2" +
191                            Twine(GetInstance(LocalLabelVal) + bORf));
192 }
193
194 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
195   return Symbols.lookup(Name);
196 }
197
198 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
199   SmallString<128> NameSV;
200   Name.toVector(NameSV);
201   return LookupSymbol(NameSV.str());
202 }
203
204 //===----------------------------------------------------------------------===//
205 // Section Management
206 //===----------------------------------------------------------------------===//
207
208 const MCSectionMachO *MCContext::
209 getMachOSection(StringRef Segment, StringRef Section,
210                 unsigned TypeAndAttributes,
211                 unsigned Reserved2, SectionKind Kind) {
212
213   // We unique sections by their segment/section pair.  The returned section
214   // may not have the same flags as the requested section, if so this should be
215   // diagnosed by the client as an error.
216
217   // Create the map if it doesn't already exist.
218   if (MachOUniquingMap == 0)
219     MachOUniquingMap = new MachOUniqueMapTy();
220   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
221
222   // Form the name to look up.
223   SmallString<64> Name;
224   Name += Segment;
225   Name.push_back(',');
226   Name += Section;
227
228   // Do the lookup, if we have a hit, return it.
229   const MCSectionMachO *&Entry = Map[Name.str()];
230   if (Entry) return Entry;
231
232   // Otherwise, return a new section.
233   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
234                                             Reserved2, Kind);
235 }
236
237 const MCSectionELF *MCContext::
238 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
239               SectionKind Kind) {
240   return getELFSection(Section, Type, Flags, Kind, 0, "");
241 }
242
243 const MCSectionELF *MCContext::
244 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
245               SectionKind Kind, unsigned EntrySize, StringRef Group) {
246   if (ELFUniquingMap == 0)
247     ELFUniquingMap = new ELFUniqueMapTy();
248   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
249
250   // Do the lookup, if we have a hit, return it.
251   StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
252   if (Entry.getValue()) return Entry.getValue();
253
254   // Possibly refine the entry size first.
255   if (!EntrySize) {
256     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
257   }
258
259   MCSymbol *GroupSym = NULL;
260   if (!Group.empty())
261     GroupSym = GetOrCreateSymbol(Group);
262
263   MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
264                                                   Kind, EntrySize, GroupSym);
265   Entry.setValue(Result);
266   return Result;
267 }
268
269 const MCSectionELF *MCContext::CreateELFGroupSection() {
270   MCSectionELF *Result =
271     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
272                              SectionKind::getReadOnly(), 4, NULL);
273   return Result;
274 }
275
276 const MCSection *MCContext::getCOFFSection(StringRef Section,
277                                            unsigned Characteristics,
278                                            int Selection,
279                                            SectionKind Kind) {
280   if (COFFUniquingMap == 0)
281     COFFUniquingMap = new COFFUniqueMapTy();
282   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
283
284   // Do the lookup, if we have a hit, return it.
285   StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
286   if (Entry.getValue()) return Entry.getValue();
287
288   MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
289                                                     Characteristics,
290                                                     Selection, Kind);
291
292   Entry.setValue(Result);
293   return Result;
294 }
295
296 //===----------------------------------------------------------------------===//
297 // Dwarf Management
298 //===----------------------------------------------------------------------===//
299
300 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
301 /// directory tables.  If the file number has already been allocated it is an
302 /// error and zero is returned and the client reports the error, else the
303 /// allocated file number is returned.  The file numbers may be in any order.
304 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
305                                  unsigned FileNumber, unsigned CUID) {
306   // TODO: a FileNumber of zero says to use the next available file number.
307   // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
308   // to not be less than one.  This needs to be change to be not less than zero.
309
310   SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
311   SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
312   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
313   if (FileNumber >= MCDwarfFiles.size()) {
314     MCDwarfFiles.resize(FileNumber + 1);
315   } else {
316     MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
317     if (ExistingFile)
318       // It is an error to use see the same number more than once.
319       return 0;
320   }
321
322   // Get the new MCDwarfFile slot for this FileNumber.
323   MCDwarfFile *&File = MCDwarfFiles[FileNumber];
324
325   if (Directory.empty()) {
326     // Separate the directory part from the basename of the FileName.
327     StringRef tFileName = sys::path::filename(FileName);
328     if (!tFileName.empty()) {
329       Directory = sys::path::parent_path(FileName);
330       if (!Directory.empty())
331         FileName = tFileName;
332     }
333   }
334
335   // Find or make a entry in the MCDwarfDirs vector for this Directory.
336   // Capture directory name.
337   unsigned DirIndex;
338   if (Directory.empty()) {
339     // For FileNames with no directories a DirIndex of 0 is used.
340     DirIndex = 0;
341   } else {
342     DirIndex = 0;
343     for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
344       if (Directory == MCDwarfDirs[DirIndex])
345         break;
346     }
347     if (DirIndex >= MCDwarfDirs.size()) {
348       char *Buf = static_cast<char *>(Allocate(Directory.size()));
349       memcpy(Buf, Directory.data(), Directory.size());
350       MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
351     }
352     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
353     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
354     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
355     // are stored at MCDwarfFiles[FileNumber].Name .
356     DirIndex++;
357   }
358
359   // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
360   // vector.
361   char *Buf = static_cast<char *>(Allocate(FileName.size()));
362   memcpy(Buf, FileName.data(), FileName.size());
363   File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
364
365   // return the allocated FileNumber.
366   return FileNumber;
367 }
368
369 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
370 /// currently is assigned and false otherwise.
371 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
372   SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
373   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
374     return false;
375
376   return MCDwarfFiles[FileNumber] != 0;
377 }
378
379 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
380   // If we have a source manager and a location, use it. Otherwise just
381   // use the generic report_fatal_error().
382   if (!SrcMgr || Loc == SMLoc())
383     report_fatal_error(Msg);
384
385   // Use the source manager to print the message.
386   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
387
388   // If we reached here, we are failing ungracefully. Run the interrupt handlers
389   // to make sure any special cleanups get done, in particular that we remove
390   // files registered with RemoveFileOnSignal.
391   sys::RunInterruptHandlers();
392   exit(1);
393 }