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