Reimplement debug info compression by compressing the whole section, rather than...
[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), Allocator(),
42       Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
43       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
44       GenDwarfForAssembly(false), GenDwarfFileNumber(0),
45       AllowTemporaryLabels(true), DwarfCompileUnitID(0),
46       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 }
63
64 MCContext::~MCContext() {
65
66   if (AutoReset)
67     reset();
68
69   // NOTE: The symbols are all allocated out of a bump pointer allocator,
70   // we don't need to free them here.
71
72   // If the stream for the .secure_log_unique directive was created free it.
73   delete (raw_ostream*)SecureLog;
74 }
75
76 //===----------------------------------------------------------------------===//
77 // Module Lifetime Management
78 //===----------------------------------------------------------------------===//
79
80 void MCContext::reset() {
81   UsedNames.clear();
82   Symbols.clear();
83   Allocator.Reset();
84   Instances.clear();
85   MCDwarfLineTablesCUMap.clear();
86   MCGenDwarfLabelEntries.clear();
87   DwarfDebugFlags = StringRef();
88   DwarfCompileUnitID = 0;
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   return GetOrCreateSymbol(Name.toStringRef(NameSV));
154 }
155
156 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
157   SmallString<128> NameSV;
158   raw_svector_ostream(NameSV)
159     << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
160   return CreateSymbol(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(unsigned 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(unsigned LocalLabelVal) {
178   MCLabel *&Label = Instances[LocalLabelVal];
179   if (!Label)
180     Label = new (*this) MCLabel(0);
181   return Label->getInstance();
182 }
183
184 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
185                                                        unsigned Instance) {
186   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
187   if (!Sym)
188     Sym = CreateTempSymbol();
189   return Sym;
190 }
191
192 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
193   unsigned Instance = NextInstance(LocalLabelVal);
194   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
195 }
196
197 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
198                                                bool Before) {
199   unsigned Instance = GetInstance(LocalLabelVal);
200   if (!Before)
201     ++Instance;
202   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
203 }
204
205 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
206   return Symbols.lookup(Name);
207 }
208
209 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
210   SmallString<128> NameSV;
211   Name.toVector(NameSV);
212   return LookupSymbol(NameSV.str());
213 }
214
215 //===----------------------------------------------------------------------===//
216 // Section Management
217 //===----------------------------------------------------------------------===//
218
219 const MCSectionMachO *MCContext::
220 getMachOSection(StringRef Segment, StringRef Section,
221                 unsigned TypeAndAttributes,
222                 unsigned Reserved2, SectionKind Kind) {
223
224   // We unique sections by their segment/section pair.  The returned section
225   // may not have the same flags as the requested section, if so this should be
226   // diagnosed by the client as an error.
227
228   // Create the map if it doesn't already exist.
229   if (MachOUniquingMap == 0)
230     MachOUniquingMap = new MachOUniqueMapTy();
231   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
232
233   // Form the name to look up.
234   SmallString<64> Name;
235   Name += Segment;
236   Name.push_back(',');
237   Name += Section;
238
239   // Do the lookup, if we have a hit, return it.
240   const MCSectionMachO *&Entry = Map[Name.str()];
241   if (Entry) return Entry;
242
243   // Otherwise, return a new section.
244   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
245                                             Reserved2, Kind);
246 }
247
248 const MCSectionELF *MCContext::
249 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
250               SectionKind Kind) {
251   return getELFSection(Section, Type, Flags, Kind, 0, "");
252 }
253
254 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
255   if (ELFUniquingMap == 0)
256     ELFUniquingMap = new ELFUniqueMapTy();
257   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
258
259   StringRef GroupName;
260   if (const MCSymbol *Group = Section->getGroup())
261     GroupName = Group->getName();
262
263   Map.erase(SectionGroupPair(Section->getSectionName(), GroupName));
264   auto I = Map.insert(std::make_pair(SectionGroupPair(Name, GroupName),
265                                      Section)).first;
266   const_cast<MCSectionELF*>(Section)->setSectionName(I->first.first);
267 }
268
269 const MCSectionELF *MCContext::
270 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
271               SectionKind Kind, unsigned EntrySize, StringRef Group) {
272   if (ELFUniquingMap == 0)
273     ELFUniquingMap = new ELFUniqueMapTy();
274   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
275
276   // Do the lookup, if we have a hit, return it.
277   std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert(
278       std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0));
279   if (!Entry.second) return Entry.first->second;
280
281   // Possibly refine the entry size first.
282   if (!EntrySize) {
283     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
284   }
285
286   MCSymbol *GroupSym = NULL;
287   if (!Group.empty())
288     GroupSym = GetOrCreateSymbol(Group);
289
290   MCSectionELF *Result = new (*this) MCSectionELF(
291       Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym);
292   Entry.first->second = Result;
293   return Result;
294 }
295
296 const MCSectionELF *MCContext::CreateELFGroupSection() {
297   MCSectionELF *Result =
298     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
299                              SectionKind::getReadOnly(), 4, NULL);
300   return Result;
301 }
302
303 const MCSectionCOFF *
304 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
305                           SectionKind Kind, StringRef COMDATSymName,
306                           int Selection, const MCSectionCOFF *Assoc) {
307   if (COFFUniquingMap == 0)
308     COFFUniquingMap = new COFFUniqueMapTy();
309   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
310
311   // Do the lookup, if we have a hit, return it.
312
313   SectionGroupPair P(Section, COMDATSymName);
314   std::pair<COFFUniqueMapTy::iterator, bool> Entry =
315       Map.insert(std::make_pair(P, (MCSectionCOFF *)0));
316   COFFUniqueMapTy::iterator Iter = Entry.first;
317   if (!Entry.second)
318     return Iter->second;
319
320   const MCSymbol *COMDATSymbol = NULL;
321   if (!COMDATSymName.empty())
322     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
323
324   MCSectionCOFF *Result =
325       new (*this) MCSectionCOFF(Iter->first.first, Characteristics,
326                                 COMDATSymbol, Selection, Assoc, Kind);
327
328   Iter->second = Result;
329   return Result;
330 }
331
332 const MCSectionCOFF *
333 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
334                           SectionKind Kind) {
335   return getCOFFSection(Section, Characteristics, Kind, "", 0);
336 }
337
338 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
339   if (COFFUniquingMap == 0)
340     COFFUniquingMap = new COFFUniqueMapTy();
341   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
342
343   SectionGroupPair P(Section, "");
344   COFFUniqueMapTy::iterator Iter = Map.find(P);
345   if (Iter == Map.end())
346     return 0;
347   return Iter->second;
348 }
349
350 //===----------------------------------------------------------------------===//
351 // Dwarf Management
352 //===----------------------------------------------------------------------===//
353
354 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
355 /// directory tables.  If the file number has already been allocated it is an
356 /// error and zero is returned and the client reports the error, else the
357 /// allocated file number is returned.  The file numbers may be in any order.
358 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
359                                  unsigned FileNumber, unsigned CUID) {
360   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
361   return Table.getFile(Directory, FileName, FileNumber);
362 }
363
364 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
365 /// currently is assigned and false otherwise.
366 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
367   const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
368   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
369     return false;
370
371   return !MCDwarfFiles[FileNumber].Name.empty();
372 }
373
374 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
375   // If we have a source manager and a location, use it. Otherwise just
376   // use the generic report_fatal_error().
377   if (!SrcMgr || Loc == SMLoc())
378     report_fatal_error(Msg, false);
379
380   // Use the source manager to print the message.
381   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
382
383   // If we reached here, we are failing ungracefully. Run the interrupt handlers
384   // to make sure any special cleanups get done, in particular that we remove
385   // files registered with RemoveFileOnSignal.
386   sys::RunInterruptHandlers();
387   exit(1);
388 }