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