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