Correctly handle references to section symbols.
[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   // Do the lookup and get the entire StringMapEntry.  We want access to the
104   // key if we are creating the entry.
105   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
106   MCSymbol *Sym = Entry.getValue();
107
108   if (Sym)
109     return Sym;
110
111   Sym = CreateSymbol(Name);
112   Entry.setValue(Sym);
113   return Sym;
114 }
115
116 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
117   MCSymbol *&Sym = SectionSymbols[&Section];
118   if (Sym)
119     return Sym;
120
121   StringRef Name = Section.getSectionName();
122   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
123   NameEntry->setValue(true);
124   Sym = new (*this) MCSymbol(NameEntry->getKey(), /*isTemporary*/ false);
125
126   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
127   if (!Entry.getValue())
128     Entry.setValue(Sym);
129
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::CreateLinkerPrivateTempSymbol() {
164   SmallString<128> NameSV;
165   raw_svector_ostream(NameSV)
166     << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
167   return CreateSymbol(NameSV);
168 }
169
170 MCSymbol *MCContext::CreateTempSymbol() {
171   SmallString<128> NameSV;
172   raw_svector_ostream(NameSV)
173     << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
174   return CreateSymbol(NameSV);
175 }
176
177 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
178   MCLabel *&Label = Instances[LocalLabelVal];
179   if (!Label)
180     Label = new (*this) MCLabel(0);
181   return Label->incInstance();
182 }
183
184 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
185   MCLabel *&Label = Instances[LocalLabelVal];
186   if (!Label)
187     Label = new (*this) MCLabel(0);
188   return Label->getInstance();
189 }
190
191 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
192                                                        unsigned Instance) {
193   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
194   if (!Sym)
195     Sym = CreateTempSymbol();
196   return Sym;
197 }
198
199 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
200   unsigned Instance = NextInstance(LocalLabelVal);
201   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
202 }
203
204 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
205                                                bool Before) {
206   unsigned Instance = GetInstance(LocalLabelVal);
207   if (!Before)
208     ++Instance;
209   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
210 }
211
212 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
213   return Symbols.lookup(Name);
214 }
215
216 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
217   SmallString<128> NameSV;
218   Name.toVector(NameSV);
219   return LookupSymbol(NameSV.str());
220 }
221
222 //===----------------------------------------------------------------------===//
223 // Section Management
224 //===----------------------------------------------------------------------===//
225
226 const MCSectionMachO *MCContext::
227 getMachOSection(StringRef Segment, StringRef Section,
228                 unsigned TypeAndAttributes,
229                 unsigned Reserved2, SectionKind Kind) {
230
231   // We unique sections by their segment/section pair.  The returned section
232   // may not have the same flags as the requested section, if so this should be
233   // diagnosed by the client as an error.
234
235   // Form the name to look up.
236   SmallString<64> Name;
237   Name += Segment;
238   Name.push_back(',');
239   Name += Section;
240
241   // Do the lookup, if we have a hit, return it.
242   const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
243   if (Entry) return Entry;
244
245   // Otherwise, return a new section.
246   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
247                                             Reserved2, Kind);
248 }
249
250 const MCSectionELF *MCContext::
251 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
252               SectionKind Kind) {
253   return getELFSection(Section, Type, Flags, Kind, 0, "");
254 }
255
256 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
257   StringRef GroupName;
258   if (const MCSymbol *Group = Section->getGroup())
259     GroupName = Group->getName();
260
261   ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
262   auto I =
263       ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
264                                            Section)).first;
265   StringRef CachedName = I->first.first;
266   const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
267 }
268
269 const MCSectionELF *MCContext::
270 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
271               SectionKind Kind, unsigned EntrySize, StringRef Group) {
272   // Do the lookup, if we have a hit, return it.
273   auto IterBool = ELFUniquingMap.insert(
274       std::make_pair(SectionGroupPair(Section, Group), nullptr));
275   auto &Entry = *IterBool.first;
276   if (!IterBool.second) return Entry.second;
277
278   // Possibly refine the entry size first.
279   if (!EntrySize) {
280     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
281   }
282
283   MCSymbol *GroupSym = nullptr;
284   if (!Group.empty())
285     GroupSym = GetOrCreateSymbol(Group);
286
287   StringRef CachedName = Entry.first.first;
288   MCSectionELF *Result = new (*this)
289       MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym);
290   Entry.second = Result;
291   return Result;
292 }
293
294 const MCSectionELF *MCContext::CreateELFGroupSection() {
295   MCSectionELF *Result =
296     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
297                              SectionKind::getReadOnly(), 4, nullptr);
298   return Result;
299 }
300
301 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
302                                                unsigned Characteristics,
303                                                SectionKind Kind,
304                                                StringRef COMDATSymName,
305                                                int Selection) {
306   // Do the lookup, if we have a hit, return it.
307
308   SectionGroupTriple T(Section, COMDATSymName, Selection);
309   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
310   auto Iter = IterBool.first;
311   if (!IterBool.second)
312     return Iter->second;
313
314   MCSymbol *COMDATSymbol = nullptr;
315   if (!COMDATSymName.empty())
316     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
317
318   StringRef CachedName = std::get<0>(Iter->first);
319   MCSectionCOFF *Result = new (*this)
320       MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
321
322   Iter->second = Result;
323   return Result;
324 }
325
326 const MCSectionCOFF *
327 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
328                           SectionKind Kind) {
329   return getCOFFSection(Section, Characteristics, Kind, "", 0);
330 }
331
332 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
333   SectionGroupTriple T(Section, "", 0);
334   auto Iter = COFFUniquingMap.find(T);
335   if (Iter == COFFUniquingMap.end())
336     return nullptr;
337   return Iter->second;
338 }
339
340 const MCSectionCOFF *
341 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
342                                      const MCSymbol *KeySym) {
343   // Return the normal section if we don't have to be associative.
344   if (!KeySym)
345     return Sec;
346
347   // Make an associative section with the same name and kind as the normal
348   // section.
349   unsigned Characteristics =
350       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
351   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
352                         KeySym->getName(),
353                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
354 }
355
356 //===----------------------------------------------------------------------===//
357 // Dwarf Management
358 //===----------------------------------------------------------------------===//
359
360 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
361 /// directory tables.  If the file number has already been allocated it is an
362 /// error and zero is returned and the client reports the error, else the
363 /// allocated file number is returned.  The file numbers may be in any order.
364 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
365                                  unsigned FileNumber, unsigned CUID) {
366   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
367   return Table.getFile(Directory, FileName, FileNumber);
368 }
369
370 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
371 /// currently is assigned and false otherwise.
372 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
373   const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
374   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
375     return false;
376
377   return !MCDwarfFiles[FileNumber].Name.empty();
378 }
379
380 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
381 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
382 /// useless debug info for them.
383 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
384   MCContext &context = MCOS.getContext();
385
386   auto sec = SectionStartEndSyms.begin();
387   while (sec != SectionStartEndSyms.end()) {
388     assert(sec->second.first && "Start symbol must be set by now");
389     MCOS.SwitchSection(sec->first);
390     if (MCOS.mayHaveInstructions()) {
391       MCSymbol *SectionEndSym = context.CreateTempSymbol();
392       MCOS.EmitLabel(SectionEndSym);
393       sec->second.second = SectionEndSym;
394       ++sec;
395     } else {
396       MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
397         to_erase = sec;
398       sec = SectionStartEndSyms.erase(to_erase);
399     }
400   }
401 }
402
403 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
404   // If we have a source manager and a location, use it. Otherwise just
405   // use the generic report_fatal_error().
406   if (!SrcMgr || Loc == SMLoc())
407     report_fatal_error(Msg, false);
408
409   // Use the source manager to print the message.
410   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
411
412   // If we reached here, we are failing ungracefully. Run the interrupt handlers
413   // to make sure any special cleanups get done, in particular that we remove
414   // files registered with RemoveFileOnSignal.
415   sys::RunInterruptHandlers();
416   exit(1);
417 }