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