1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
33 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
34 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
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) {
43 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
45 CompilationDir.clear();
47 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
49 SecureLogUsed = false;
51 if (SrcMgr && SrcMgr->getNumBuffers())
53 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
56 MCContext::~MCContext() {
61 // NOTE: The symbols are all allocated out of a bump pointer allocator,
62 // we don't need to free them here.
64 // If the stream for the .secure_log_unique directive was created free it.
65 delete (raw_ostream*)SecureLog;
68 //===----------------------------------------------------------------------===//
69 // Module Lifetime Management
70 //===----------------------------------------------------------------------===//
72 void MCContext::reset() {
77 CompilationDir.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);
86 MachOUniquingMap.clear();
87 ELFUniquingMap.clear();
88 COFFUniquingMap.clear();
91 AllowTemporaryLabels = true;
93 GenDwarfForAssembly = false;
94 GenDwarfFileNumber = 0;
97 //===----------------------------------------------------------------------===//
98 // Symbol Manipulation
99 //===----------------------------------------------------------------------===//
101 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
102 SmallString<128> NameSV;
103 StringRef NameRef = Name.toStringRef(NameSV);
105 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
107 MCSymbol *&Sym = Symbols[NameRef];
109 Sym = CreateSymbol(NameRef, false);
114 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
115 MCSymbol *&Sym = SectionSymbols[&Section];
119 StringRef Name = Section.getSectionName();
121 MCSymbol *&OldSym = Symbols[Name];
122 if (OldSym && OldSym->isUndefined()) {
127 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
128 Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
136 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
138 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
139 "$frame_escape_" + Twine(Idx));
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());
148 SmallString<128> NewName = Name;
149 bool AddSuffix = AlwaysAddSuffix;
150 unsigned &NextUniqueID = NextID[Name];
153 NewName.resize(Name.size());
154 raw_svector_ostream(NewName) << NextUniqueID++;
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.
161 new (*this) MCSymbol(NameEntry.first->getKey(), IsTemporary);
164 assert(IsTemporary && "Cannot rename non-temporary symbols");
167 llvm_unreachable("Infinite loop");
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);
176 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
177 SmallString<128> NameSV;
178 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
179 return CreateSymbol(NameSV, true);
182 MCSymbol *MCContext::CreateTempSymbol() {
183 return createTempSymbol("tmp", true);
186 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
187 MCLabel *&Label = Instances[LocalLabelVal];
189 Label = new (*this) MCLabel(0);
190 return Label->incInstance();
193 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
194 MCLabel *&Label = Instances[LocalLabelVal];
196 Label = new (*this) MCLabel(0);
197 return Label->getInstance();
200 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
202 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
204 Sym = CreateTempSymbol();
208 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
209 unsigned Instance = NextInstance(LocalLabelVal);
210 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
213 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
215 unsigned Instance = GetInstance(LocalLabelVal);
218 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
221 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
222 SmallString<128> NameSV;
223 StringRef NameRef = Name.toStringRef(NameSV);
224 return Symbols.lookup(NameRef);
227 //===----------------------------------------------------------------------===//
228 // Section Management
229 //===----------------------------------------------------------------------===//
231 const MCSectionMachO *
232 MCContext::getMachOSection(StringRef Segment, StringRef Section,
233 unsigned TypeAndAttributes, unsigned Reserved2,
234 SectionKind Kind, const char *BeginSymName) {
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.
240 // Form the name to look up.
241 SmallString<64> Name;
246 // Do the lookup, if we have a hit, return it.
247 const MCSectionMachO *&Entry = MachOUniquingMap[Name];
251 MCSymbol *Begin = nullptr;
253 Begin = createTempSymbol(BeginSymName, false);
255 // Otherwise, return a new section.
256 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
257 Reserved2, Kind, Begin);
260 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
262 const char *BeginSymName) {
263 return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
266 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
268 if (const MCSymbol *Group = Section->getGroup())
269 GroupName = Group->getName();
271 ELFUniquingMap.erase(ELFSectionKey{Section->getSectionName(), GroupName});
272 auto I = ELFUniquingMap.insert(std::make_pair(ELFSectionKey{Name, GroupName},
274 StringRef CachedName = I->first.SectionName;
275 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
279 MCContext::createELFRelSection(StringRef Name, unsigned Type, unsigned Flags,
280 unsigned EntrySize, const MCSymbol *Group) {
281 StringMap<bool>::iterator I;
283 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
286 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
287 EntrySize, Group, true, nullptr);
290 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
291 unsigned Flags, unsigned EntrySize,
292 StringRef Group, bool Unique,
293 const char *BeginSymName) {
294 MCSymbol *GroupSym = nullptr;
295 if (!Group.empty()) {
296 GroupSym = GetOrCreateSymbol(Group);
297 Group = GroupSym->getName();
300 // Do the lookup, if we have a hit, return it.
301 auto IterBool = ELFUniquingMap.insert(
302 std::make_pair(ELFSectionKey{Section, Group}, nullptr));
303 auto &Entry = *IterBool.first;
304 if (!IterBool.second && !Unique)
307 StringRef CachedName = Entry.first.SectionName;
310 if (Flags & ELF::SHF_EXECINSTR)
311 Kind = SectionKind::getText();
313 Kind = SectionKind::getReadOnly();
315 MCSymbol *Begin = nullptr;
317 Begin = createTempSymbol(BeginSymName, false);
319 MCSectionELF *Result = new (*this) MCSectionELF(
320 CachedName, Type, Flags, Kind, EntrySize, GroupSym, Unique, Begin);
322 Entry.second = Result;
326 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
327 unsigned Flags, unsigned EntrySize,
329 const char *BeginSymName) {
330 return getELFSection(Section, Type, Flags, EntrySize, Group, false,
334 const MCSectionELF *MCContext::CreateELFGroupSection() {
335 MCSectionELF *Result = new (*this)
336 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
337 nullptr, false, nullptr);
341 const MCSectionCOFF *
342 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
343 SectionKind Kind, StringRef COMDATSymName,
344 int Selection, const char *BeginSymName) {
345 MCSymbol *COMDATSymbol = nullptr;
346 if (!COMDATSymName.empty()) {
347 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
348 COMDATSymName = COMDATSymbol->getName();
351 // Do the lookup, if we have a hit, return it.
352 COFFSectionKey T{Section, COMDATSymName, Selection};
353 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
354 auto Iter = IterBool.first;
355 if (!IterBool.second)
358 MCSymbol *Begin = nullptr;
360 Begin = createTempSymbol(BeginSymName, false);
362 StringRef CachedName = Iter->first.SectionName;
363 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
364 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
366 Iter->second = Result;
370 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
371 unsigned Characteristics,
373 const char *BeginSymName) {
374 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
377 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
378 COFFSectionKey T{Section, "", 0};
379 auto Iter = COFFUniquingMap.find(T);
380 if (Iter == COFFUniquingMap.end())
385 const MCSectionCOFF *
386 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
387 const MCSymbol *KeySym) {
388 // Return the normal section if we don't have to be associative.
392 // Make an associative section with the same name and kind as the normal
394 unsigned Characteristics =
395 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
396 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
398 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
401 //===----------------------------------------------------------------------===//
403 //===----------------------------------------------------------------------===//
405 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
406 /// directory tables. If the file number has already been allocated it is an
407 /// error and zero is returned and the client reports the error, else the
408 /// allocated file number is returned. The file numbers may be in any order.
409 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
410 unsigned FileNumber, unsigned CUID) {
411 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
412 return Table.getFile(Directory, FileName, FileNumber);
415 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
416 /// currently is assigned and false otherwise.
417 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
418 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
419 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
422 return !MCDwarfFiles[FileNumber].Name.empty();
425 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
426 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
427 /// useless debug info for them.
428 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
429 MCContext &context = MCOS.getContext();
431 auto sec = SectionStartEndSyms.begin();
432 while (sec != SectionStartEndSyms.end()) {
433 assert(sec->second.first && "Start symbol must be set by now");
434 MCOS.SwitchSection(sec->first);
435 if (MCOS.mayHaveInstructions()) {
436 MCSymbol *SectionEndSym = context.CreateTempSymbol();
437 MCOS.EmitLabel(SectionEndSym);
438 sec->second.second = SectionEndSym;
441 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
443 sec = SectionStartEndSyms.erase(to_erase);
448 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
449 // If we have a source manager and a location, use it. Otherwise just
450 // use the generic report_fatal_error().
451 if (!SrcMgr || Loc == SMLoc())
452 report_fatal_error(Msg, false);
454 // Use the source manager to print the message.
455 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
457 // If we reached here, we are failing ungracefully. Run the interrupt handlers
458 // to make sure any special cleanups get done, in particular that we remove
459 // files registered with RemoveFileOnSignal.
460 sys::RunInterruptHandlers();