Home | History | Annotate | Download | only in MC
      1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
      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/MCDwarf.h"
     11 #include "llvm/MC/MCAsmInfo.h"
     12 #include "llvm/MC/MCContext.h"
     13 #include "llvm/MC/MCObjectFileInfo.h"
     14 #include "llvm/MC/MCObjectWriter.h"
     15 #include "llvm/MC/MCRegisterInfo.h"
     16 #include "llvm/MC/MCStreamer.h"
     17 #include "llvm/MC/MCSymbol.h"
     18 #include "llvm/MC/MCExpr.h"
     19 #include "llvm/Support/Debug.h"
     20 #include "llvm/Support/ErrorHandling.h"
     21 #include "llvm/Support/raw_ostream.h"
     22 #include "llvm/ADT/FoldingSet.h"
     23 #include "llvm/ADT/SmallString.h"
     24 #include "llvm/ADT/StringExtras.h"
     25 #include "llvm/ADT/Twine.h"
     26 using namespace llvm;
     27 
     28 // Given a special op, return the address skip amount (in units of
     29 // DWARF2_LINE_MIN_INSN_LENGTH.
     30 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
     31 
     32 // The maximum address skip amount that can be encoded with a special op.
     33 #define MAX_SPECIAL_ADDR_DELTA         SPECIAL_ADDR(255)
     34 
     35 // First special line opcode - leave room for the standard opcodes.
     36 // Note: If you want to change this, you'll have to update the
     37 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
     38 #define DWARF2_LINE_OPCODE_BASE         13
     39 
     40 // Minimum line offset in a special line info. opcode.  This value
     41 // was chosen to give a reasonable range of values.
     42 #define DWARF2_LINE_BASE                -5
     43 
     44 // Range of line offsets in a special line info. opcode.
     45 #define DWARF2_LINE_RANGE               14
     46 
     47 // Define the architecture-dependent minimum instruction length (in bytes).
     48 // This value should be rather too small than too big.
     49 #define DWARF2_LINE_MIN_INSN_LENGTH     1
     50 
     51 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
     52 // this routine is a nop and will be optimized away.
     53 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
     54   if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
     55     return AddrDelta;
     56   if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
     57     // TODO: report this error, but really only once.
     58     ;
     59   }
     60   return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
     61 }
     62 
     63 //
     64 // This is called when an instruction is assembled into the specified section
     65 // and if there is information from the last .loc directive that has yet to have
     66 // a line entry made for it is made.
     67 //
     68 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
     69   if (!MCOS->getContext().getDwarfLocSeen())
     70     return;
     71 
     72   // Create a symbol at in the current section for use in the line entry.
     73   MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
     74   // Set the value of the symbol to use for the MCLineEntry.
     75   MCOS->EmitLabel(LineSym);
     76 
     77   // Get the current .loc info saved in the context.
     78   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
     79 
     80   // Create a (local) line entry with the symbol and the current .loc info.
     81   MCLineEntry LineEntry(LineSym, DwarfLoc);
     82 
     83   // clear DwarfLocSeen saying the current .loc info is now used.
     84   MCOS->getContext().ClearDwarfLocSeen();
     85 
     86   // Get the MCLineSection for this section, if one does not exist for this
     87   // section create it.
     88   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
     89     MCOS->getContext().getMCLineSections();
     90   MCLineSection *LineSection = MCLineSections.lookup(Section);
     91   if (!LineSection) {
     92     // Create a new MCLineSection.  This will be deleted after the dwarf line
     93     // table is created using it by iterating through the MCLineSections
     94     // DenseMap.
     95     LineSection = new MCLineSection;
     96     // Save a pointer to the new LineSection into the MCLineSections DenseMap.
     97     MCOS->getContext().addMCLineSection(Section, LineSection);
     98   }
     99 
    100   // Add the line entry to this section's entries.
    101   LineSection->addLineEntry(LineEntry);
    102 }
    103 
    104 //
    105 // This helper routine returns an expression of End - Start + IntVal .
    106 //
    107 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
    108                                                   const MCSymbol &Start,
    109                                                   const MCSymbol &End,
    110                                                   int IntVal) {
    111   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
    112   const MCExpr *Res =
    113     MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
    114   const MCExpr *RHS =
    115     MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
    116   const MCExpr *Res1 =
    117     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
    118   const MCExpr *Res2 =
    119     MCConstantExpr::Create(IntVal, MCOS.getContext());
    120   const MCExpr *Res3 =
    121     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
    122   return Res3;
    123 }
    124 
    125 //
    126 // This emits the Dwarf line table for the specified section from the entries
    127 // in the LineSection.
    128 //
    129 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
    130                                       const MCSection *Section,
    131                                       const MCLineSection *LineSection) {
    132   unsigned FileNum = 1;
    133   unsigned LastLine = 1;
    134   unsigned Column = 0;
    135   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
    136   unsigned Isa = 0;
    137   MCSymbol *LastLabel = NULL;
    138 
    139   // Loop through each MCLineEntry and encode the dwarf line number table.
    140   for (MCLineSection::const_iterator
    141          it = LineSection->getMCLineEntries()->begin(),
    142          ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
    143 
    144     if (FileNum != it->getFileNum()) {
    145       FileNum = it->getFileNum();
    146       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
    147       MCOS->EmitULEB128IntValue(FileNum);
    148     }
    149     if (Column != it->getColumn()) {
    150       Column = it->getColumn();
    151       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
    152       MCOS->EmitULEB128IntValue(Column);
    153     }
    154     if (Isa != it->getIsa()) {
    155       Isa = it->getIsa();
    156       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
    157       MCOS->EmitULEB128IntValue(Isa);
    158     }
    159     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
    160       Flags = it->getFlags();
    161       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
    162     }
    163     if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
    164       MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
    165     if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
    166       MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
    167     if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
    168       MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
    169 
    170     int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
    171     MCSymbol *Label = it->getLabel();
    172 
    173     // At this point we want to emit/create the sequence to encode the delta in
    174     // line numbers and the increment of the address from the previous Label
    175     // and the current Label.
    176     const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
    177     MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
    178                                    asmInfo.getPointerSize());
    179 
    180     LastLine = it->getLine();
    181     LastLabel = Label;
    182   }
    183 
    184   // Emit a DW_LNE_end_sequence for the end of the section.
    185   // Using the pointer Section create a temporary label at the end of the
    186   // section and use that and the LastLabel to compute the address delta
    187   // and use INT64_MAX as the line delta which is the signal that this is
    188   // actually a DW_LNE_end_sequence.
    189 
    190   // Switch to the section to be able to create a symbol at its end.
    191   MCOS->SwitchSection(Section);
    192 
    193   MCContext &context = MCOS->getContext();
    194   // Create a symbol at the end of the section.
    195   MCSymbol *SectionEnd = context.CreateTempSymbol();
    196   // Set the value of the symbol, as we are at the end of the section.
    197   MCOS->EmitLabel(SectionEnd);
    198 
    199   // Switch back the the dwarf line section.
    200   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
    201 
    202   const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
    203   MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
    204                                  asmInfo.getPointerSize());
    205 }
    206 
    207 //
    208 // This emits the Dwarf file and the line tables.
    209 //
    210 void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
    211   MCContext &context = MCOS->getContext();
    212   // Switch to the section where the table will be emitted into.
    213   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
    214 
    215   // Create a symbol at the beginning of this section.
    216   MCSymbol *LineStartSym = context.CreateTempSymbol();
    217   // Set the value of the symbol, as we are at the start of the section.
    218   MCOS->EmitLabel(LineStartSym);
    219 
    220   // Create a symbol for the end of the section (to be set when we get there).
    221   MCSymbol *LineEndSym = context.CreateTempSymbol();
    222 
    223   // The first 4 bytes is the total length of the information for this
    224   // compilation unit (not including these 4 bytes for the length).
    225   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
    226                      4);
    227 
    228   // Next 2 bytes is the Version, which is Dwarf 2.
    229   MCOS->EmitIntValue(2, 2);
    230 
    231   // Create a symbol for the end of the prologue (to be set when we get there).
    232   MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
    233 
    234   // Length of the prologue, is the next 4 bytes.  Which is the start of the
    235   // section to the end of the prologue.  Not including the 4 bytes for the
    236   // total length, the 2 bytes for the version, and these 4 bytes for the
    237   // length of the prologue.
    238   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
    239                                         (4 + 2 + 4)),
    240                   4, 0);
    241 
    242   // Parameters of the state machine, are next.
    243   MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
    244   MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
    245   MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
    246   MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
    247   MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
    248 
    249   // Standard opcode lengths
    250   MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
    251   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
    252   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
    253   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
    254   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
    255   MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
    256   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
    257   MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
    258   MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
    259   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
    260   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
    261   MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
    262 
    263   // Put out the directory and file tables.
    264 
    265   // First the directory table.
    266   const std::vector<StringRef> &MCDwarfDirs =
    267     context.getMCDwarfDirs();
    268   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
    269     MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
    270     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
    271   }
    272   MCOS->EmitIntValue(0, 1); // Terminate the directory list
    273 
    274   // Second the file table.
    275   const std::vector<MCDwarfFile *> &MCDwarfFiles =
    276     MCOS->getContext().getMCDwarfFiles();
    277   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
    278     MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
    279     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
    280     // the Directory num
    281     MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
    282     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
    283     MCOS->EmitIntValue(0, 1); // filesize (always 0)
    284   }
    285   MCOS->EmitIntValue(0, 1); // Terminate the file list
    286 
    287   // This is the end of the prologue, so set the value of the symbol at the
    288   // end of the prologue (that was used in a previous expression).
    289   MCOS->EmitLabel(ProEndSym);
    290 
    291   // Put out the line tables.
    292   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
    293     MCOS->getContext().getMCLineSections();
    294   const std::vector<const MCSection *> &MCLineSectionOrder =
    295     MCOS->getContext().getMCLineSectionOrder();
    296   for (std::vector<const MCSection*>::const_iterator it =
    297          MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
    298        ++it) {
    299     const MCSection *Sec = *it;
    300     const MCLineSection *Line = MCLineSections.lookup(Sec);
    301     EmitDwarfLineTable(MCOS, Sec, Line);
    302 
    303     // Now delete the MCLineSections that were created in MCLineEntry::Make()
    304     // and used to emit the line table.
    305     delete Line;
    306   }
    307 
    308   if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
    309       && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
    310     // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
    311     // it requires:
    312     // total_length >= prologue_length + 10
    313     // We are 4 bytes short, since we have total_length = 51 and
    314     // prologue_length = 45
    315 
    316     // The regular end_sequence should be sufficient.
    317     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
    318   }
    319 
    320   // This is the end of the section, so set the value of the symbol at the end
    321   // of this section (that was used in a previous expression).
    322   MCOS->EmitLabel(LineEndSym);
    323 }
    324 
    325 /// Utility function to write the encoding to an object writer.
    326 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
    327                             uint64_t AddrDelta) {
    328   SmallString<256> Tmp;
    329   raw_svector_ostream OS(Tmp);
    330   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
    331   OW->WriteBytes(OS.str());
    332 }
    333 
    334 /// Utility function to emit the encoding to a streamer.
    335 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
    336                            uint64_t AddrDelta) {
    337   SmallString<256> Tmp;
    338   raw_svector_ostream OS(Tmp);
    339   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
    340   MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
    341 }
    342 
    343 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
    344 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
    345                              raw_ostream &OS) {
    346   uint64_t Temp, Opcode;
    347   bool NeedCopy = false;
    348 
    349   // Scale the address delta by the minimum instruction length.
    350   AddrDelta = ScaleAddrDelta(AddrDelta);
    351 
    352   // A LineDelta of INT64_MAX is a signal that this is actually a
    353   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
    354   // end_sequence to emit the matrix entry.
    355   if (LineDelta == INT64_MAX) {
    356     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
    357       OS << char(dwarf::DW_LNS_const_add_pc);
    358     else {
    359       OS << char(dwarf::DW_LNS_advance_pc);
    360       MCObjectWriter::EncodeULEB128(AddrDelta, OS);
    361     }
    362     OS << char(dwarf::DW_LNS_extended_op);
    363     OS << char(1);
    364     OS << char(dwarf::DW_LNE_end_sequence);
    365     return;
    366   }
    367 
    368   // Bias the line delta by the base.
    369   Temp = LineDelta - DWARF2_LINE_BASE;
    370 
    371   // If the line increment is out of range of a special opcode, we must encode
    372   // it with DW_LNS_advance_line.
    373   if (Temp >= DWARF2_LINE_RANGE) {
    374     OS << char(dwarf::DW_LNS_advance_line);
    375     SmallString<32> Tmp;
    376     raw_svector_ostream OSE(Tmp);
    377     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
    378     OS << OSE.str();
    379 
    380     LineDelta = 0;
    381     Temp = 0 - DWARF2_LINE_BASE;
    382     NeedCopy = true;
    383   }
    384 
    385   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
    386   if (LineDelta == 0 && AddrDelta == 0) {
    387     OS << char(dwarf::DW_LNS_copy);
    388     return;
    389   }
    390 
    391   // Bias the opcode by the special opcode base.
    392   Temp += DWARF2_LINE_OPCODE_BASE;
    393 
    394   // Avoid overflow when addr_delta is large.
    395   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
    396     // Try using a special opcode.
    397     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
    398     if (Opcode <= 255) {
    399       OS << char(Opcode);
    400       return;
    401     }
    402 
    403     // Try using DW_LNS_const_add_pc followed by special op.
    404     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
    405     if (Opcode <= 255) {
    406       OS << char(dwarf::DW_LNS_const_add_pc);
    407       OS << char(Opcode);
    408       return;
    409     }
    410   }
    411 
    412   // Otherwise use DW_LNS_advance_pc.
    413   OS << char(dwarf::DW_LNS_advance_pc);
    414   SmallString<32> Tmp;
    415   raw_svector_ostream OSE(Tmp);
    416   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
    417   OS << OSE.str();
    418 
    419   if (NeedCopy)
    420     OS << char(dwarf::DW_LNS_copy);
    421   else
    422     OS << char(Temp);
    423 }
    424 
    425 void MCDwarfFile::print(raw_ostream &OS) const {
    426   OS << '"' << getName() << '"';
    427 }
    428 
    429 void MCDwarfFile::dump() const {
    430   print(dbgs());
    431 }
    432 
    433 static int getDataAlignmentFactor(MCStreamer &streamer) {
    434   MCContext &context = streamer.getContext();
    435   const MCAsmInfo &asmInfo = context.getAsmInfo();
    436   int size = asmInfo.getPointerSize();
    437   if (asmInfo.isStackGrowthDirectionUp())
    438     return size;
    439   else
    440     return -size;
    441 }
    442 
    443 static unsigned getSizeForEncoding(MCStreamer &streamer,
    444                                    unsigned symbolEncoding) {
    445   MCContext &context = streamer.getContext();
    446   unsigned format = symbolEncoding & 0x0f;
    447   switch (format) {
    448   default:
    449     assert(0 && "Unknown Encoding");
    450   case dwarf::DW_EH_PE_absptr:
    451   case dwarf::DW_EH_PE_signed:
    452     return context.getAsmInfo().getPointerSize();
    453   case dwarf::DW_EH_PE_udata2:
    454   case dwarf::DW_EH_PE_sdata2:
    455     return 2;
    456   case dwarf::DW_EH_PE_udata4:
    457   case dwarf::DW_EH_PE_sdata4:
    458     return 4;
    459   case dwarf::DW_EH_PE_udata8:
    460   case dwarf::DW_EH_PE_sdata8:
    461     return 8;
    462   }
    463 }
    464 
    465 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
    466                        unsigned symbolEncoding, const char *comment = 0) {
    467   MCContext &context = streamer.getContext();
    468   const MCAsmInfo &asmInfo = context.getAsmInfo();
    469   const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
    470                                                 symbolEncoding,
    471                                                 streamer);
    472   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
    473   if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
    474   streamer.EmitAbsValue(v, size);
    475 }
    476 
    477 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
    478                             unsigned symbolEncoding) {
    479   MCContext &context = streamer.getContext();
    480   const MCAsmInfo &asmInfo = context.getAsmInfo();
    481   const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
    482                                                         symbolEncoding,
    483                                                         streamer);
    484   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
    485   streamer.EmitValue(v, size);
    486 }
    487 
    488 static const MachineLocation TranslateMachineLocation(
    489                                                   const MCRegisterInfo &MRI,
    490                                                   const MachineLocation &Loc) {
    491   unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
    492     MachineLocation::VirtualFP :
    493     unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
    494   const MachineLocation &NewLoc = Loc.isReg() ?
    495     MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
    496   return NewLoc;
    497 }
    498 
    499 namespace {
    500   class FrameEmitterImpl {
    501     int CFAOffset;
    502     int CIENum;
    503     bool UsingCFI;
    504     bool IsEH;
    505     const MCSymbol *SectionStart;
    506   public:
    507     FrameEmitterImpl(bool usingCFI, bool isEH)
    508       : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
    509         SectionStart(0) {}
    510 
    511     void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
    512 
    513     /// EmitCompactUnwind - Emit the unwind information in a compact way. If
    514     /// we're successful, return 'true'. Otherwise, return 'false' and it will
    515     /// emit the normal CIE and FDE.
    516     bool EmitCompactUnwind(MCStreamer &streamer,
    517                            const MCDwarfFrameInfo &frame);
    518 
    519     const MCSymbol &EmitCIE(MCStreamer &streamer,
    520                             const MCSymbol *personality,
    521                             unsigned personalityEncoding,
    522                             const MCSymbol *lsda,
    523                             unsigned lsdaEncoding);
    524     MCSymbol *EmitFDE(MCStreamer &streamer,
    525                       const MCSymbol &cieStart,
    526                       const MCDwarfFrameInfo &frame);
    527     void EmitCFIInstructions(MCStreamer &streamer,
    528                              const std::vector<MCCFIInstruction> &Instrs,
    529                              MCSymbol *BaseLabel);
    530     void EmitCFIInstruction(MCStreamer &Streamer,
    531                             const MCCFIInstruction &Instr);
    532   };
    533 
    534 } // end anonymous namespace
    535 
    536 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
    537                              StringRef Prefix) {
    538   if (Streamer.isVerboseAsm()) {
    539     const char *EncStr = 0;
    540     switch (Encoding) {
    541     default: EncStr = "<unknown encoding>";
    542     case dwarf::DW_EH_PE_absptr: EncStr = "absptr";
    543     case dwarf::DW_EH_PE_omit:   EncStr = "omit";
    544     case dwarf::DW_EH_PE_pcrel:  EncStr = "pcrel";
    545     case dwarf::DW_EH_PE_udata4: EncStr = "udata4";
    546     case dwarf::DW_EH_PE_udata8: EncStr = "udata8";
    547     case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4";
    548     case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8";
    549     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4";
    550     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4";
    551     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8";
    552     case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr = "pcrel sdata8";
    553     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
    554       EncStr = "indirect pcrel udata4";
    555     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
    556       EncStr = "indirect pcrel sdata4";
    557     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
    558       EncStr = "indirect pcrel udata8";
    559     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
    560       EncStr = "indirect pcrel sdata8";
    561     }
    562 
    563     Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
    564   }
    565 
    566   Streamer.EmitIntValue(Encoding, 1);
    567 }
    568 
    569 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
    570                                           const MCCFIInstruction &Instr) {
    571   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
    572   bool VerboseAsm = Streamer.isVerboseAsm();
    573 
    574   switch (Instr.getOperation()) {
    575   case MCCFIInstruction::Move:
    576   case MCCFIInstruction::RelMove: {
    577     const MachineLocation &Dst = Instr.getDestination();
    578     const MachineLocation &Src = Instr.getSource();
    579     const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
    580 
    581     // If advancing cfa.
    582     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
    583       if (Src.getReg() == MachineLocation::VirtualFP) {
    584         if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
    585         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
    586       } else {
    587         if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
    588         Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
    589         if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
    590                                             Twine(Src.getReg()));
    591         Streamer.EmitULEB128IntValue(Src.getReg());
    592       }
    593 
    594       if (IsRelative)
    595         CFAOffset += Src.getOffset();
    596       else
    597         CFAOffset = -Src.getOffset();
    598 
    599       if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
    600       Streamer.EmitULEB128IntValue(CFAOffset);
    601       return;
    602     }
    603 
    604     if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
    605       assert(Dst.isReg() && "Machine move not supported yet.");
    606       if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
    607       Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
    608       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
    609       Streamer.EmitULEB128IntValue(Dst.getReg());
    610       return;
    611     }
    612 
    613     unsigned Reg = Src.getReg();
    614     int Offset = Dst.getOffset();
    615     if (IsRelative)
    616       Offset -= CFAOffset;
    617     Offset = Offset / dataAlignmentFactor;
    618 
    619     if (Offset < 0) {
    620       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
    621       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
    622       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    623       Streamer.EmitULEB128IntValue(Reg);
    624       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    625       Streamer.EmitSLEB128IntValue(Offset);
    626     } else if (Reg < 64) {
    627       if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
    628                                           Twine(Reg) + ")");
    629       Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
    630       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    631       Streamer.EmitULEB128IntValue(Offset);
    632     } else {
    633       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
    634       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
    635       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    636       Streamer.EmitULEB128IntValue(Reg);
    637       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
    638       Streamer.EmitULEB128IntValue(Offset);
    639     }
    640     return;
    641   }
    642   case MCCFIInstruction::Remember:
    643     if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
    644     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
    645     return;
    646   case MCCFIInstruction::Restore:
    647     if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
    648     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
    649     return;
    650   case MCCFIInstruction::SameValue: {
    651     unsigned Reg = Instr.getDestination().getReg();
    652     if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
    653     Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
    654     if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
    655     Streamer.EmitULEB128IntValue(Reg);
    656     return;
    657   }
    658   }
    659   llvm_unreachable("Unhandled case in switch");
    660 }
    661 
    662 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
    663 /// frame.
    664 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
    665                                     const std::vector<MCCFIInstruction> &Instrs,
    666                                            MCSymbol *BaseLabel) {
    667   for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
    668     const MCCFIInstruction &Instr = Instrs[i];
    669     MCSymbol *Label = Instr.getLabel();
    670     // Throw out move if the label is invalid.
    671     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
    672 
    673     // Advance row if new location.
    674     if (BaseLabel && Label) {
    675       MCSymbol *ThisSym = Label;
    676       if (ThisSym != BaseLabel) {
    677         if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
    678         streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
    679         BaseLabel = ThisSym;
    680       }
    681     }
    682 
    683     EmitCFIInstruction(streamer, Instr);
    684   }
    685 }
    686 
    687 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
    688 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
    689 /// normal CIE and FDE.
    690 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
    691                                          const MCDwarfFrameInfo &Frame) {
    692   MCContext &Context = Streamer.getContext();
    693   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
    694   bool VerboseAsm = Streamer.isVerboseAsm();
    695 
    696   // range-start range-length  compact-unwind-enc personality-func   lsda
    697   //  _foo       LfooEnd-_foo  0x00000023          0                 0
    698   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
    699   //
    700   //   .section __LD,__compact_unwind,regular,debug
    701   //
    702   //   # compact unwind for _foo
    703   //   .quad _foo
    704   //   .set L1,LfooEnd-_foo
    705   //   .long L1
    706   //   .long 0x01010001
    707   //   .quad 0
    708   //   .quad 0
    709   //
    710   //   # compact unwind for _bar
    711   //   .quad _bar
    712   //   .set L2,LbarEnd-_bar
    713   //   .long L2
    714   //   .long 0x01020011
    715   //   .quad __gxx_personality
    716   //   .quad except_tab1
    717 
    718   uint32_t Encoding = Frame.CompactUnwindEncoding;
    719   if (!Encoding) return false;
    720 
    721   // The encoding needs to know we have an LSDA.
    722   if (Frame.Lsda)
    723     Encoding |= 0x40000000;
    724 
    725   Streamer.SwitchSection(MOFI->getCompactUnwindSection());
    726 
    727   // Range Start
    728   unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
    729   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
    730   if (VerboseAsm) Streamer.AddComment("Range Start");
    731   Streamer.EmitSymbolValue(Frame.Function, Size);
    732 
    733   // Range Length
    734   const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
    735                                               *Frame.End, 0);
    736   if (VerboseAsm) Streamer.AddComment("Range Length");
    737   Streamer.EmitAbsValue(Range, 4);
    738 
    739   // Compact Encoding
    740   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
    741   if (VerboseAsm) Streamer.AddComment(Twine("Compact Unwind Encoding: 0x") +
    742                                       Twine(llvm::utohexstr(Encoding)));
    743   Streamer.EmitIntValue(Encoding, Size);
    744 
    745 
    746   // Personality Function
    747   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
    748   if (VerboseAsm) Streamer.AddComment("Personality Function");
    749   if (Frame.Personality)
    750     Streamer.EmitSymbolValue(Frame.Personality, Size);
    751   else
    752     Streamer.EmitIntValue(0, Size); // No personality fn
    753 
    754   // LSDA
    755   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
    756   if (VerboseAsm) Streamer.AddComment("LSDA");
    757   if (Frame.Lsda)
    758     Streamer.EmitSymbolValue(Frame.Lsda, Size);
    759   else
    760     Streamer.EmitIntValue(0, Size); // No LSDA
    761 
    762   return true;
    763 }
    764 
    765 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
    766                                           const MCSymbol *personality,
    767                                           unsigned personalityEncoding,
    768                                           const MCSymbol *lsda,
    769                                           unsigned lsdaEncoding) {
    770   MCContext &context = streamer.getContext();
    771   const MCRegisterInfo &MRI = context.getRegisterInfo();
    772   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
    773   bool verboseAsm = streamer.isVerboseAsm();
    774 
    775   MCSymbol *sectionStart;
    776   if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
    777     sectionStart = context.CreateTempSymbol();
    778   else
    779     sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
    780 
    781   streamer.EmitLabel(sectionStart);
    782   CIENum++;
    783 
    784   MCSymbol *sectionEnd = context.CreateTempSymbol();
    785 
    786   // Length
    787   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
    788                                                *sectionEnd, 4);
    789   if (verboseAsm) streamer.AddComment("CIE Length");
    790   streamer.EmitAbsValue(Length, 4);
    791 
    792   // CIE ID
    793   unsigned CIE_ID = IsEH ? 0 : -1;
    794   if (verboseAsm) streamer.AddComment("CIE ID Tag");
    795   streamer.EmitIntValue(CIE_ID, 4);
    796 
    797   // Version
    798   if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
    799   streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
    800 
    801   // Augmentation String
    802   SmallString<8> Augmentation;
    803   if (IsEH) {
    804     if (verboseAsm) streamer.AddComment("CIE Augmentation");
    805     Augmentation += "z";
    806     if (personality)
    807       Augmentation += "P";
    808     if (lsda)
    809       Augmentation += "L";
    810     Augmentation += "R";
    811     streamer.EmitBytes(Augmentation.str(), 0);
    812   }
    813   streamer.EmitIntValue(0, 1);
    814 
    815   // Code Alignment Factor
    816   if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
    817   streamer.EmitULEB128IntValue(1);
    818 
    819   // Data Alignment Factor
    820   if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
    821   streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
    822 
    823   // Return Address Register
    824   if (verboseAsm) streamer.AddComment("CIE Return Address Column");
    825   streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
    826 
    827   // Augmentation Data Length (optional)
    828 
    829   unsigned augmentationLength = 0;
    830   if (IsEH) {
    831     if (personality) {
    832       // Personality Encoding
    833       augmentationLength += 1;
    834       // Personality
    835       augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
    836     }
    837     if (lsda)
    838       augmentationLength += 1;
    839     // Encoding of the FDE pointers
    840     augmentationLength += 1;
    841 
    842     if (verboseAsm) streamer.AddComment("Augmentation Size");
    843     streamer.EmitULEB128IntValue(augmentationLength);
    844 
    845     // Augmentation Data (optional)
    846     if (personality) {
    847       // Personality Encoding
    848       EmitEncodingByte(streamer, personalityEncoding,
    849                        "Personality Encoding");
    850       // Personality
    851       if (verboseAsm) streamer.AddComment("Personality");
    852       EmitPersonality(streamer, *personality, personalityEncoding);
    853     }
    854 
    855     if (lsda)
    856       EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
    857 
    858     // Encoding of the FDE pointers
    859     EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
    860                      "FDE Encoding");
    861   }
    862 
    863   // Initial Instructions
    864 
    865   const MCAsmInfo &MAI = context.getAsmInfo();
    866   const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
    867   std::vector<MCCFIInstruction> Instructions;
    868 
    869   for (int i = 0, n = Moves.size(); i != n; ++i) {
    870     MCSymbol *Label = Moves[i].getLabel();
    871     const MachineLocation &Dst =
    872       TranslateMachineLocation(MRI, Moves[i].getDestination());
    873     const MachineLocation &Src =
    874       TranslateMachineLocation(MRI, Moves[i].getSource());
    875     MCCFIInstruction Inst(Label, Dst, Src);
    876     Instructions.push_back(Inst);
    877   }
    878 
    879   EmitCFIInstructions(streamer, Instructions, NULL);
    880 
    881   // Padding
    882   streamer.EmitValueToAlignment(IsEH
    883                                 ? 4 : context.getAsmInfo().getPointerSize());
    884 
    885   streamer.EmitLabel(sectionEnd);
    886   return *sectionStart;
    887 }
    888 
    889 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
    890                                     const MCSymbol &cieStart,
    891                                     const MCDwarfFrameInfo &frame) {
    892   MCContext &context = streamer.getContext();
    893   MCSymbol *fdeStart = context.CreateTempSymbol();
    894   MCSymbol *fdeEnd = context.CreateTempSymbol();
    895   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
    896   bool verboseAsm = streamer.isVerboseAsm();
    897 
    898   if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
    899     MCSymbol *EHSym =
    900       context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
    901     streamer.EmitEHSymAttributes(frame.Function, EHSym);
    902     streamer.EmitLabel(EHSym);
    903   }
    904 
    905   // Length
    906   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
    907   if (verboseAsm) streamer.AddComment("FDE Length");
    908   streamer.EmitAbsValue(Length, 4);
    909 
    910   streamer.EmitLabel(fdeStart);
    911 
    912   // CIE Pointer
    913   const MCAsmInfo &asmInfo = context.getAsmInfo();
    914   if (IsEH) {
    915     const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
    916                                                  0);
    917     if (verboseAsm) streamer.AddComment("FDE CIE Offset");
    918     streamer.EmitAbsValue(offset, 4);
    919   } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
    920     const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
    921                                                  cieStart, 0);
    922     streamer.EmitAbsValue(offset, 4);
    923   } else {
    924     streamer.EmitSymbolValue(&cieStart, 4);
    925   }
    926 
    927   unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI);
    928   unsigned size = getSizeForEncoding(streamer, fdeEncoding);
    929 
    930   // PC Begin
    931   unsigned PCBeginEncoding = IsEH ? fdeEncoding :
    932     (unsigned)dwarf::DW_EH_PE_absptr;
    933   unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
    934   EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
    935 
    936   // PC Range
    937   const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
    938                                               *frame.End, 0);
    939   if (verboseAsm) streamer.AddComment("FDE address range");
    940   streamer.EmitAbsValue(Range, size);
    941 
    942   if (IsEH) {
    943     // Augmentation Data Length
    944     unsigned augmentationLength = 0;
    945 
    946     if (frame.Lsda)
    947       augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
    948 
    949     if (verboseAsm) streamer.AddComment("Augmentation size");
    950     streamer.EmitULEB128IntValue(augmentationLength);
    951 
    952     // Augmentation Data
    953     if (frame.Lsda)
    954       EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
    955                  "Language Specific Data Area");
    956   }
    957 
    958   // Call Frame Instructions
    959 
    960   EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
    961 
    962   // Padding
    963   streamer.EmitValueToAlignment(PCBeginSize);
    964 
    965   return fdeEnd;
    966 }
    967 
    968 namespace {
    969   struct CIEKey {
    970     static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
    971     static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
    972 
    973     CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
    974            unsigned LsdaEncoding_) : Personality(Personality_),
    975                                      PersonalityEncoding(PersonalityEncoding_),
    976                                      LsdaEncoding(LsdaEncoding_) {
    977     }
    978     const MCSymbol* Personality;
    979     unsigned PersonalityEncoding;
    980     unsigned LsdaEncoding;
    981   };
    982 }
    983 
    984 namespace llvm {
    985   template <>
    986   struct DenseMapInfo<CIEKey> {
    987     static CIEKey getEmptyKey() {
    988       return CIEKey::getEmptyKey();
    989     }
    990     static CIEKey getTombstoneKey() {
    991       return CIEKey::getTombstoneKey();
    992     }
    993     static unsigned getHashValue(const CIEKey &Key) {
    994       FoldingSetNodeID ID;
    995       ID.AddPointer(Key.Personality);
    996       ID.AddInteger(Key.PersonalityEncoding);
    997       ID.AddInteger(Key.LsdaEncoding);
    998       return ID.ComputeHash();
    999     }
   1000     static bool isEqual(const CIEKey &LHS,
   1001                         const CIEKey &RHS) {
   1002       return LHS.Personality == RHS.Personality &&
   1003         LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
   1004         LHS.LsdaEncoding == RHS.LsdaEncoding;
   1005     }
   1006   };
   1007 }
   1008 
   1009 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
   1010                                bool UsingCFI,
   1011                                bool IsEH) {
   1012   MCContext &Context = Streamer.getContext();
   1013   MCObjectFileInfo *MOFI =
   1014     const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
   1015   FrameEmitterImpl Emitter(UsingCFI, IsEH);
   1016   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
   1017 
   1018   // Emit the compact unwind info if available.
   1019   // FIXME: This emits both the compact unwind and the old CIE/FDE
   1020   //        information. Only one of those is needed.
   1021   if (IsEH && MOFI->getCompactUnwindSection())
   1022     for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
   1023       const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
   1024       if (!Frame.CompactUnwindEncoding)
   1025         Emitter.EmitCompactUnwind(Streamer, Frame);
   1026     }
   1027 
   1028   const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
   1029                                     *MOFI->getDwarfFrameSection();
   1030   Streamer.SwitchSection(&Section);
   1031   MCSymbol *SectionStart = Context.CreateTempSymbol();
   1032   Streamer.EmitLabel(SectionStart);
   1033   Emitter.setSectionStart(SectionStart);
   1034 
   1035   MCSymbol *FDEEnd = NULL;
   1036   DenseMap<CIEKey, const MCSymbol*> CIEStarts;
   1037 
   1038   const MCSymbol *DummyDebugKey = NULL;
   1039   for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
   1040     const MCDwarfFrameInfo &Frame = FrameArray[i];
   1041     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
   1042                Frame.LsdaEncoding);
   1043     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
   1044     if (!CIEStart)
   1045       CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
   1046                                   Frame.PersonalityEncoding, Frame.Lsda,
   1047                                   Frame.LsdaEncoding);
   1048 
   1049     FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
   1050 
   1051     if (i != n - 1)
   1052       Streamer.EmitLabel(FDEEnd);
   1053   }
   1054 
   1055   Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
   1056   if (FDEEnd)
   1057     Streamer.EmitLabel(FDEEnd);
   1058 }
   1059 
   1060 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
   1061                                          uint64_t AddrDelta) {
   1062   SmallString<256> Tmp;
   1063   raw_svector_ostream OS(Tmp);
   1064   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
   1065   Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
   1066 }
   1067 
   1068 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
   1069                                            raw_ostream &OS) {
   1070   // FIXME: Assumes the code alignment factor is 1.
   1071   if (AddrDelta == 0) {
   1072   } else if (isUIntN(6, AddrDelta)) {
   1073     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
   1074     OS << Opcode;
   1075   } else if (isUInt<8>(AddrDelta)) {
   1076     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
   1077     OS << uint8_t(AddrDelta);
   1078   } else if (isUInt<16>(AddrDelta)) {
   1079     // FIXME: check what is the correct behavior on a big endian machine.
   1080     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
   1081     OS << uint8_t( AddrDelta       & 0xff);
   1082     OS << uint8_t((AddrDelta >> 8) & 0xff);
   1083   } else {
   1084     // FIXME: check what is the correct behavior on a big endian machine.
   1085     assert(isUInt<32>(AddrDelta));
   1086     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
   1087     OS << uint8_t( AddrDelta        & 0xff);
   1088     OS << uint8_t((AddrDelta >> 8)  & 0xff);
   1089     OS << uint8_t((AddrDelta >> 16) & 0xff);
   1090     OS << uint8_t((AddrDelta >> 24) & 0xff);
   1091 
   1092   }
   1093 }
   1094