1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/MC/MCObjectStreamer.h" 10 #include "llvm/MC/MCAsmBackend.h" 11 #include "llvm/MC/MCAsmInfo.h" 12 #include "llvm/MC/MCAssembler.h" 13 #include "llvm/MC/MCCodeEmitter.h" 14 #include "llvm/MC/MCCodeView.h" 15 #include "llvm/MC/MCContext.h" 16 #include "llvm/MC/MCDwarf.h" 17 #include "llvm/MC/MCExpr.h" 18 #include "llvm/MC/MCObjectFileInfo.h" 19 #include "llvm/MC/MCObjectWriter.h" 20 #include "llvm/MC/MCSection.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/MC/MCValue.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/SourceMgr.h" 25 using namespace llvm; 26 27 MCObjectStreamer::MCObjectStreamer(MCContext &Context, 28 std::unique_ptr<MCAsmBackend> TAB, 29 std::unique_ptr<MCObjectWriter> OW, 30 std::unique_ptr<MCCodeEmitter> Emitter) 31 : MCStreamer(Context), 32 Assembler(std::make_unique<MCAssembler>( 33 Context, std::move(TAB), std::move(Emitter), std::move(OW))), 34 EmitEHFrame(true), EmitDebugFrame(false) { 35 if (Assembler->getBackendPtr()) 36 setAllowAutoPadding(Assembler->getBackend().allowAutoPadding()); 37 if (Context.getTargetOptions() && Context.getTargetOptions()->MCRelaxAll) 38 Assembler->setRelaxAll(true); 39 } 40 41 MCObjectStreamer::~MCObjectStreamer() = default; 42 43 MCAssembler *MCObjectStreamer::getAssemblerPtr() { 44 if (getUseAssemblerInfoForParsing()) 45 return Assembler.get(); 46 return nullptr; 47 } 48 49 void MCObjectStreamer::addPendingLabel(MCSymbol* S) { 50 MCSection *CurSection = getCurrentSectionOnly(); 51 if (CurSection) { 52 // Register labels that have not yet been assigned to a Section. 53 if (!PendingLabels.empty()) { 54 for (MCSymbol* Sym : PendingLabels) 55 CurSection->addPendingLabel(Sym); 56 PendingLabels.clear(); 57 } 58 59 // Add this label to the current Section / Subsection. 60 CurSection->addPendingLabel(S, CurSubsectionIdx); 61 62 // Add this Section to the list of PendingLabelSections. 63 PendingLabelSections.insert(CurSection); 64 } else 65 // There is no Section / Subsection for this label yet. 66 PendingLabels.push_back(S); 67 } 68 69 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) { 70 assert(F); 71 MCSection *CurSection = getCurrentSectionOnly(); 72 if (!CurSection) { 73 assert(PendingLabels.empty()); 74 return; 75 } 76 // Register labels that have not yet been assigned to a Section. 77 if (!PendingLabels.empty()) { 78 for (MCSymbol* Sym : PendingLabels) 79 CurSection->addPendingLabel(Sym, CurSubsectionIdx); 80 PendingLabels.clear(); 81 } 82 83 // Associate the labels with F. 84 CurSection->flushPendingLabels(F, CurSubsectionIdx); 85 } 86 87 void MCObjectStreamer::flushPendingLabels() { 88 // Register labels that have not yet been assigned to a Section. 89 if (!PendingLabels.empty()) { 90 MCSection *CurSection = getCurrentSectionOnly(); 91 assert(CurSection); 92 for (MCSymbol* Sym : PendingLabels) 93 CurSection->addPendingLabel(Sym, CurSubsectionIdx); 94 PendingLabels.clear(); 95 } 96 97 // Assign an empty data fragment to all remaining pending labels. 98 for (MCSection* Section : PendingLabelSections) 99 Section->flushPendingLabels(); 100 } 101 102 // When fixup's offset is a forward declared label, e.g.: 103 // 104 // .reloc 1f, R_MIPS_JALR, foo 105 // 1: nop 106 // 107 // postpone adding it to Fixups vector until the label is defined and its offset 108 // is known. 109 void MCObjectStreamer::resolvePendingFixups() { 110 for (PendingMCFixup &PendingFixup : PendingFixups) { 111 if (!PendingFixup.Sym || PendingFixup.Sym->isUndefined ()) { 112 getContext().reportError(PendingFixup.Fixup.getLoc(), 113 "unresolved relocation offset"); 114 continue; 115 } 116 flushPendingLabels(PendingFixup.DF, PendingFixup.DF->getContents().size()); 117 PendingFixup.Fixup.setOffset(PendingFixup.Sym->getOffset() + 118 PendingFixup.Fixup.getOffset()); 119 120 // If the location symbol to relocate is in MCEncodedFragmentWithFixups, 121 // put the Fixup into location symbol's fragment. Otherwise 122 // put into PendingFixup.DF 123 MCFragment *SymFragment = PendingFixup.Sym->getFragment(); 124 switch (SymFragment->getKind()) { 125 case MCFragment::FT_Relaxable: 126 case MCFragment::FT_Dwarf: 127 case MCFragment::FT_PseudoProbe: 128 cast<MCEncodedFragmentWithFixups<8, 1>>(SymFragment) 129 ->getFixups() 130 .push_back(PendingFixup.Fixup); 131 break; 132 case MCFragment::FT_Data: 133 case MCFragment::FT_CVDefRange: 134 cast<MCEncodedFragmentWithFixups<32, 4>>(SymFragment) 135 ->getFixups() 136 .push_back(PendingFixup.Fixup); 137 break; 138 default: 139 PendingFixup.DF->getFixups().push_back(PendingFixup.Fixup); 140 break; 141 } 142 } 143 PendingFixups.clear(); 144 } 145 146 // As a compile-time optimization, avoid allocating and evaluating an MCExpr 147 // tree for (Hi - Lo) when Hi and Lo are offsets into the same fragment. 148 static std::optional<uint64_t> absoluteSymbolDiff(const MCSymbol *Hi, 149 const MCSymbol *Lo) { 150 assert(Hi && Lo); 151 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() || 152 Hi->isVariable() || Lo->isVariable()) 153 return std::nullopt; 154 155 return Hi->getOffset() - Lo->getOffset(); 156 } 157 158 void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, 159 const MCSymbol *Lo, 160 unsigned Size) { 161 if (!getAssembler().getContext().getTargetTriple().isRISCV()) 162 if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo)) 163 return emitIntValue(*Diff, Size); 164 MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size); 165 } 166 167 void MCObjectStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi, 168 const MCSymbol *Lo) { 169 if (!getAssembler().getContext().getTargetTriple().isRISCV()) 170 if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo)) { 171 emitULEB128IntValue(*Diff); 172 return; 173 } 174 MCStreamer::emitAbsoluteSymbolDiffAsULEB128(Hi, Lo); 175 } 176 177 void MCObjectStreamer::reset() { 178 if (Assembler) { 179 Assembler->reset(); 180 if (getContext().getTargetOptions()) 181 Assembler->setRelaxAll(getContext().getTargetOptions()->MCRelaxAll); 182 } 183 EmitEHFrame = true; 184 EmitDebugFrame = false; 185 PendingLabels.clear(); 186 PendingLabelSections.clear(); 187 MCStreamer::reset(); 188 } 189 190 void MCObjectStreamer::emitFrames(MCAsmBackend *MAB) { 191 if (!getNumFrameInfos()) 192 return; 193 194 if (EmitEHFrame) 195 MCDwarfFrameEmitter::Emit(*this, MAB, true); 196 197 if (EmitDebugFrame) 198 MCDwarfFrameEmitter::Emit(*this, MAB, false); 199 } 200 201 MCFragment *MCObjectStreamer::getCurrentFragment() const { 202 return getCurrentSectionOnly()->curFragList()->Tail; 203 } 204 205 static bool canReuseDataFragment(const MCDataFragment &F, 206 const MCAssembler &Assembler, 207 const MCSubtargetInfo *STI) { 208 if (!F.hasInstructions()) 209 return true; 210 // Do not add data after a linker-relaxable instruction. The difference 211 // between a new label and a label at or before the linker-relaxable 212 // instruction cannot be resolved at assemble-time. 213 if (F.isLinkerRelaxable()) 214 return false; 215 // When bundling is enabled, we don't want to add data to a fragment that 216 // already has instructions (see MCELFStreamer::emitInstToData for details) 217 if (Assembler.isBundlingEnabled()) 218 return false; 219 // If the subtarget is changed mid fragment we start a new fragment to record 220 // the new STI. 221 return !STI || F.getSubtargetInfo() == STI; 222 } 223 224 MCDataFragment * 225 MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) { 226 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); 227 if (!F || !canReuseDataFragment(*F, *Assembler, STI)) { 228 F = getContext().allocFragment<MCDataFragment>(); 229 insert(F); 230 } 231 return F; 232 } 233 234 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) { 235 Assembler->registerSymbol(Sym); 236 } 237 238 void MCObjectStreamer::emitCFISections(bool EH, bool Debug) { 239 MCStreamer::emitCFISections(EH, Debug); 240 EmitEHFrame = EH; 241 EmitDebugFrame = Debug; 242 } 243 244 void MCObjectStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, 245 SMLoc Loc) { 246 MCStreamer::emitValueImpl(Value, Size, Loc); 247 MCDataFragment *DF = getOrCreateDataFragment(); 248 flushPendingLabels(DF, DF->getContents().size()); 249 250 MCDwarfLineEntry::make(this, getCurrentSectionOnly()); 251 252 // Avoid fixups when possible. 253 int64_t AbsValue; 254 if (Value->evaluateAsAbsolute(AbsValue, getAssemblerPtr())) { 255 if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) { 256 getContext().reportError( 257 Loc, "value evaluated as " + Twine(AbsValue) + " is out of range."); 258 return; 259 } 260 emitIntValue(AbsValue, Size); 261 return; 262 } 263 DF->getFixups().push_back( 264 MCFixup::create(DF->getContents().size(), Value, 265 MCFixup::getKindForSize(Size, false), Loc)); 266 DF->getContents().resize(DF->getContents().size() + Size, 0); 267 } 268 269 MCSymbol *MCObjectStreamer::emitCFILabel() { 270 MCSymbol *Label = getContext().createTempSymbol("cfi"); 271 emitLabel(Label); 272 return Label; 273 } 274 275 void MCObjectStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { 276 // We need to create a local symbol to avoid relocations. 277 Frame.Begin = getContext().createTempSymbol(); 278 emitLabel(Frame.Begin); 279 } 280 281 void MCObjectStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { 282 Frame.End = getContext().createTempSymbol(); 283 emitLabel(Frame.End); 284 } 285 286 void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) { 287 MCStreamer::emitLabel(Symbol, Loc); 288 289 getAssembler().registerSymbol(*Symbol); 290 291 // If there is a current fragment, mark the symbol as pointing into it. 292 // Otherwise queue the label and set its fragment pointer when we emit the 293 // next fragment. 294 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment()); 295 if (F) { 296 Symbol->setFragment(F); 297 Symbol->setOffset(F->getContents().size()); 298 } else { 299 // Assign all pending labels to offset 0 within the dummy "pending" 300 // fragment. (They will all be reassigned to a real fragment in 301 // flushPendingLabels()) 302 Symbol->setOffset(0); 303 addPendingLabel(Symbol); 304 } 305 306 emitPendingAssignments(Symbol); 307 } 308 309 void MCObjectStreamer::emitPendingAssignments(MCSymbol *Symbol) { 310 auto Assignments = pendingAssignments.find(Symbol); 311 if (Assignments != pendingAssignments.end()) { 312 for (const PendingAssignment &A : Assignments->second) 313 emitAssignment(A.Symbol, A.Value); 314 315 pendingAssignments.erase(Assignments); 316 } 317 } 318 319 // Emit a label at a previously emitted fragment/offset position. This must be 320 // within the currently-active section. 321 void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc, 322 MCFragment *F, uint64_t Offset) { 323 assert(F->getParent() == getCurrentSectionOnly()); 324 325 MCStreamer::emitLabel(Symbol, Loc); 326 getAssembler().registerSymbol(*Symbol); 327 auto *DF = dyn_cast_or_null<MCDataFragment>(F); 328 Symbol->setOffset(Offset); 329 if (DF) { 330 Symbol->setFragment(F); 331 } else { 332 assert(isa<MCDummyFragment>(F) && 333 "F must either be an MCDataFragment or the pending MCDummyFragment"); 334 assert(Offset == 0); 335 addPendingLabel(Symbol); 336 } 337 } 338 339 void MCObjectStreamer::emitULEB128Value(const MCExpr *Value) { 340 int64_t IntValue; 341 if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) { 342 emitULEB128IntValue(IntValue); 343 return; 344 } 345 insert(getContext().allocFragment<MCLEBFragment>(*Value, false)); 346 } 347 348 void MCObjectStreamer::emitSLEB128Value(const MCExpr *Value) { 349 int64_t IntValue; 350 if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) { 351 emitSLEB128IntValue(IntValue); 352 return; 353 } 354 insert(getContext().allocFragment<MCLEBFragment>(*Value, true)); 355 } 356 357 void MCObjectStreamer::emitWeakReference(MCSymbol *Alias, 358 const MCSymbol *Symbol) { 359 report_fatal_error("This file format doesn't support weak aliases."); 360 } 361 362 void MCObjectStreamer::changeSection(MCSection *Section, 363 const MCExpr *Subsection) { 364 changeSectionImpl(Section, Subsection); 365 } 366 367 bool MCObjectStreamer::changeSectionImpl(MCSection *Section, 368 const MCExpr *Subsection) { 369 assert(Section && "Cannot switch to a null section!"); 370 getContext().clearDwarfLocSeen(); 371 372 bool Created = getAssembler().registerSection(*Section); 373 374 int64_t IntSubsection = 0; 375 if (Subsection && 376 !Subsection->evaluateAsAbsolute(IntSubsection, getAssemblerPtr())) { 377 getContext().reportError(Subsection->getLoc(), 378 "cannot evaluate subsection number"); 379 } 380 if (!isUInt<31>(IntSubsection)) { 381 getContext().reportError(Subsection->getLoc(), 382 "subsection number " + Twine(IntSubsection) + 383 " is not within [0,2147483647]"); 384 } 385 386 CurSubsectionIdx = unsigned(IntSubsection); 387 Section->switchSubsection(CurSubsectionIdx); 388 return Created; 389 } 390 391 void MCObjectStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) { 392 getAssembler().registerSymbol(*Symbol); 393 MCStreamer::emitAssignment(Symbol, Value); 394 emitPendingAssignments(Symbol); 395 } 396 397 void MCObjectStreamer::emitConditionalAssignment(MCSymbol *Symbol, 398 const MCExpr *Value) { 399 const MCSymbol *Target = &cast<MCSymbolRefExpr>(*Value).getSymbol(); 400 401 // If the symbol already exists, emit the assignment. Otherwise, emit it 402 // later only if the symbol is also emitted. 403 if (Target->isRegistered()) 404 emitAssignment(Symbol, Value); 405 else 406 pendingAssignments[Target].push_back({Symbol, Value}); 407 } 408 409 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const { 410 return Sec.hasInstructions(); 411 } 412 413 void MCObjectStreamer::emitInstruction(const MCInst &Inst, 414 const MCSubtargetInfo &STI) { 415 const MCSection &Sec = *getCurrentSectionOnly(); 416 if (Sec.isVirtualSection()) { 417 getContext().reportError(Inst.getLoc(), Twine(Sec.getVirtualSectionKind()) + 418 " section '" + Sec.getName() + 419 "' cannot have instructions"); 420 return; 421 } 422 getAssembler().getBackend().emitInstructionBegin(*this, Inst, STI); 423 emitInstructionImpl(Inst, STI); 424 getAssembler().getBackend().emitInstructionEnd(*this, Inst); 425 } 426 427 void MCObjectStreamer::emitInstructionImpl(const MCInst &Inst, 428 const MCSubtargetInfo &STI) { 429 MCStreamer::emitInstruction(Inst, STI); 430 431 MCSection *Sec = getCurrentSectionOnly(); 432 Sec->setHasInstructions(true); 433 434 // Now that a machine instruction has been assembled into this section, make 435 // a line entry for any .loc directive that has been seen. 436 MCDwarfLineEntry::make(this, getCurrentSectionOnly()); 437 438 // If this instruction doesn't need relaxation, just emit it as data. 439 MCAssembler &Assembler = getAssembler(); 440 MCAsmBackend &Backend = Assembler.getBackend(); 441 if (!(Backend.mayNeedRelaxation(Inst, STI) || 442 Backend.allowEnhancedRelaxation())) { 443 emitInstToData(Inst, STI); 444 return; 445 } 446 447 // Otherwise, relax and emit it as data if either: 448 // - The RelaxAll flag was passed 449 // - Bundling is enabled and this instruction is inside a bundle-locked 450 // group. We want to emit all such instructions into the same data 451 // fragment. 452 if (Assembler.getRelaxAll() || 453 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) { 454 MCInst Relaxed = Inst; 455 while (Backend.mayNeedRelaxation(Relaxed, STI)) 456 Backend.relaxInstruction(Relaxed, STI); 457 emitInstToData(Relaxed, STI); 458 return; 459 } 460 461 // Otherwise emit to a separate fragment. 462 emitInstToFragment(Inst, STI); 463 } 464 465 void MCObjectStreamer::emitInstToFragment(const MCInst &Inst, 466 const MCSubtargetInfo &STI) { 467 // Always create a new, separate fragment here, because its size can change 468 // during relaxation. 469 MCRelaxableFragment *IF = 470 getContext().allocFragment<MCRelaxableFragment>(Inst, STI); 471 insert(IF); 472 473 SmallString<128> Code; 474 getAssembler().getEmitter().encodeInstruction(Inst, Code, IF->getFixups(), 475 STI); 476 IF->getContents().append(Code.begin(), Code.end()); 477 } 478 479 #ifndef NDEBUG 480 static const char *const BundlingNotImplementedMsg = 481 "Aligned bundling is not implemented for this object format"; 482 #endif 483 484 void MCObjectStreamer::emitBundleAlignMode(Align Alignment) { 485 llvm_unreachable(BundlingNotImplementedMsg); 486 } 487 488 void MCObjectStreamer::emitBundleLock(bool AlignToEnd) { 489 llvm_unreachable(BundlingNotImplementedMsg); 490 } 491 492 void MCObjectStreamer::emitBundleUnlock() { 493 llvm_unreachable(BundlingNotImplementedMsg); 494 } 495 496 void MCObjectStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line, 497 unsigned Column, unsigned Flags, 498 unsigned Isa, 499 unsigned Discriminator, 500 StringRef FileName) { 501 // In case we see two .loc directives in a row, make sure the 502 // first one gets a line entry. 503 MCDwarfLineEntry::make(this, getCurrentSectionOnly()); 504 505 this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa, 506 Discriminator, FileName); 507 } 508 509 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A, 510 const MCSymbol *B, SMLoc Loc) { 511 MCContext &Context = OS.getContext(); 512 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 513 const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context); 514 const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context); 515 const MCExpr *AddrDelta = 516 MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context, Loc); 517 return AddrDelta; 518 } 519 520 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, 521 MCDwarfLineTableParams Params, 522 int64_t LineDelta, const MCSymbol *Label, 523 int PointerSize) { 524 // emit the sequence to set the address 525 OS.emitIntValue(dwarf::DW_LNS_extended_op, 1); 526 OS.emitULEB128IntValue(PointerSize + 1); 527 OS.emitIntValue(dwarf::DW_LNE_set_address, 1); 528 OS.emitSymbolValue(Label, PointerSize); 529 530 // emit the sequence for the LineDelta (from 1) and a zero address delta. 531 MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0); 532 } 533 534 void MCObjectStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta, 535 const MCSymbol *LastLabel, 536 const MCSymbol *Label, 537 unsigned PointerSize) { 538 if (!LastLabel) { 539 emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta, 540 Label, PointerSize); 541 return; 542 } 543 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel, SMLoc()); 544 insert(getContext().allocFragment<MCDwarfLineAddrFragment>(LineDelta, 545 *AddrDelta)); 546 } 547 548 void MCObjectStreamer::emitDwarfLineEndEntry(MCSection *Section, 549 MCSymbol *LastLabel) { 550 // Emit a DW_LNE_end_sequence for the end of the section. 551 // Use the section end label to compute the address delta and use INT64_MAX 552 // as the line delta which is the signal that this is actually a 553 // DW_LNE_end_sequence. 554 MCSymbol *SectionEnd = endSection(Section); 555 556 // Switch back the dwarf line section, in case endSection had to switch the 557 // section. 558 MCContext &Ctx = getContext(); 559 switchSection(Ctx.getObjectFileInfo()->getDwarfLineSection()); 560 561 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo(); 562 emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, 563 AsmInfo->getCodePointerSize()); 564 } 565 566 void MCObjectStreamer::emitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel, 567 const MCSymbol *Label, 568 SMLoc Loc) { 569 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel, Loc); 570 insert(getContext().allocFragment<MCDwarfCallFrameFragment>(*AddrDelta, 571 nullptr)); 572 } 573 574 void MCObjectStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo, 575 unsigned Line, unsigned Column, 576 bool PrologueEnd, bool IsStmt, 577 StringRef FileName, SMLoc Loc) { 578 // Validate the directive. 579 if (!checkCVLocSection(FunctionId, FileNo, Loc)) 580 return; 581 582 // Emit a label at the current position and record it in the CodeViewContext. 583 MCSymbol *LineSym = getContext().createTempSymbol(); 584 emitLabel(LineSym); 585 getContext().getCVContext().recordCVLoc(getContext(), LineSym, FunctionId, 586 FileNo, Line, Column, PrologueEnd, 587 IsStmt); 588 } 589 590 void MCObjectStreamer::emitCVLinetableDirective(unsigned FunctionId, 591 const MCSymbol *Begin, 592 const MCSymbol *End) { 593 getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin, 594 End); 595 this->MCStreamer::emitCVLinetableDirective(FunctionId, Begin, End); 596 } 597 598 void MCObjectStreamer::emitCVInlineLinetableDirective( 599 unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum, 600 const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) { 601 getContext().getCVContext().emitInlineLineTableForFunction( 602 *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, 603 FnEndSym); 604 this->MCStreamer::emitCVInlineLinetableDirective( 605 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym); 606 } 607 608 void MCObjectStreamer::emitCVDefRangeDirective( 609 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, 610 StringRef FixedSizePortion) { 611 MCFragment *Frag = 612 getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion); 613 // Attach labels that were pending before we created the defrange fragment to 614 // the beginning of the new fragment. 615 flushPendingLabels(Frag, 0); 616 this->MCStreamer::emitCVDefRangeDirective(Ranges, FixedSizePortion); 617 } 618 619 void MCObjectStreamer::emitCVStringTableDirective() { 620 getContext().getCVContext().emitStringTable(*this); 621 } 622 void MCObjectStreamer::emitCVFileChecksumsDirective() { 623 getContext().getCVContext().emitFileChecksums(*this); 624 } 625 626 void MCObjectStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) { 627 getContext().getCVContext().emitFileChecksumOffset(*this, FileNo); 628 } 629 630 void MCObjectStreamer::emitBytes(StringRef Data) { 631 MCDwarfLineEntry::make(this, getCurrentSectionOnly()); 632 MCDataFragment *DF = getOrCreateDataFragment(); 633 flushPendingLabels(DF, DF->getContents().size()); 634 DF->getContents().append(Data.begin(), Data.end()); 635 } 636 637 void MCObjectStreamer::emitValueToAlignment(Align Alignment, int64_t Value, 638 unsigned ValueSize, 639 unsigned MaxBytesToEmit) { 640 if (MaxBytesToEmit == 0) 641 MaxBytesToEmit = Alignment.value(); 642 insert(getContext().allocFragment<MCAlignFragment>( 643 Alignment, Value, ValueSize, MaxBytesToEmit)); 644 645 // Update the maximum alignment on the current section if necessary. 646 MCSection *CurSec = getCurrentSectionOnly(); 647 CurSec->ensureMinAlignment(Alignment); 648 } 649 650 void MCObjectStreamer::emitCodeAlignment(Align Alignment, 651 const MCSubtargetInfo *STI, 652 unsigned MaxBytesToEmit) { 653 emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit); 654 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true, STI); 655 } 656 657 void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset, 658 unsigned char Value, 659 SMLoc Loc) { 660 insert(getContext().allocFragment<MCOrgFragment>(*Offset, Value, Loc)); 661 } 662 663 // Associate DTPRel32 fixup with data and resize data area 664 void MCObjectStreamer::emitDTPRel32Value(const MCExpr *Value) { 665 MCDataFragment *DF = getOrCreateDataFragment(); 666 flushPendingLabels(DF, DF->getContents().size()); 667 668 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), 669 Value, FK_DTPRel_4)); 670 DF->getContents().resize(DF->getContents().size() + 4, 0); 671 } 672 673 // Associate DTPRel64 fixup with data and resize data area 674 void MCObjectStreamer::emitDTPRel64Value(const MCExpr *Value) { 675 MCDataFragment *DF = getOrCreateDataFragment(); 676 flushPendingLabels(DF, DF->getContents().size()); 677 678 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), 679 Value, FK_DTPRel_8)); 680 DF->getContents().resize(DF->getContents().size() + 8, 0); 681 } 682 683 // Associate TPRel32 fixup with data and resize data area 684 void MCObjectStreamer::emitTPRel32Value(const MCExpr *Value) { 685 MCDataFragment *DF = getOrCreateDataFragment(); 686 flushPendingLabels(DF, DF->getContents().size()); 687 688 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), 689 Value, FK_TPRel_4)); 690 DF->getContents().resize(DF->getContents().size() + 4, 0); 691 } 692 693 // Associate TPRel64 fixup with data and resize data area 694 void MCObjectStreamer::emitTPRel64Value(const MCExpr *Value) { 695 MCDataFragment *DF = getOrCreateDataFragment(); 696 flushPendingLabels(DF, DF->getContents().size()); 697 698 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(), 699 Value, FK_TPRel_8)); 700 DF->getContents().resize(DF->getContents().size() + 8, 0); 701 } 702 703 // Associate GPRel32 fixup with data and resize data area 704 void MCObjectStreamer::emitGPRel32Value(const MCExpr *Value) { 705 MCDataFragment *DF = getOrCreateDataFragment(); 706 flushPendingLabels(DF, DF->getContents().size()); 707 708 DF->getFixups().push_back( 709 MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4)); 710 DF->getContents().resize(DF->getContents().size() + 4, 0); 711 } 712 713 // Associate GPRel64 fixup with data and resize data area 714 void MCObjectStreamer::emitGPRel64Value(const MCExpr *Value) { 715 MCDataFragment *DF = getOrCreateDataFragment(); 716 flushPendingLabels(DF, DF->getContents().size()); 717 718 DF->getFixups().push_back( 719 MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4)); 720 DF->getContents().resize(DF->getContents().size() + 8, 0); 721 } 722 723 static std::optional<std::pair<bool, std::string>> 724 getOffsetAndDataFragment(const MCSymbol &Symbol, uint32_t &RelocOffset, 725 MCDataFragment *&DF) { 726 if (Symbol.isVariable()) { 727 const MCExpr *SymbolExpr = Symbol.getVariableValue(); 728 MCValue OffsetVal; 729 if(!SymbolExpr->evaluateAsRelocatable(OffsetVal, nullptr, nullptr)) 730 return std::make_pair(false, 731 std::string("symbol in .reloc offset is not " 732 "relocatable")); 733 if (OffsetVal.isAbsolute()) { 734 RelocOffset = OffsetVal.getConstant(); 735 MCFragment *Fragment = Symbol.getFragment(); 736 // FIXME Support symbols with no DF. For example: 737 // .reloc .data, ENUM_VALUE, <some expr> 738 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data) 739 return std::make_pair(false, 740 std::string("symbol in offset has no data " 741 "fragment")); 742 DF = cast<MCDataFragment>(Fragment); 743 return std::nullopt; 744 } 745 746 if (OffsetVal.getSymB()) 747 return std::make_pair(false, 748 std::string(".reloc symbol offset is not " 749 "representable")); 750 751 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA()); 752 if (!SRE.getSymbol().isDefined()) 753 return std::make_pair(false, 754 std::string("symbol used in the .reloc offset is " 755 "not defined")); 756 757 if (SRE.getSymbol().isVariable()) 758 return std::make_pair(false, 759 std::string("symbol used in the .reloc offset is " 760 "variable")); 761 762 MCFragment *Fragment = SRE.getSymbol().getFragment(); 763 // FIXME Support symbols with no DF. For example: 764 // .reloc .data, ENUM_VALUE, <some expr> 765 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data) 766 return std::make_pair(false, 767 std::string("symbol in offset has no data " 768 "fragment")); 769 RelocOffset = SRE.getSymbol().getOffset() + OffsetVal.getConstant(); 770 DF = cast<MCDataFragment>(Fragment); 771 } else { 772 RelocOffset = Symbol.getOffset(); 773 MCFragment *Fragment = Symbol.getFragment(); 774 // FIXME Support symbols with no DF. For example: 775 // .reloc .data, ENUM_VALUE, <some expr> 776 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data) 777 return std::make_pair(false, 778 std::string("symbol in offset has no data " 779 "fragment")); 780 DF = cast<MCDataFragment>(Fragment); 781 } 782 return std::nullopt; 783 } 784 785 std::optional<std::pair<bool, std::string>> 786 MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name, 787 const MCExpr *Expr, SMLoc Loc, 788 const MCSubtargetInfo &STI) { 789 std::optional<MCFixupKind> MaybeKind = 790 Assembler->getBackend().getFixupKind(Name); 791 if (!MaybeKind) 792 return std::make_pair(true, std::string("unknown relocation name")); 793 794 MCFixupKind Kind = *MaybeKind; 795 if (Expr) 796 visitUsedExpr(*Expr); 797 else 798 Expr = 799 MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext()); 800 801 MCDataFragment *DF = getOrCreateDataFragment(&STI); 802 flushPendingLabels(DF, DF->getContents().size()); 803 804 MCValue OffsetVal; 805 if (!Offset.evaluateAsRelocatable(OffsetVal, nullptr, nullptr)) 806 return std::make_pair(false, 807 std::string(".reloc offset is not relocatable")); 808 if (OffsetVal.isAbsolute()) { 809 if (OffsetVal.getConstant() < 0) 810 return std::make_pair(false, std::string(".reloc offset is negative")); 811 DF->getFixups().push_back( 812 MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc)); 813 return std::nullopt; 814 } 815 if (OffsetVal.getSymB()) 816 return std::make_pair(false, 817 std::string(".reloc offset is not representable")); 818 819 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA()); 820 const MCSymbol &Symbol = SRE.getSymbol(); 821 if (Symbol.isDefined()) { 822 uint32_t SymbolOffset = 0; 823 std::optional<std::pair<bool, std::string>> Error = 824 getOffsetAndDataFragment(Symbol, SymbolOffset, DF); 825 826 if (Error != std::nullopt) 827 return Error; 828 829 DF->getFixups().push_back( 830 MCFixup::create(SymbolOffset + OffsetVal.getConstant(), 831 Expr, Kind, Loc)); 832 return std::nullopt; 833 } 834 835 PendingFixups.emplace_back( 836 &SRE.getSymbol(), DF, 837 MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc)); 838 return std::nullopt; 839 } 840 841 void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue, 842 SMLoc Loc) { 843 MCDataFragment *DF = getOrCreateDataFragment(); 844 flushPendingLabels(DF, DF->getContents().size()); 845 846 assert(getCurrentSectionOnly() && "need a section"); 847 insert( 848 getContext().allocFragment<MCFillFragment>(FillValue, 1, NumBytes, Loc)); 849 } 850 851 void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size, 852 int64_t Expr, SMLoc Loc) { 853 int64_t IntNumValues; 854 // Do additional checking now if we can resolve the value. 855 if (NumValues.evaluateAsAbsolute(IntNumValues, getAssemblerPtr())) { 856 if (IntNumValues < 0) { 857 getContext().getSourceManager()->PrintMessage( 858 Loc, SourceMgr::DK_Warning, 859 "'.fill' directive with negative repeat count has no effect"); 860 return; 861 } 862 // Emit now if we can for better errors. 863 int64_t NonZeroSize = Size > 4 ? 4 : Size; 864 Expr &= ~0ULL >> (64 - NonZeroSize * 8); 865 for (uint64_t i = 0, e = IntNumValues; i != e; ++i) { 866 emitIntValue(Expr, NonZeroSize); 867 if (NonZeroSize < Size) 868 emitIntValue(0, Size - NonZeroSize); 869 } 870 return; 871 } 872 873 // Otherwise emit as fragment. 874 MCDataFragment *DF = getOrCreateDataFragment(); 875 flushPendingLabels(DF, DF->getContents().size()); 876 877 assert(getCurrentSectionOnly() && "need a section"); 878 insert( 879 getContext().allocFragment<MCFillFragment>(Expr, Size, NumValues, Loc)); 880 } 881 882 void MCObjectStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLength, 883 SMLoc Loc, const MCSubtargetInfo &STI) { 884 // Emit an NOP fragment. 885 MCDataFragment *DF = getOrCreateDataFragment(); 886 flushPendingLabels(DF, DF->getContents().size()); 887 888 assert(getCurrentSectionOnly() && "need a section"); 889 890 insert(getContext().allocFragment<MCNopsFragment>( 891 NumBytes, ControlledNopLength, Loc, STI)); 892 } 893 894 void MCObjectStreamer::emitFileDirective(StringRef Filename) { 895 getAssembler().addFileName(Filename); 896 } 897 898 void MCObjectStreamer::emitFileDirective(StringRef Filename, 899 StringRef CompilerVersion, 900 StringRef TimeStamp, 901 StringRef Description) { 902 getAssembler().addFileName(Filename); 903 getAssembler().setCompilerVersion(CompilerVersion.str()); 904 // TODO: add TimeStamp and Description to .file symbol table entry 905 // with the integrated assembler. 906 } 907 908 void MCObjectStreamer::emitAddrsig() { 909 getAssembler().getWriter().emitAddrsigSection(); 910 } 911 912 void MCObjectStreamer::emitAddrsigSym(const MCSymbol *Sym) { 913 getAssembler().getWriter().addAddrsigSymbol(Sym); 914 } 915 916 void MCObjectStreamer::finishImpl() { 917 getContext().RemapDebugPaths(); 918 919 // If we are generating dwarf for assembly source files dump out the sections. 920 if (getContext().getGenDwarfForAssembly()) 921 MCGenDwarfInfo::Emit(this); 922 923 // Dump out the dwarf file & directory tables and line tables. 924 MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams()); 925 926 // Emit pseudo probes for the current module. 927 MCPseudoProbeTable::emit(this); 928 929 // Update any remaining pending labels with empty data fragments. 930 flushPendingLabels(); 931 932 resolvePendingFixups(); 933 getAssembler().Finish(); 934 } 935