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