Home | History | Annotate | Download | only in MC
      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 using namespace llvm;
     29 
     30 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
     31 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
     32 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
     33 
     34 
     35 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
     36                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
     37                      bool DoAutoReset) :
     38   SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
     39   Allocator(), Symbols(Allocator), UsedNames(Allocator),
     40   NextUniqueID(0),
     41   CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
     42   DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
     43   AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
     44 
     45   error_code EC = llvm::sys::fs::current_path(CompilationDir);
     46   assert(!EC && "Could not determine the current directory");
     47   (void)EC;
     48 
     49   MachOUniquingMap = 0;
     50   ELFUniquingMap = 0;
     51   COFFUniquingMap = 0;
     52 
     53   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
     54   SecureLog = 0;
     55   SecureLogUsed = false;
     56 
     57   if (SrcMgr && SrcMgr->getNumBuffers() > 0)
     58     MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
     59   else
     60     MainFileName = "";
     61 }
     62 
     63 MCContext::~MCContext() {
     64 
     65   if (AutoReset)
     66     reset();
     67 
     68   // NOTE: The symbols are all allocated out of a bump pointer allocator,
     69   // we don't need to free them here.
     70 
     71   // If the stream for the .secure_log_unique directive was created free it.
     72   delete (raw_ostream*)SecureLog;
     73 }
     74 
     75 //===----------------------------------------------------------------------===//
     76 // Module Lifetime Management
     77 //===----------------------------------------------------------------------===//
     78 
     79 void MCContext::reset() {
     80   UsedNames.clear();
     81   Symbols.clear();
     82   Allocator.Reset();
     83   Instances.clear();
     84   MCDwarfFilesCUMap.clear();
     85   MCDwarfDirsCUMap.clear();
     86   MCGenDwarfLabelEntries.clear();
     87   DwarfDebugFlags = StringRef();
     88   MCLineSections.clear();
     89   MCLineSectionOrder.clear();
     90   DwarfCompileUnitID = 0;
     91   MCLineTableSymbols.clear();
     92   CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
     93 
     94   // If we have the MachO uniquing map, free it.
     95   delete (MachOUniqueMapTy*)MachOUniquingMap;
     96   delete (ELFUniqueMapTy*)ELFUniquingMap;
     97   delete (COFFUniqueMapTy*)COFFUniquingMap;
     98   MachOUniquingMap = 0;
     99   ELFUniquingMap = 0;
    100   COFFUniquingMap = 0;
    101 
    102   NextUniqueID = 0;
    103   AllowTemporaryLabels = true;
    104   DwarfLocSeen = false;
    105   GenDwarfForAssembly = false;
    106   GenDwarfFileNumber = 0;
    107 }
    108 
    109 //===----------------------------------------------------------------------===//
    110 // Symbol Manipulation
    111 //===----------------------------------------------------------------------===//
    112 
    113 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
    114   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
    115 
    116   // Do the lookup and get the entire StringMapEntry.  We want access to the
    117   // key if we are creating the entry.
    118   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
    119   MCSymbol *Sym = Entry.getValue();
    120 
    121   if (Sym)
    122     return Sym;
    123 
    124   Sym = CreateSymbol(Name);
    125   Entry.setValue(Sym);
    126   return Sym;
    127 }
    128 
    129 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
    130   // Determine whether this is an assembler temporary or normal label, if used.
    131   bool isTemporary = false;
    132   if (AllowTemporaryLabels)
    133     isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
    134 
    135   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
    136   if (NameEntry->getValue()) {
    137     assert(isTemporary && "Cannot rename non temporary symbols");
    138     SmallString<128> NewName = Name;
    139     do {
    140       NewName.resize(Name.size());
    141       raw_svector_ostream(NewName) << NextUniqueID++;
    142       NameEntry = &UsedNames.GetOrCreateValue(NewName);
    143     } while (NameEntry->getValue());
    144   }
    145   NameEntry->setValue(true);
    146 
    147   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
    148   // to the copy of the string that is embedded in the UsedNames entry.
    149   MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
    150 
    151   return Result;
    152 }
    153 
    154 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
    155   SmallString<128> NameSV;
    156   Name.toVector(NameSV);
    157   return GetOrCreateSymbol(NameSV.str());
    158 }
    159 
    160 MCSymbol *MCContext::CreateTempSymbol() {
    161   SmallString<128> NameSV;
    162   raw_svector_ostream(NameSV)
    163     << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
    164   return CreateSymbol(NameSV);
    165 }
    166 
    167 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
    168   MCLabel *&Label = Instances[LocalLabelVal];
    169   if (!Label)
    170     Label = new (*this) MCLabel(0);
    171   return Label->incInstance();
    172 }
    173 
    174 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
    175   MCLabel *&Label = Instances[LocalLabelVal];
    176   if (!Label)
    177     Label = new (*this) MCLabel(0);
    178   return Label->getInstance();
    179 }
    180 
    181 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
    182   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
    183                            Twine(LocalLabelVal) +
    184                            "\2" +
    185                            Twine(NextInstance(LocalLabelVal)));
    186 }
    187 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
    188                                                int bORf) {
    189   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
    190                            Twine(LocalLabelVal) +
    191                            "\2" +
    192                            Twine(GetInstance(LocalLabelVal) + bORf));
    193 }
    194 
    195 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
    196   return Symbols.lookup(Name);
    197 }
    198 
    199 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
    200   SmallString<128> NameSV;
    201   Name.toVector(NameSV);
    202   return LookupSymbol(NameSV.str());
    203 }
    204 
    205 //===----------------------------------------------------------------------===//
    206 // Section Management
    207 //===----------------------------------------------------------------------===//
    208 
    209 const MCSectionMachO *MCContext::
    210 getMachOSection(StringRef Segment, StringRef Section,
    211                 unsigned TypeAndAttributes,
    212                 unsigned Reserved2, SectionKind Kind) {
    213 
    214   // We unique sections by their segment/section pair.  The returned section
    215   // may not have the same flags as the requested section, if so this should be
    216   // diagnosed by the client as an error.
    217 
    218   // Create the map if it doesn't already exist.
    219   if (MachOUniquingMap == 0)
    220     MachOUniquingMap = new MachOUniqueMapTy();
    221   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
    222 
    223   // Form the name to look up.
    224   SmallString<64> Name;
    225   Name += Segment;
    226   Name.push_back(',');
    227   Name += Section;
    228 
    229   // Do the lookup, if we have a hit, return it.
    230   const MCSectionMachO *&Entry = Map[Name.str()];
    231   if (Entry) return Entry;
    232 
    233   // Otherwise, return a new section.
    234   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
    235                                             Reserved2, Kind);
    236 }
    237 
    238 const MCSectionELF *MCContext::
    239 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
    240               SectionKind Kind) {
    241   return getELFSection(Section, Type, Flags, Kind, 0, "");
    242 }
    243 
    244 const MCSectionELF *MCContext::
    245 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
    246               SectionKind Kind, unsigned EntrySize, StringRef Group) {
    247   if (ELFUniquingMap == 0)
    248     ELFUniquingMap = new ELFUniqueMapTy();
    249   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
    250 
    251   // Do the lookup, if we have a hit, return it.
    252   StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
    253   if (Entry.getValue()) return Entry.getValue();
    254 
    255   // Possibly refine the entry size first.
    256   if (!EntrySize) {
    257     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
    258   }
    259 
    260   MCSymbol *GroupSym = NULL;
    261   if (!Group.empty())
    262     GroupSym = GetOrCreateSymbol(Group);
    263 
    264   MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
    265                                                   Kind, EntrySize, GroupSym);
    266   Entry.setValue(Result);
    267   return Result;
    268 }
    269 
    270 const MCSectionELF *MCContext::CreateELFGroupSection() {
    271   MCSectionELF *Result =
    272     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
    273                              SectionKind::getReadOnly(), 4, NULL);
    274   return Result;
    275 }
    276 
    277 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
    278                                                unsigned Characteristics,
    279                                                SectionKind Kind, int Selection,
    280                                                const MCSectionCOFF *Assoc) {
    281   if (COFFUniquingMap == 0)
    282     COFFUniquingMap = new COFFUniqueMapTy();
    283   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
    284 
    285   // Do the lookup, if we have a hit, return it.
    286   StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
    287   if (Entry.getValue()) return Entry.getValue();
    288 
    289   MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
    290                                                     Characteristics,
    291                                                     Selection, Assoc, Kind);
    292 
    293   Entry.setValue(Result);
    294   return Result;
    295 }
    296 
    297 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
    298   if (COFFUniquingMap == 0)
    299     COFFUniquingMap = new COFFUniqueMapTy();
    300   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
    301 
    302   return Map.lookup(Section);
    303 }
    304 
    305 //===----------------------------------------------------------------------===//
    306 // Dwarf Management
    307 //===----------------------------------------------------------------------===//
    308 
    309 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
    310 /// directory tables.  If the file number has already been allocated it is an
    311 /// error and zero is returned and the client reports the error, else the
    312 /// allocated file number is returned.  The file numbers may be in any order.
    313 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
    314                                  unsigned FileNumber, unsigned CUID) {
    315   // TODO: a FileNumber of zero says to use the next available file number.
    316   // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
    317   // to not be less than one.  This needs to be change to be not less than zero.
    318 
    319   SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
    320   SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
    321   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
    322   if (FileNumber >= MCDwarfFiles.size()) {
    323     MCDwarfFiles.resize(FileNumber + 1);
    324   } else {
    325     MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
    326     if (ExistingFile)
    327       // It is an error to use see the same number more than once.
    328       return 0;
    329   }
    330 
    331   // Get the new MCDwarfFile slot for this FileNumber.
    332   MCDwarfFile *&File = MCDwarfFiles[FileNumber];
    333 
    334   if (Directory.empty()) {
    335     // Separate the directory part from the basename of the FileName.
    336     StringRef tFileName = sys::path::filename(FileName);
    337     if (!tFileName.empty()) {
    338       Directory = sys::path::parent_path(FileName);
    339       if (!Directory.empty())
    340         FileName = tFileName;
    341     }
    342   }
    343 
    344   // Find or make a entry in the MCDwarfDirs vector for this Directory.
    345   // Capture directory name.
    346   unsigned DirIndex;
    347   if (Directory.empty()) {
    348     // For FileNames with no directories a DirIndex of 0 is used.
    349     DirIndex = 0;
    350   } else {
    351     DirIndex = 0;
    352     for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
    353       if (Directory == MCDwarfDirs[DirIndex])
    354         break;
    355     }
    356     if (DirIndex >= MCDwarfDirs.size()) {
    357       char *Buf = static_cast<char *>(Allocate(Directory.size()));
    358       memcpy(Buf, Directory.data(), Directory.size());
    359       MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
    360     }
    361     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
    362     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
    363     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
    364     // are stored at MCDwarfFiles[FileNumber].Name .
    365     DirIndex++;
    366   }
    367 
    368   // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
    369   // vector.
    370   char *Buf = static_cast<char *>(Allocate(FileName.size()));
    371   memcpy(Buf, FileName.data(), FileName.size());
    372   File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
    373 
    374   // return the allocated FileNumber.
    375   return FileNumber;
    376 }
    377 
    378 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
    379 /// currently is assigned and false otherwise.
    380 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
    381   SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
    382   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
    383     return false;
    384 
    385   return MCDwarfFiles[FileNumber] != 0;
    386 }
    387 
    388 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
    389   // If we have a source manager and a location, use it. Otherwise just
    390   // use the generic report_fatal_error().
    391   if (!SrcMgr || Loc == SMLoc())
    392     report_fatal_error(Msg);
    393 
    394   // Use the source manager to print the message.
    395   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
    396 
    397   // If we reached here, we are failing ungracefully. Run the interrupt handlers
    398   // to make sure any special cleanups get done, in particular that we remove
    399   // files registered with RemoveFileOnSignal.
    400   sys::RunInterruptHandlers();
    401   exit(1);
    402 }
    403