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