Move MCSection destruction to MCContext::reset.
[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/MCAssembler.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCLabel.h"
17 #include "llvm/MC/MCObjectFileInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCSectionCOFF.h"
20 #include "llvm/MC/MCSectionELF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/ELF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include <map>
31
32 using namespace llvm;
33
34 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
35                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
36                      bool DoAutoReset)
37     : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
38       Symbols(Allocator), UsedNames(Allocator),
39       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
40       GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
41       AllowTemporaryLabels(true), DwarfCompileUnitID(0),
42       AutoReset(DoAutoReset) {
43
44   std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
45   if (EC)
46     CompilationDir.clear();
47
48   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
49   SecureLog = nullptr;
50   SecureLogUsed = false;
51
52   if (SrcMgr && SrcMgr->getNumBuffers())
53     MainFileName =
54         SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
55 }
56
57 MCContext::~MCContext() {
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   // Call the destructors so the fragments are freed
74   for (auto &I : ELFUniquingMap)
75     I.second->~MCSectionELF();
76   for (auto &I : COFFUniquingMap)
77     I.second->~MCSectionCOFF();
78   for (auto &I : MachOUniquingMap)
79     I.second->~MCSectionMachO();
80
81   UsedNames.clear();
82   Symbols.clear();
83   Allocator.Reset();
84   Instances.clear();
85   CompilationDir.clear();
86   MainFileName.clear();
87   MCDwarfLineTablesCUMap.clear();
88   SectionsForRanges.clear();
89   MCGenDwarfLabelEntries.clear();
90   DwarfDebugFlags = StringRef();
91   DwarfCompileUnitID = 0;
92   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
93
94   MachOUniquingMap.clear();
95   ELFUniquingMap.clear();
96   COFFUniquingMap.clear();
97
98   NextID.clear();
99   AllowTemporaryLabels = true;
100   DwarfLocSeen = false;
101   GenDwarfForAssembly = false;
102   GenDwarfFileNumber = 0;
103 }
104
105 //===----------------------------------------------------------------------===//
106 // Symbol Manipulation
107 //===----------------------------------------------------------------------===//
108
109 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
110   SmallString<128> NameSV;
111   StringRef NameRef = Name.toStringRef(NameSV);
112
113   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
114
115   MCSymbol *&Sym = Symbols[NameRef];
116   if (!Sym)
117     Sym = CreateSymbol(NameRef, false);
118
119   return Sym;
120 }
121
122 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
123   MCSymbol *&Sym = SectionSymbols[&Section];
124   if (Sym)
125     return Sym;
126
127   StringRef Name = Section.getSectionName();
128
129   MCSymbol *&OldSym = Symbols[Name];
130   if (OldSym && OldSym->isUndefined()) {
131     Sym = OldSym;
132     return OldSym;
133   }
134
135   auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
136   Sym = new (*this) MCSymbol(&*NameIter, /*isTemporary*/ false);
137
138   if (!OldSym)
139     OldSym = Sym;
140
141   return Sym;
142 }
143
144 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
145                                                  unsigned Idx) {
146   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
147                            "$frame_escape_" + Twine(Idx));
148 }
149
150 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
151   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
152                            "$parent_frame_offset");
153 }
154
155 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
156   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
157                            FuncName);
158 }
159
160 MCSymbol *MCContext::CreateSymbol(StringRef Name, bool AlwaysAddSuffix) {
161   // Determine whether this is an assembler temporary or normal label, if used.
162   bool IsTemporary = false;
163   if (AllowTemporaryLabels)
164     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
165
166   if (IsTemporary && AlwaysAddSuffix && !UseNamesOnTempLabels)
167     return new (*this) MCSymbol(nullptr, true);
168
169   SmallString<128> NewName = Name;
170   bool AddSuffix = AlwaysAddSuffix;
171   unsigned &NextUniqueID = NextID[Name];
172   for (;;) {
173     if (AddSuffix) {
174       NewName.resize(Name.size());
175       raw_svector_ostream(NewName) << NextUniqueID++;
176     }
177     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
178     if (NameEntry.second) {
179       // Ok, we found a name. Have the MCSymbol object itself refer to the copy
180       // of the string that is embedded in the UsedNames entry.
181       MCSymbol *Result = new (*this) MCSymbol(&*NameEntry.first, IsTemporary);
182       return Result;
183     }
184     assert(IsTemporary && "Cannot rename non-temporary symbols");
185     AddSuffix = true;
186   }
187   llvm_unreachable("Infinite loop");
188 }
189
190 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
191   SmallString<128> NameSV;
192   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
193   return CreateSymbol(NameSV, AlwaysAddSuffix);
194 }
195
196 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
197   SmallString<128> NameSV;
198   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
199   return CreateSymbol(NameSV, true);
200 }
201
202 MCSymbol *MCContext::createTempSymbol() {
203   return createTempSymbol("tmp", true);
204 }
205
206 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
207   MCLabel *&Label = Instances[LocalLabelVal];
208   if (!Label)
209     Label = new (*this) MCLabel(0);
210   return Label->incInstance();
211 }
212
213 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
214   MCLabel *&Label = Instances[LocalLabelVal];
215   if (!Label)
216     Label = new (*this) MCLabel(0);
217   return Label->getInstance();
218 }
219
220 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
221                                                        unsigned Instance) {
222   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
223   if (!Sym)
224     Sym = createTempSymbol();
225   return Sym;
226 }
227
228 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
229   unsigned Instance = NextInstance(LocalLabelVal);
230   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
231 }
232
233 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
234                                                bool Before) {
235   unsigned Instance = GetInstance(LocalLabelVal);
236   if (!Before)
237     ++Instance;
238   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
239 }
240
241 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
242   SmallString<128> NameSV;
243   StringRef NameRef = Name.toStringRef(NameSV);
244   return Symbols.lookup(NameRef);
245 }
246
247 //===----------------------------------------------------------------------===//
248 // Section Management
249 //===----------------------------------------------------------------------===//
250
251 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
252                                            unsigned TypeAndAttributes,
253                                            unsigned Reserved2, SectionKind Kind,
254                                            const char *BeginSymName) {
255
256   // We unique sections by their segment/section pair.  The returned section
257   // may not have the same flags as the requested section, if so this should be
258   // diagnosed by the client as an error.
259
260   // Form the name to look up.
261   SmallString<64> Name;
262   Name += Segment;
263   Name.push_back(',');
264   Name += Section;
265
266   // Do the lookup, if we have a hit, return it.
267   MCSectionMachO *&Entry = MachOUniquingMap[Name];
268   if (Entry)
269     return Entry;
270
271   MCSymbol *Begin = nullptr;
272   if (BeginSymName)
273     Begin = createTempSymbol(BeginSymName, false);
274
275   // Otherwise, return a new section.
276   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
277                                             Reserved2, Kind, Begin);
278 }
279
280 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
281   StringRef GroupName;
282   if (const MCSymbol *Group = Section->getGroup())
283     GroupName = Group->getName();
284
285   unsigned UniqueID = Section->getUniqueID();
286   ELFUniquingMap.erase(
287       ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
288   auto I = ELFUniquingMap.insert(std::make_pair(
289                                      ELFSectionKey{Name, GroupName, UniqueID},
290                                      Section))
291                .first;
292   StringRef CachedName = I->first.SectionName;
293   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
294 }
295
296 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
297                                              unsigned Flags, unsigned EntrySize,
298                                              const MCSymbol *Group,
299                                              const MCSectionELF *Associated) {
300   StringMap<bool>::iterator I;
301   bool Inserted;
302   std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
303
304   return new (*this)
305       MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
306                    EntrySize, Group, true, nullptr, Associated);
307 }
308
309 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
310                                        unsigned Flags, unsigned EntrySize,
311                                        StringRef Group, unsigned UniqueID,
312                                        const char *BeginSymName) {
313   MCSymbol *GroupSym = nullptr;
314   if (!Group.empty())
315     GroupSym = getOrCreateSymbol(Group);
316
317   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
318                        BeginSymName, nullptr);
319 }
320
321 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
322                                        unsigned Flags, unsigned EntrySize,
323                                        const MCSymbol *GroupSym,
324                                        unsigned UniqueID,
325                                        const char *BeginSymName,
326                                        const MCSectionELF *Associated) {
327   StringRef Group = "";
328   if (GroupSym)
329     Group = GroupSym->getName();
330   // Do the lookup, if we have a hit, return it.
331   auto IterBool = ELFUniquingMap.insert(
332       std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
333   auto &Entry = *IterBool.first;
334   if (!IterBool.second)
335     return Entry.second;
336
337   StringRef CachedName = Entry.first.SectionName;
338
339   SectionKind Kind;
340   if (Flags & ELF::SHF_EXECINSTR)
341     Kind = SectionKind::getText();
342   else
343     Kind = SectionKind::getReadOnly();
344
345   MCSymbol *Begin = nullptr;
346   if (BeginSymName)
347     Begin = createTempSymbol(BeginSymName, false);
348
349   MCSectionELF *Result =
350       new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
351                                GroupSym, UniqueID, Begin, Associated);
352   Entry.second = Result;
353   return Result;
354 }
355
356 MCSectionELF *MCContext::createELFGroupSection(const MCSymbol *Group) {
357   MCSectionELF *Result = new (*this)
358       MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
359                    Group, ~0, nullptr, nullptr);
360   return Result;
361 }
362
363 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
364                                          unsigned Characteristics,
365                                          SectionKind Kind,
366                                          StringRef COMDATSymName, int Selection,
367                                          const char *BeginSymName) {
368   MCSymbol *COMDATSymbol = nullptr;
369   if (!COMDATSymName.empty()) {
370     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
371     COMDATSymName = COMDATSymbol->getName();
372   }
373
374   // Do the lookup, if we have a hit, return it.
375   COFFSectionKey T{Section, COMDATSymName, Selection};
376   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
377   auto Iter = IterBool.first;
378   if (!IterBool.second)
379     return Iter->second;
380
381   MCSymbol *Begin = nullptr;
382   if (BeginSymName)
383     Begin = createTempSymbol(BeginSymName, false);
384
385   StringRef CachedName = Iter->first.SectionName;
386   MCSectionCOFF *Result = new (*this) MCSectionCOFF(
387       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
388
389   Iter->second = Result;
390   return Result;
391 }
392
393 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
394                                          unsigned Characteristics,
395                                          SectionKind Kind,
396                                          const char *BeginSymName) {
397   return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
398 }
399
400 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
401   COFFSectionKey T{Section, "", 0};
402   auto Iter = COFFUniquingMap.find(T);
403   if (Iter == COFFUniquingMap.end())
404     return nullptr;
405   return Iter->second;
406 }
407
408 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
409                                                     const MCSymbol *KeySym) {
410   // Return the normal section if we don't have to be associative.
411   if (!KeySym)
412     return Sec;
413
414   // Make an associative section with the same name and kind as the normal
415   // section.
416   unsigned Characteristics =
417       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
418   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
419                         KeySym->getName(),
420                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
421 }
422
423 //===----------------------------------------------------------------------===//
424 // Dwarf Management
425 //===----------------------------------------------------------------------===//
426
427 /// getDwarfFile - takes a file name an number to place in the dwarf file and
428 /// directory tables.  If the file number has already been allocated it is an
429 /// error and zero is returned and the client reports the error, else the
430 /// allocated file number is returned.  The file numbers may be in any order.
431 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
432                                  unsigned FileNumber, unsigned CUID) {
433   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
434   return Table.getFile(Directory, FileName, FileNumber);
435 }
436
437 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
438 /// currently is assigned and false otherwise.
439 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
440   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
441   if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
442     return false;
443
444   return !MCDwarfFiles[FileNumber].Name.empty();
445 }
446
447 /// Remove empty sections from SectionStartEndSyms, to avoid generating
448 /// useless debug info for them.
449 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
450   std::vector<MCSection *> Keep;
451   for (MCSection *Sec : SectionsForRanges) {
452     if (MCOS.mayHaveInstructions(*Sec))
453       Keep.push_back(Sec);
454   }
455   SectionsForRanges.clear();
456   SectionsForRanges.insert(Keep.begin(), Keep.end());
457 }
458
459 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
460   // If we have a source manager and a location, use it. Otherwise just
461   // use the generic report_fatal_error().
462   if (!SrcMgr || Loc == SMLoc())
463     report_fatal_error(Msg, false);
464
465   // Use the source manager to print the message.
466   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
467
468   // If we reached here, we are failing ungracefully. Run the interrupt handlers
469   // to make sure any special cleanups get done, in particular that we remove
470   // files registered with RemoveFileOnSignal.
471   sys::RunInterruptHandlers();
472   exit(1);
473 }