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