Home | History | Annotate | Download | only in MC
      1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
      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/MCObjectStreamer.h"
     11 #include "llvm/ADT/STLExtras.h"
     12 #include "llvm/MC/MCAsmBackend.h"
     13 #include "llvm/MC/MCAsmInfo.h"
     14 #include "llvm/MC/MCAssembler.h"
     15 #include "llvm/MC/MCCodeEmitter.h"
     16 #include "llvm/MC/MCContext.h"
     17 #include "llvm/MC/MCDwarf.h"
     18 #include "llvm/MC/MCExpr.h"
     19 #include "llvm/MC/MCObjectWriter.h"
     20 #include "llvm/MC/MCSection.h"
     21 #include "llvm/MC/MCSymbol.h"
     22 #include "llvm/Support/ErrorHandling.h"
     23 #include "llvm/Support/TargetRegistry.h"
     24 using namespace llvm;
     25 
     26 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
     27                                    raw_pwrite_stream &OS,
     28                                    MCCodeEmitter *Emitter_)
     29     : MCStreamer(Context),
     30       Assembler(new MCAssembler(Context, TAB, *Emitter_,
     31                                 *TAB.createObjectWriter(OS), OS)),
     32       CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
     33 
     34 MCObjectStreamer::~MCObjectStreamer() {
     35   delete &Assembler->getBackend();
     36   delete &Assembler->getEmitter();
     37   delete &Assembler->getWriter();
     38   delete Assembler;
     39 }
     40 
     41 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
     42   if (PendingLabels.size()) {
     43     if (!F) {
     44       F = new MCDataFragment();
     45       CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
     46       F->setParent(CurSectionData);
     47     }
     48     for (MCSymbolData *SD : PendingLabels) {
     49       SD->setFragment(F);
     50       SD->setOffset(FOffset);
     51     }
     52     PendingLabels.clear();
     53   }
     54 }
     55 
     56 void MCObjectStreamer::reset() {
     57   if (Assembler)
     58     Assembler->reset();
     59   CurSectionData = nullptr;
     60   CurInsertionPoint = MCSectionData::iterator();
     61   EmitEHFrame = true;
     62   EmitDebugFrame = false;
     63   PendingLabels.clear();
     64   MCStreamer::reset();
     65 }
     66 
     67 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
     68   if (!getNumFrameInfos())
     69     return;
     70 
     71   if (EmitEHFrame)
     72     MCDwarfFrameEmitter::Emit(*this, MAB, true);
     73 
     74   if (EmitDebugFrame)
     75     MCDwarfFrameEmitter::Emit(*this, MAB, false);
     76 }
     77 
     78 MCFragment *MCObjectStreamer::getCurrentFragment() const {
     79   assert(getCurrentSectionData() && "No current section!");
     80 
     81   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
     82     return std::prev(CurInsertionPoint);
     83 
     84   return nullptr;
     85 }
     86 
     87 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
     88   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
     89   // When bundling is enabled, we don't want to add data to a fragment that
     90   // already has instructions (see MCELFStreamer::EmitInstToData for details)
     91   if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
     92              F->hasInstructions())) {
     93     F = new MCDataFragment();
     94     insert(F);
     95   }
     96   return F;
     97 }
     98 
     99 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
    100   Assembler->getOrCreateSymbolData(Sym);
    101 }
    102 
    103 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
    104   MCStreamer::EmitCFISections(EH, Debug);
    105   EmitEHFrame = EH;
    106   EmitDebugFrame = Debug;
    107 }
    108 
    109 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
    110                                      const SMLoc &Loc) {
    111   MCStreamer::EmitValueImpl(Value, Size, Loc);
    112   MCDataFragment *DF = getOrCreateDataFragment();
    113 
    114   MCLineEntry::Make(this, getCurrentSection().first);
    115 
    116   // Avoid fixups when possible.
    117   int64_t AbsValue;
    118   if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
    119     EmitIntValue(AbsValue, Size);
    120     return;
    121   }
    122   DF->getFixups().push_back(
    123       MCFixup::Create(DF->getContents().size(), Value,
    124                       MCFixup::getKindForSize(Size, false), Loc));
    125   DF->getContents().resize(DF->getContents().size() + Size, 0);
    126 }
    127 
    128 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
    129   // We need to create a local symbol to avoid relocations.
    130   Frame.Begin = getContext().CreateTempSymbol();
    131   EmitLabel(Frame.Begin);
    132 }
    133 
    134 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
    135   Frame.End = getContext().CreateTempSymbol();
    136   EmitLabel(Frame.End);
    137 }
    138 
    139 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
    140   MCStreamer::EmitLabel(Symbol);
    141 
    142   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    143   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
    144 
    145   // If there is a current fragment, mark the symbol as pointing into it.
    146   // Otherwise queue the label and set its fragment pointer when we emit the
    147   // next fragment.
    148   auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
    149   if (F && !(getAssembler().isBundlingEnabled() &&
    150              getAssembler().getRelaxAll())) {
    151     SD.setFragment(F);
    152     SD.setOffset(F->getContents().size());
    153   } else {
    154     PendingLabels.push_back(&SD);
    155   }
    156 }
    157 
    158 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
    159   int64_t IntValue;
    160   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
    161     EmitULEB128IntValue(IntValue);
    162     return;
    163   }
    164   insert(new MCLEBFragment(*Value, false));
    165 }
    166 
    167 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
    168   int64_t IntValue;
    169   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
    170     EmitSLEB128IntValue(IntValue);
    171     return;
    172   }
    173   insert(new MCLEBFragment(*Value, true));
    174 }
    175 
    176 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
    177                                          const MCSymbol *Symbol) {
    178   report_fatal_error("This file format doesn't support weak aliases.");
    179 }
    180 
    181 void MCObjectStreamer::ChangeSection(const MCSection *Section,
    182                                      const MCExpr *Subsection) {
    183   changeSectionImpl(Section, Subsection);
    184 }
    185 
    186 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
    187                                          const MCExpr *Subsection) {
    188   assert(Section && "Cannot switch to a null section!");
    189   flushPendingLabels(nullptr);
    190 
    191   bool Created;
    192   CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
    193 
    194   int64_t IntSubsection = 0;
    195   if (Subsection &&
    196       !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
    197     report_fatal_error("Cannot evaluate subsection number");
    198   if (IntSubsection < 0 || IntSubsection > 8192)
    199     report_fatal_error("Subsection number out of range");
    200   CurInsertionPoint =
    201     CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
    202   return Created;
    203 }
    204 
    205 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
    206   getAssembler().getOrCreateSymbolData(*Symbol);
    207   MCStreamer::EmitAssignment(Symbol, Value);
    208 }
    209 
    210 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
    211                                        const MCSubtargetInfo &STI) {
    212   MCStreamer::EmitInstruction(Inst, STI);
    213 
    214   MCSectionData *SD = getCurrentSectionData();
    215   SD->setHasInstructions(true);
    216 
    217   // Now that a machine instruction has been assembled into this section, make
    218   // a line entry for any .loc directive that has been seen.
    219   MCLineEntry::Make(this, getCurrentSection().first);
    220 
    221   // If this instruction doesn't need relaxation, just emit it as data.
    222   MCAssembler &Assembler = getAssembler();
    223   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
    224     EmitInstToData(Inst, STI);
    225     return;
    226   }
    227 
    228   // Otherwise, relax and emit it as data if either:
    229   // - The RelaxAll flag was passed
    230   // - Bundling is enabled and this instruction is inside a bundle-locked
    231   //   group. We want to emit all such instructions into the same data
    232   //   fragment.
    233   if (Assembler.getRelaxAll() ||
    234       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
    235     MCInst Relaxed;
    236     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
    237     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
    238       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
    239     EmitInstToData(Relaxed, STI);
    240     return;
    241   }
    242 
    243   // Otherwise emit to a separate fragment.
    244   EmitInstToFragment(Inst, STI);
    245 }
    246 
    247 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
    248                                           const MCSubtargetInfo &STI) {
    249   if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
    250     llvm_unreachable("All instructions should have already been relaxed");
    251 
    252   // Always create a new, separate fragment here, because its size can change
    253   // during relaxation.
    254   MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
    255   insert(IF);
    256 
    257   SmallString<128> Code;
    258   raw_svector_ostream VecOS(Code);
    259   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
    260                                                 STI);
    261   VecOS.flush();
    262   IF->getContents().append(Code.begin(), Code.end());
    263 }
    264 
    265 #ifndef NDEBUG
    266 static const char *const BundlingNotImplementedMsg =
    267   "Aligned bundling is not implemented for this object format";
    268 #endif
    269 
    270 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
    271   llvm_unreachable(BundlingNotImplementedMsg);
    272 }
    273 
    274 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
    275   llvm_unreachable(BundlingNotImplementedMsg);
    276 }
    277 
    278 void MCObjectStreamer::EmitBundleUnlock() {
    279   llvm_unreachable(BundlingNotImplementedMsg);
    280 }
    281 
    282 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
    283                                              unsigned Column, unsigned Flags,
    284                                              unsigned Isa,
    285                                              unsigned Discriminator,
    286                                              StringRef FileName) {
    287   // In case we see two .loc directives in a row, make sure the
    288   // first one gets a line entry.
    289   MCLineEntry::Make(this, getCurrentSection().first);
    290 
    291   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
    292                                           Isa, Discriminator, FileName);
    293 }
    294 
    295 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
    296                                      const MCSymbol *B) {
    297   MCContext &Context = OS.getContext();
    298   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
    299   const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
    300   const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
    301   const MCExpr *AddrDelta =
    302       MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
    303   return AddrDelta;
    304 }
    305 
    306 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
    307                                  const MCSymbol *Label, int PointerSize) {
    308   // emit the sequence to set the address
    309   OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
    310   OS.EmitULEB128IntValue(PointerSize + 1);
    311   OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
    312   OS.EmitSymbolValue(Label, PointerSize);
    313 
    314   // emit the sequence for the LineDelta (from 1) and a zero address delta.
    315   MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
    316 }
    317 
    318 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
    319                                                 const MCSymbol *LastLabel,
    320                                                 const MCSymbol *Label,
    321                                                 unsigned PointerSize) {
    322   if (!LastLabel) {
    323     emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
    324     return;
    325   }
    326   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
    327   int64_t Res;
    328   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
    329     MCDwarfLineAddr::Emit(this, LineDelta, Res);
    330     return;
    331   }
    332   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
    333 }
    334 
    335 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
    336                                                  const MCSymbol *Label) {
    337   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
    338   int64_t Res;
    339   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
    340     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
    341     return;
    342   }
    343   insert(new MCDwarfCallFrameFragment(*AddrDelta));
    344 }
    345 
    346 void MCObjectStreamer::EmitBytes(StringRef Data) {
    347   MCLineEntry::Make(this, getCurrentSection().first);
    348   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
    349 }
    350 
    351 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
    352                                             int64_t Value,
    353                                             unsigned ValueSize,
    354                                             unsigned MaxBytesToEmit) {
    355   if (MaxBytesToEmit == 0)
    356     MaxBytesToEmit = ByteAlignment;
    357   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
    358 
    359   // Update the maximum alignment on the current section if necessary.
    360   if (ByteAlignment > getCurrentSectionData()->getAlignment())
    361     getCurrentSectionData()->setAlignment(ByteAlignment);
    362 }
    363 
    364 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
    365                                          unsigned MaxBytesToEmit) {
    366   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
    367   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
    368 }
    369 
    370 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
    371                                          unsigned char Value) {
    372   int64_t Res;
    373   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
    374     insert(new MCOrgFragment(*Offset, Value));
    375     return false;
    376   }
    377 
    378   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
    379   EmitLabel(CurrentPos);
    380   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
    381   const MCExpr *Ref =
    382     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
    383   const MCExpr *Delta =
    384     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
    385 
    386   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
    387     return true;
    388   EmitFill(Res, Value);
    389   return false;
    390 }
    391 
    392 // Associate GPRel32 fixup with data and resize data area
    393 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
    394   MCDataFragment *DF = getOrCreateDataFragment();
    395 
    396   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
    397                                             Value, FK_GPRel_4));
    398   DF->getContents().resize(DF->getContents().size() + 4, 0);
    399 }
    400 
    401 // Associate GPRel32 fixup with data and resize data area
    402 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
    403   MCDataFragment *DF = getOrCreateDataFragment();
    404 
    405   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
    406                                             Value, FK_GPRel_4));
    407   DF->getContents().resize(DF->getContents().size() + 8, 0);
    408 }
    409 
    410 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
    411   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
    412   //        problems evaluating expressions across multiple fragments.
    413   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
    414 }
    415 
    416 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
    417   const MCSection *Sec = getCurrentSection().first;
    418   assert(Sec && "need a section");
    419   unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
    420   insert(new MCFillFragment(0, ItemSize, NumBytes));
    421 }
    422 
    423 void MCObjectStreamer::FinishImpl() {
    424   // If we are generating dwarf for assembly source files dump out the sections.
    425   if (getContext().getGenDwarfForAssembly())
    426     MCGenDwarfInfo::Emit(this);
    427 
    428   // Dump out the dwarf file & directory tables and line tables.
    429   MCDwarfLineTable::Emit(this);
    430 
    431   flushPendingLabels(nullptr);
    432   getAssembler().Finish();
    433 }
    434