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