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