OSDN Git Service

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