Centralize handling of the eh_begin and eh_end labels.
[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 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
33                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
34                      bool DoAutoReset)
35     : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
36       Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
37       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
38       GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
39       AllowTemporaryLabels(true), DwarfCompileUnitID(0),
40       AutoReset(DoAutoReset) {
41
42   std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
43   if (EC)
44     CompilationDir.clear();
45
46   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
47   SecureLog = nullptr;
48   SecureLogUsed = false;
49
50   if (SrcMgr && SrcMgr->getNumBuffers())
51     MainFileName =
52         SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
53 }
54
55 MCContext::~MCContext() {
56
57   if (AutoReset)
58     reset();
59
60   // NOTE: The symbols are all allocated out of a bump pointer allocator,
61   // we don't need to free them here.
62
63   // If the stream for the .secure_log_unique directive was created free it.
64   delete (raw_ostream*)SecureLog;
65 }
66
67 //===----------------------------------------------------------------------===//
68 // Module Lifetime Management
69 //===----------------------------------------------------------------------===//
70
71 void MCContext::reset() {
72   UsedNames.clear();
73   Symbols.clear();
74   Allocator.Reset();
75   Instances.clear();
76   CompilationDir.clear();
77   MainFileName.clear();
78   MCDwarfLineTablesCUMap.clear();
79   SectionStartEndSyms.clear();
80   MCGenDwarfLabelEntries.clear();
81   DwarfDebugFlags = StringRef();
82   DwarfCompileUnitID = 0;
83   CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
84
85   MachOUniquingMap.clear();
86   ELFUniquingMap.clear();
87   COFFUniquingMap.clear();
88
89   NextUniqueID = 0;
90   AllowTemporaryLabels = true;
91   DwarfLocSeen = false;
92   GenDwarfForAssembly = false;
93   GenDwarfFileNumber = 0;
94 }
95
96 //===----------------------------------------------------------------------===//
97 // Symbol Manipulation
98 //===----------------------------------------------------------------------===//
99
100 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
101   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
102
103   MCSymbol *&Sym = Symbols[Name];
104
105   if (!Sym)
106     Sym = CreateSymbol(Name);
107
108   return Sym;
109 }
110
111 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
112   MCSymbol *&Sym = SectionSymbols[&Section];
113   if (Sym)
114     return Sym;
115
116   StringRef Name = Section.getSectionName();
117
118   MCSymbol *&OldSym = Symbols[Name];
119   if (OldSym && OldSym->isUndefined()) {
120     Sym = OldSym;
121     return OldSym;
122   }
123
124   auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
125   Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
126
127   if (!OldSym)
128     OldSym = Sym;
129
130   return Sym;
131 }
132
133 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName) {
134   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
135                            "frameallocation_" + FuncName);
136 }
137
138 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
139   // Determine whether this is an assembler temporary or normal label, if used.
140   bool isTemporary = false;
141   if (AllowTemporaryLabels)
142     isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
143
144   auto NameEntry = UsedNames.insert(std::make_pair(Name, true));
145   if (!NameEntry.second) {
146     assert(isTemporary && "Cannot rename non-temporary symbols");
147     SmallString<128> NewName = Name;
148     do {
149       NewName.resize(Name.size());
150       raw_svector_ostream(NewName) << NextUniqueID++;
151       NameEntry = UsedNames.insert(std::make_pair(NewName, true));
152     } while (!NameEntry.second);
153   }
154
155   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
156   // to the copy of the string that is embedded in the UsedNames entry.
157   MCSymbol *Result =
158       new (*this) MCSymbol(NameEntry.first->getKey(), isTemporary);
159
160   return Result;
161 }
162
163 MCSymbol *MCContext::createTempSymbol(const Twine &Name) {
164   SmallString<128> NameSV;
165   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
166   return CreateSymbol(NameSV);
167 }
168
169 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
170   SmallString<128> NameSV;
171   return GetOrCreateSymbol(Name.toStringRef(NameSV));
172 }
173
174 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
175   SmallString<128> NameSV;
176   raw_svector_ostream(NameSV)
177     << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
178   return CreateSymbol(NameSV);
179 }
180
181 MCSymbol *MCContext::CreateTempSymbol() {
182   SmallString<128> NameSV;
183   raw_svector_ostream(NameSV)
184     << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
185   return CreateSymbol(NameSV);
186 }
187
188 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
189   MCLabel *&Label = Instances[LocalLabelVal];
190   if (!Label)
191     Label = new (*this) MCLabel(0);
192   return Label->incInstance();
193 }
194
195 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
196   MCLabel *&Label = Instances[LocalLabelVal];
197   if (!Label)
198     Label = new (*this) MCLabel(0);
199   return Label->getInstance();
200 }
201
202 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
203                                                        unsigned Instance) {
204   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
205   if (!Sym)
206     Sym = CreateTempSymbol();
207   return Sym;
208 }
209
210 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
211   unsigned Instance = NextInstance(LocalLabelVal);
212   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
213 }
214
215 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
216                                                bool Before) {
217   unsigned Instance = GetInstance(LocalLabelVal);
218   if (!Before)
219     ++Instance;
220   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
221 }
222
223 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
224   return Symbols.lookup(Name);
225 }
226
227 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
228   SmallString<128> NameSV;
229   Name.toVector(NameSV);
230   return LookupSymbol(NameSV.str());
231 }
232
233 //===----------------------------------------------------------------------===//
234 // Section Management
235 //===----------------------------------------------------------------------===//
236
237 const MCSectionMachO *MCContext::
238 getMachOSection(StringRef Segment, StringRef Section,
239                 unsigned TypeAndAttributes,
240                 unsigned Reserved2, SectionKind Kind) {
241
242   // We unique sections by their segment/section pair.  The returned section
243   // may not have the same flags as the requested section, if so this should be
244   // diagnosed by the client as an error.
245
246   // Form the name to look up.
247   SmallString<64> Name;
248   Name += Segment;
249   Name.push_back(',');
250   Name += Section;
251
252   // Do the lookup, if we have a hit, return it.
253   const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
254   if (Entry) return Entry;
255
256   // Otherwise, return a new section.
257   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
258                                             Reserved2, Kind);
259 }
260
261 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
262                                              unsigned Flags) {
263   return getELFSection(Section, Type, Flags, 0, "");
264 }
265
266 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
267   StringRef GroupName;
268   if (const MCSymbol *Group = Section->getGroup())
269     GroupName = Group->getName();
270
271   ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
272   auto I =
273       ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
274                                            Section)).first;
275   StringRef CachedName = I->first.first;
276   const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
277 }
278
279 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
280                                              unsigned Flags, unsigned EntrySize,
281                                              StringRef Group, bool Unique) {
282   // Do the lookup, if we have a hit, return it.
283   auto IterBool = ELFUniquingMap.insert(
284       std::make_pair(SectionGroupPair(Section, Group), nullptr));
285   auto &Entry = *IterBool.first;
286   if (!IterBool.second && !Unique)
287     return Entry.second;
288
289   MCSymbol *GroupSym = nullptr;
290   if (!Group.empty())
291     GroupSym = GetOrCreateSymbol(Group);
292
293   StringRef CachedName = Entry.first.first;
294
295   SectionKind Kind;
296   if (Flags & ELF::SHF_EXECINSTR)
297     Kind = SectionKind::getText();
298   else
299     Kind = SectionKind::getReadOnly();
300
301   MCSectionELF *Result = new (*this)
302       MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, Unique);
303   if (!Unique)
304     Entry.second = Result;
305   return Result;
306 }
307
308 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
309                                              unsigned Flags, unsigned EntrySize,
310                                              StringRef Group) {
311   return getELFSection(Section, Type, Flags, EntrySize, Group, false);
312 }
313
314 const MCSectionELF *MCContext::CreateELFGroupSection() {
315   MCSectionELF *Result =
316       new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
317                                SectionKind::getReadOnly(), 4, nullptr, false);
318   return Result;
319 }
320
321 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
322                                                unsigned Characteristics,
323                                                SectionKind Kind,
324                                                StringRef COMDATSymName,
325                                                int Selection) {
326   // Do the lookup, if we have a hit, return it.
327
328   SectionGroupTriple T(Section, COMDATSymName, Selection);
329   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
330   auto Iter = IterBool.first;
331   if (!IterBool.second)
332     return Iter->second;
333
334   MCSymbol *COMDATSymbol = nullptr;
335   if (!COMDATSymName.empty())
336     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
337
338   StringRef CachedName = std::get<0>(Iter->first);
339   MCSectionCOFF *Result = new (*this)
340       MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
341
342   Iter->second = Result;
343   return Result;
344 }
345
346 const MCSectionCOFF *
347 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
348                           SectionKind Kind) {
349   return getCOFFSection(Section, Characteristics, Kind, "", 0);
350 }
351
352 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
353   SectionGroupTriple T(Section, "", 0);
354   auto Iter = COFFUniquingMap.find(T);
355   if (Iter == COFFUniquingMap.end())
356     return nullptr;
357   return Iter->second;
358 }
359
360 const MCSectionCOFF *
361 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
362                                      const MCSymbol *KeySym) {
363   // Return the normal section if we don't have to be associative.
364   if (!KeySym)
365     return Sec;
366
367   // Make an associative section with the same name and kind as the normal
368   // section.
369   unsigned Characteristics =
370       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
371   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
372                         KeySym->getName(),
373                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
374 }
375
376 //===----------------------------------------------------------------------===//
377 // Dwarf Management
378 //===----------------------------------------------------------------------===//
379
380 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
381 /// directory tables.  If the file number has already been allocated it is an
382 /// error and zero is returned and the client reports the error, else the
383 /// allocated file number is returned.  The file numbers may be in any order.
384 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
385                                  unsigned FileNumber, unsigned CUID) {
386   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
387   return Table.getFile(Directory, FileName, FileNumber);
388 }
389
390 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
391 /// currently is assigned and false otherwise.
392 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
393   const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
394   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
395     return false;
396
397   return !MCDwarfFiles[FileNumber].Name.empty();
398 }
399
400 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
401 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
402 /// useless debug info for them.
403 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
404   MCContext &context = MCOS.getContext();
405
406   auto sec = SectionStartEndSyms.begin();
407   while (sec != SectionStartEndSyms.end()) {
408     assert(sec->second.first && "Start symbol must be set by now");
409     MCOS.SwitchSection(sec->first);
410     if (MCOS.mayHaveInstructions()) {
411       MCSymbol *SectionEndSym = context.CreateTempSymbol();
412       MCOS.EmitLabel(SectionEndSym);
413       sec->second.second = SectionEndSym;
414       ++sec;
415     } else {
416       MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
417         to_erase = sec;
418       sec = SectionStartEndSyms.erase(to_erase);
419     }
420   }
421 }
422
423 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
424   // If we have a source manager and a location, use it. Otherwise just
425   // use the generic report_fatal_error().
426   if (!SrcMgr || Loc == SMLoc())
427     report_fatal_error(Msg, false);
428
429   // Use the source manager to print the message.
430   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
431
432   // If we reached here, we are failing ungracefully. Run the interrupt handlers
433   // to make sure any special cleanups get done, in particular that we remove
434   // files registered with RemoveFileOnSignal.
435   sys::RunInterruptHandlers();
436   exit(1);
437 }