1 //===--- BinaryEmitter.cpp - collection of functions to emit code and data ===// 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 //===----------------------------------------------------------------------===// 10 11 #include "bolt/Core/BinaryEmitter.h" 12 #include "bolt/Core/BinaryContext.h" 13 #include "bolt/Core/BinaryFunction.h" 14 #include "bolt/Core/DebugData.h" 15 #include "bolt/Utils/CommandLineOpts.h" 16 #include "bolt/Utils/Utils.h" 17 #include "llvm/MC/MCSection.h" 18 #include "llvm/MC/MCStreamer.h" 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm/Support/LEB128.h" 21 #include "llvm/Support/SMLoc.h" 22 23 #define DEBUG_TYPE "bolt" 24 25 using namespace llvm; 26 using namespace bolt; 27 28 namespace opts { 29 30 extern cl::opt<JumpTableSupportLevel> JumpTables; 31 extern cl::opt<bool> PreserveBlocksAlignment; 32 33 cl::opt<bool> 34 AlignBlocks("align-blocks", 35 cl::desc("align basic blocks"), 36 cl::init(false), 37 cl::ZeroOrMore, 38 cl::cat(BoltOptCategory)); 39 40 cl::opt<MacroFusionType> 41 AlignMacroOpFusion("align-macro-fusion", 42 cl::desc("fix instruction alignment for macro-fusion (x86 relocation mode)"), 43 cl::init(MFT_HOT), 44 cl::values(clEnumValN(MFT_NONE, "none", 45 "do not insert alignment no-ops for macro-fusion"), 46 clEnumValN(MFT_HOT, "hot", 47 "only insert alignment no-ops on hot execution paths (default)"), 48 clEnumValN(MFT_ALL, "all", 49 "always align instructions to allow macro-fusion")), 50 cl::ZeroOrMore, 51 cl::cat(BoltRelocCategory)); 52 53 static cl::list<std::string> 54 BreakFunctionNames("break-funcs", 55 cl::CommaSeparated, 56 cl::desc("list of functions to core dump on (debugging)"), 57 cl::value_desc("func1,func2,func3,..."), 58 cl::Hidden, 59 cl::cat(BoltCategory)); 60 61 static cl::list<std::string> 62 FunctionPadSpec("pad-funcs", 63 cl::CommaSeparated, 64 cl::desc("list of functions to pad with amount of bytes"), 65 cl::value_desc("func1:pad1,func2:pad2,func3:pad3,..."), 66 cl::Hidden, 67 cl::cat(BoltCategory)); 68 69 static cl::opt<bool> 70 MarkFuncs("mark-funcs", 71 cl::desc("mark function boundaries with break instruction to make " 72 "sure we accidentally don't cross them"), 73 cl::ReallyHidden, 74 cl::ZeroOrMore, 75 cl::cat(BoltCategory)); 76 77 static cl::opt<bool> 78 PrintJumpTables("print-jump-tables", 79 cl::desc("print jump tables"), 80 cl::ZeroOrMore, 81 cl::Hidden, 82 cl::cat(BoltCategory)); 83 84 static cl::opt<bool> 85 X86AlignBranchBoundaryHotOnly("x86-align-branch-boundary-hot-only", 86 cl::desc("only apply branch boundary alignment in hot code"), 87 cl::init(true), 88 cl::cat(BoltOptCategory)); 89 90 size_t padFunction(const BinaryFunction &Function) { 91 static std::map<std::string, size_t> FunctionPadding; 92 93 if (FunctionPadding.empty() && !FunctionPadSpec.empty()) { 94 for (std::string &Spec : FunctionPadSpec) { 95 size_t N = Spec.find(':'); 96 if (N == std::string::npos) 97 continue; 98 std::string Name = Spec.substr(0, N); 99 size_t Padding = std::stoull(Spec.substr(N + 1)); 100 FunctionPadding[Name] = Padding; 101 } 102 } 103 104 for (auto &FPI : FunctionPadding) { 105 std::string Name = FPI.first; 106 size_t Padding = FPI.second; 107 if (Function.hasNameRegex(Name)) { 108 return Padding; 109 } 110 } 111 112 return 0; 113 } 114 115 } // namespace opts 116 117 namespace { 118 using JumpTable = bolt::JumpTable; 119 120 class BinaryEmitter { 121 private: 122 BinaryEmitter(const BinaryEmitter &) = delete; 123 BinaryEmitter &operator=(const BinaryEmitter &) = delete; 124 125 MCStreamer &Streamer; 126 BinaryContext &BC; 127 128 public: 129 BinaryEmitter(MCStreamer &Streamer, BinaryContext &BC) 130 : Streamer(Streamer), BC(BC) {} 131 132 /// Emit all code and data. 133 void emitAll(StringRef OrgSecPrefix); 134 135 /// Emit function code. The caller is responsible for emitting function 136 /// symbol(s) and setting the section to emit the code to. 137 void emitFunctionBody(BinaryFunction &BF, bool EmitColdPart, 138 bool EmitCodeOnly = false); 139 140 private: 141 /// Emit function code. 142 void emitFunctions(); 143 144 /// Emit a single function. 145 bool emitFunction(BinaryFunction &BF, bool EmitColdPart); 146 147 /// Helper for emitFunctionBody to write data inside a function 148 /// (used for AArch64) 149 void emitConstantIslands(BinaryFunction &BF, bool EmitColdPart, 150 BinaryFunction *OnBehalfOf = nullptr); 151 152 /// Emit jump tables for the function. 153 void emitJumpTables(const BinaryFunction &BF); 154 155 /// Emit jump table data. Callee supplies sections for the data. 156 void emitJumpTable(const JumpTable &JT, MCSection *HotSection, 157 MCSection *ColdSection); 158 159 void emitCFIInstruction(const MCCFIInstruction &Inst) const; 160 161 /// Emit exception handling ranges for the function. 162 void emitLSDA(BinaryFunction &BF, bool EmitColdPart); 163 164 /// Emit line number information corresponding to \p NewLoc. \p PrevLoc 165 /// provides a context for de-duplication of line number info. 166 /// \p FirstInstr indicates if \p NewLoc represents the first instruction 167 /// in a sequence, such as a function fragment. 168 /// 169 /// Return new current location which is either \p NewLoc or \p PrevLoc. 170 SMLoc emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, SMLoc PrevLoc, 171 bool FirstInstr); 172 173 /// Use \p FunctionEndSymbol to mark the end of the line info sequence. 174 /// Note that it does not automatically result in the insertion of the EOS 175 /// marker in the line table program, but provides one to the DWARF generator 176 /// when it needs it. 177 void emitLineInfoEnd(const BinaryFunction &BF, MCSymbol *FunctionEndSymbol); 178 179 /// Emit debug line info for unprocessed functions from CUs that include 180 /// emitted functions. 181 void emitDebugLineInfoForOriginalFunctions(); 182 183 /// Emit debug line for CUs that were not modified. 184 void emitDebugLineInfoForUnprocessedCUs(); 185 186 /// Emit data sections that have code references in them. 187 void emitDataSections(StringRef OrgSecPrefix); 188 }; 189 190 } // anonymous namespace 191 192 void BinaryEmitter::emitAll(StringRef OrgSecPrefix) { 193 Streamer.initSections(false, *BC.STI); 194 195 if (opts::UpdateDebugSections && BC.isELF()) { 196 // Force the emission of debug line info into allocatable section to ensure 197 // RuntimeDyld will process it without ProcessAllSections flag. 198 // 199 // NB: on MachO all sections are required for execution, hence no need 200 // to change flags/attributes. 201 MCSectionELF *ELFDwarfLineSection = 202 static_cast<MCSectionELF *>(BC.MOFI->getDwarfLineSection()); 203 ELFDwarfLineSection->setFlags(ELF::SHF_ALLOC); 204 } 205 206 if (RuntimeLibrary *RtLibrary = BC.getRuntimeLibrary()) { 207 RtLibrary->emitBinary(BC, Streamer); 208 } 209 210 BC.getTextSection()->setAlignment(Align(opts::AlignText)); 211 212 emitFunctions(); 213 214 if (opts::UpdateDebugSections) { 215 emitDebugLineInfoForOriginalFunctions(); 216 DwarfLineTable::emit(BC, Streamer); 217 } 218 219 emitDataSections(OrgSecPrefix); 220 221 Streamer.emitLabel(BC.Ctx->getOrCreateSymbol("_end")); 222 } 223 224 void BinaryEmitter::emitFunctions() { 225 auto emit = [&](const std::vector<BinaryFunction *> &Functions) { 226 const bool HasProfile = BC.NumProfiledFuncs > 0; 227 const bool OriginalAllowAutoPadding = Streamer.getAllowAutoPadding(); 228 for (BinaryFunction *Function : Functions) { 229 if (!BC.shouldEmit(*Function)) { 230 continue; 231 } 232 233 LLVM_DEBUG(dbgs() << "BOLT: generating code for function \"" << *Function 234 << "\" : " << Function->getFunctionNumber() << '\n'); 235 236 // Was any part of the function emitted. 237 bool Emitted = false; 238 239 // Turn off Intel JCC Erratum mitigation for cold code if requested 240 if (HasProfile && opts::X86AlignBranchBoundaryHotOnly && 241 !Function->hasValidProfile()) 242 Streamer.setAllowAutoPadding(false); 243 244 Emitted |= emitFunction(*Function, /*EmitColdPart=*/false); 245 246 if (Function->isSplit()) { 247 if (opts::X86AlignBranchBoundaryHotOnly) 248 Streamer.setAllowAutoPadding(false); 249 Emitted |= emitFunction(*Function, /*EmitColdPart=*/true); 250 } 251 Streamer.setAllowAutoPadding(OriginalAllowAutoPadding); 252 253 if (Emitted) 254 Function->setEmitted(/*KeepCFG=*/opts::PrintCacheMetrics); 255 } 256 }; 257 258 // Mark the start of hot text. 259 if (opts::HotText) { 260 Streamer.SwitchSection(BC.getTextSection()); 261 Streamer.emitLabel(BC.getHotTextStartSymbol()); 262 } 263 264 // Emit functions in sorted order. 265 std::vector<BinaryFunction *> SortedFunctions = BC.getSortedFunctions(); 266 emit(SortedFunctions); 267 268 // Emit functions added by BOLT. 269 emit(BC.getInjectedBinaryFunctions()); 270 271 // Mark the end of hot text. 272 if (opts::HotText) { 273 Streamer.SwitchSection(BC.getTextSection()); 274 Streamer.emitLabel(BC.getHotTextEndSymbol()); 275 } 276 } 277 278 bool BinaryEmitter::emitFunction(BinaryFunction &Function, bool EmitColdPart) { 279 if (Function.size() == 0) 280 return false; 281 282 if (Function.getState() == BinaryFunction::State::Empty) 283 return false; 284 285 MCSection *Section = 286 BC.getCodeSection(EmitColdPart ? Function.getColdCodeSectionName() 287 : Function.getCodeSectionName()); 288 Streamer.SwitchSection(Section); 289 Section->setHasInstructions(true); 290 BC.Ctx->addGenDwarfSection(Section); 291 292 if (BC.HasRelocations) { 293 Streamer.emitCodeAlignment(BinaryFunction::MinAlign, &*BC.STI); 294 uint16_t MaxAlignBytes = EmitColdPart ? Function.getMaxColdAlignmentBytes() 295 : Function.getMaxAlignmentBytes(); 296 if (MaxAlignBytes > 0) 297 Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI, 298 MaxAlignBytes); 299 } else { 300 Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI); 301 } 302 303 MCContext &Context = Streamer.getContext(); 304 const MCAsmInfo *MAI = Context.getAsmInfo(); 305 306 MCSymbol *StartSymbol = nullptr; 307 308 // Emit all symbols associated with the main function entry. 309 if (!EmitColdPart) { 310 StartSymbol = Function.getSymbol(); 311 for (MCSymbol *Symbol : Function.getSymbols()) { 312 Streamer.emitSymbolAttribute(Symbol, MCSA_ELF_TypeFunction); 313 Streamer.emitLabel(Symbol); 314 } 315 } else { 316 StartSymbol = Function.getColdSymbol(); 317 Streamer.emitSymbolAttribute(StartSymbol, MCSA_ELF_TypeFunction); 318 Streamer.emitLabel(StartSymbol); 319 } 320 321 // Emit CFI start 322 if (Function.hasCFI()) { 323 Streamer.emitCFIStartProc(/*IsSimple=*/false); 324 if (Function.getPersonalityFunction() != nullptr) { 325 Streamer.emitCFIPersonality(Function.getPersonalityFunction(), 326 Function.getPersonalityEncoding()); 327 } 328 MCSymbol *LSDASymbol = 329 EmitColdPart ? Function.getColdLSDASymbol() : Function.getLSDASymbol(); 330 if (LSDASymbol) { 331 Streamer.emitCFILsda(LSDASymbol, BC.LSDAEncoding); 332 } else { 333 Streamer.emitCFILsda(0, dwarf::DW_EH_PE_omit); 334 } 335 // Emit CFI instructions relative to the CIE 336 for (const MCCFIInstruction &CFIInstr : Function.cie()) { 337 // Only write CIE CFI insns that LLVM will not already emit 338 const std::vector<MCCFIInstruction> &FrameInstrs = 339 MAI->getInitialFrameState(); 340 if (std::find(FrameInstrs.begin(), FrameInstrs.end(), CFIInstr) == 341 FrameInstrs.end()) 342 emitCFIInstruction(CFIInstr); 343 } 344 } 345 346 assert((Function.empty() || !(*Function.begin()).isCold()) && 347 "first basic block should never be cold"); 348 349 // Emit UD2 at the beginning if requested by user. 350 if (!opts::BreakFunctionNames.empty()) { 351 for (std::string &Name : opts::BreakFunctionNames) { 352 if (Function.hasNameRegex(Name)) { 353 Streamer.emitIntValue(0x0B0F, 2); // UD2: 0F 0B 354 break; 355 } 356 } 357 } 358 359 // Emit code. 360 emitFunctionBody(Function, EmitColdPart, /*EmitCodeOnly=*/false); 361 362 // Emit padding if requested. 363 if (size_t Padding = opts::padFunction(Function)) { 364 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: padding function " << Function << " with " 365 << Padding << " bytes\n"); 366 Streamer.emitFill(Padding, MAI->getTextAlignFillValue()); 367 } 368 369 if (opts::MarkFuncs) { 370 Streamer.emitIntValue(BC.MIB->getTrapFillValue(), 1); 371 } 372 373 // Emit CFI end 374 if (Function.hasCFI()) 375 Streamer.emitCFIEndProc(); 376 377 MCSymbol *EndSymbol = EmitColdPart ? Function.getFunctionColdEndLabel() 378 : Function.getFunctionEndLabel(); 379 Streamer.emitLabel(EndSymbol); 380 381 if (MAI->hasDotTypeDotSizeDirective()) { 382 const MCExpr *SizeExpr = MCBinaryExpr::createSub( 383 MCSymbolRefExpr::create(EndSymbol, Context), 384 MCSymbolRefExpr::create(StartSymbol, Context), Context); 385 Streamer.emitELFSize(StartSymbol, SizeExpr); 386 } 387 388 if (opts::UpdateDebugSections && Function.getDWARFUnit()) 389 emitLineInfoEnd(Function, EndSymbol); 390 391 // Exception handling info for the function. 392 emitLSDA(Function, EmitColdPart); 393 394 if (!EmitColdPart && opts::JumpTables > JTS_NONE) 395 emitJumpTables(Function); 396 397 return true; 398 } 399 400 void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, bool EmitColdPart, 401 bool EmitCodeOnly) { 402 if (!EmitCodeOnly && EmitColdPart && BF.hasConstantIsland()) 403 BF.duplicateConstantIslands(); 404 405 // Track the first emitted instruction with debug info. 406 bool FirstInstr = true; 407 for (BinaryBasicBlock *BB : BF.layout()) { 408 if (EmitColdPart != BB->isCold()) 409 continue; 410 411 if ((opts::AlignBlocks || opts::PreserveBlocksAlignment) && 412 BB->getAlignment() > 1) { 413 Streamer.emitCodeAlignment(BB->getAlignment(), &*BC.STI, 414 BB->getAlignmentMaxBytes()); 415 } 416 Streamer.emitLabel(BB->getLabel()); 417 if (!EmitCodeOnly) { 418 if (MCSymbol *EntrySymbol = BF.getSecondaryEntryPointSymbol(*BB)) { 419 Streamer.emitLabel(EntrySymbol); 420 } 421 } 422 423 // Check if special alignment for macro-fusion is needed. 424 bool MayNeedMacroFusionAlignment = 425 (opts::AlignMacroOpFusion == MFT_ALL) || 426 (opts::AlignMacroOpFusion == MFT_HOT && BB->getKnownExecutionCount()); 427 BinaryBasicBlock::const_iterator MacroFusionPair; 428 if (MayNeedMacroFusionAlignment) { 429 MacroFusionPair = BB->getMacroOpFusionPair(); 430 if (MacroFusionPair == BB->end()) 431 MayNeedMacroFusionAlignment = false; 432 } 433 434 SMLoc LastLocSeen; 435 // Remember if the last instruction emitted was a prefix. 436 bool LastIsPrefix = false; 437 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 438 MCInst &Instr = *I; 439 440 if (EmitCodeOnly && BC.MIB->isPseudo(Instr)) 441 continue; 442 443 // Handle pseudo instructions. 444 if (BC.MIB->isEHLabel(Instr)) { 445 const MCSymbol *Label = BC.MIB->getTargetSymbol(Instr); 446 assert(Instr.getNumOperands() >= 1 && Label && 447 "bad EH_LABEL instruction"); 448 Streamer.emitLabel(const_cast<MCSymbol *>(Label)); 449 continue; 450 } 451 if (BC.MIB->isCFI(Instr)) { 452 emitCFIInstruction(*BF.getCFIFor(Instr)); 453 continue; 454 } 455 456 // Handle macro-fusion alignment. If we emitted a prefix as 457 // the last instruction, we should've already emitted the associated 458 // alignment hint, so don't emit it twice. 459 if (MayNeedMacroFusionAlignment && !LastIsPrefix && 460 I == MacroFusionPair) { 461 // This assumes the second instruction in the macro-op pair will get 462 // assigned to its own MCRelaxableFragment. Since all JCC instructions 463 // are relaxable, we should be safe. 464 } 465 466 if (!EmitCodeOnly && opts::UpdateDebugSections && BF.getDWARFUnit()) { 467 LastLocSeen = emitLineInfo(BF, Instr.getLoc(), LastLocSeen, FirstInstr); 468 FirstInstr = false; 469 } 470 471 // Prepare to tag this location with a label if we need to keep track of 472 // the location of calls/returns for BOLT address translation maps 473 if (!EmitCodeOnly && BF.requiresAddressTranslation() && 474 BC.MIB->hasAnnotation(Instr, "Offset")) { 475 const auto Offset = BC.MIB->getAnnotationAs<uint32_t>(Instr, "Offset"); 476 MCSymbol *LocSym = BC.Ctx->createTempSymbol(); 477 Streamer.emitLabel(LocSym); 478 BB->getLocSyms().emplace_back(Offset, LocSym); 479 } 480 481 Streamer.emitInstruction(Instr, *BC.STI); 482 LastIsPrefix = BC.MIB->isPrefix(Instr); 483 } 484 } 485 486 if (!EmitCodeOnly) 487 emitConstantIslands(BF, EmitColdPart); 488 } 489 490 void BinaryEmitter::emitConstantIslands(BinaryFunction &BF, bool EmitColdPart, 491 BinaryFunction *OnBehalfOf) { 492 if (!BF.hasIslandsInfo()) 493 return; 494 495 BinaryFunction::IslandInfo &Islands = BF.getIslandInfo(); 496 if (Islands.DataOffsets.empty() && Islands.Dependency.empty()) 497 return; 498 499 if (!OnBehalfOf) { 500 if (!EmitColdPart) 501 Streamer.emitLabel(BF.getFunctionConstantIslandLabel()); 502 else 503 Streamer.emitLabel(BF.getFunctionColdConstantIslandLabel()); 504 } 505 506 assert((!OnBehalfOf || Islands.Proxies[OnBehalfOf].size() > 0) && 507 "spurious OnBehalfOf constant island emission"); 508 509 assert(!BF.isInjected() && 510 "injected functions should not have constant islands"); 511 // Raw contents of the function. 512 StringRef SectionContents = BF.getOriginSection()->getContents(); 513 514 // Raw contents of the function. 515 StringRef FunctionContents = SectionContents.substr( 516 BF.getAddress() - BF.getOriginSection()->getAddress(), BF.getMaxSize()); 517 518 if (opts::Verbosity && !OnBehalfOf) 519 outs() << "BOLT-INFO: emitting constant island for function " << BF << "\n"; 520 521 // We split the island into smaller blocks and output labels between them. 522 auto IS = Islands.Offsets.begin(); 523 for (auto DataIter = Islands.DataOffsets.begin(); 524 DataIter != Islands.DataOffsets.end(); ++DataIter) { 525 uint64_t FunctionOffset = *DataIter; 526 uint64_t EndOffset = 0ULL; 527 528 // Determine size of this data chunk 529 auto NextData = std::next(DataIter); 530 auto CodeIter = Islands.CodeOffsets.lower_bound(*DataIter); 531 if (CodeIter == Islands.CodeOffsets.end() && 532 NextData == Islands.DataOffsets.end()) { 533 EndOffset = BF.getMaxSize(); 534 } else if (CodeIter == Islands.CodeOffsets.end()) { 535 EndOffset = *NextData; 536 } else if (NextData == Islands.DataOffsets.end()) { 537 EndOffset = *CodeIter; 538 } else { 539 EndOffset = (*CodeIter > *NextData) ? *NextData : *CodeIter; 540 } 541 542 if (FunctionOffset == EndOffset) 543 continue; // Size is zero, nothing to emit 544 545 auto emitCI = [&](uint64_t &FunctionOffset, uint64_t EndOffset) { 546 if (FunctionOffset >= EndOffset) 547 return; 548 549 for (auto It = Islands.Relocations.lower_bound(FunctionOffset); 550 It != Islands.Relocations.end(); ++It) { 551 if (It->first >= EndOffset) 552 break; 553 554 const Relocation &Relocation = It->second; 555 if (FunctionOffset < Relocation.Offset) { 556 Streamer.emitBytes( 557 FunctionContents.slice(FunctionOffset, Relocation.Offset)); 558 FunctionOffset = Relocation.Offset; 559 } 560 561 LLVM_DEBUG( 562 dbgs() << "BOLT-DEBUG: emitting constant island relocation" 563 << " for " << BF << " at offset 0x" 564 << Twine::utohexstr(Relocation.Offset) << " with size " 565 << Relocation::getSizeForType(Relocation.Type) << '\n'); 566 567 FunctionOffset += Relocation.emit(&Streamer); 568 } 569 570 assert(FunctionOffset <= EndOffset && "overflow error"); 571 if (FunctionOffset < EndOffset) { 572 Streamer.emitBytes(FunctionContents.slice(FunctionOffset, EndOffset)); 573 FunctionOffset = EndOffset; 574 } 575 }; 576 577 // Emit labels, relocs and data 578 while (IS != Islands.Offsets.end() && IS->first < EndOffset) { 579 auto NextLabelOffset = 580 IS == Islands.Offsets.end() ? EndOffset : IS->first; 581 auto NextStop = std::min(NextLabelOffset, EndOffset); 582 assert(NextStop <= EndOffset && "internal overflow error"); 583 emitCI(FunctionOffset, NextStop); 584 if (IS != Islands.Offsets.end() && FunctionOffset == IS->first) { 585 // This is a slightly complex code to decide which label to emit. We 586 // have 4 cases to handle: regular symbol, cold symbol, regular or cold 587 // symbol being emitted on behalf of an external function. 588 if (!OnBehalfOf) { 589 if (!EmitColdPart) { 590 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " 591 << IS->second->getName() << " at offset 0x" 592 << Twine::utohexstr(IS->first) << '\n'); 593 if (IS->second->isUndefined()) 594 Streamer.emitLabel(IS->second); 595 else 596 assert(BF.hasName(std::string(IS->second->getName()))); 597 } else if (Islands.ColdSymbols.count(IS->second) != 0) { 598 LLVM_DEBUG(dbgs() 599 << "BOLT-DEBUG: emitted label " 600 << Islands.ColdSymbols[IS->second]->getName() << '\n'); 601 if (Islands.ColdSymbols[IS->second]->isUndefined()) 602 Streamer.emitLabel(Islands.ColdSymbols[IS->second]); 603 } 604 } else { 605 if (!EmitColdPart) { 606 if (MCSymbol *Sym = Islands.Proxies[OnBehalfOf][IS->second]) { 607 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " 608 << Sym->getName() << '\n'); 609 Streamer.emitLabel(Sym); 610 } 611 } else if (MCSymbol *Sym = 612 Islands.ColdProxies[OnBehalfOf][IS->second]) { 613 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " << Sym->getName() 614 << '\n'); 615 Streamer.emitLabel(Sym); 616 } 617 } 618 ++IS; 619 } 620 } 621 assert(FunctionOffset <= EndOffset && "overflow error"); 622 emitCI(FunctionOffset, EndOffset); 623 } 624 assert(IS == Islands.Offsets.end() && "some symbols were not emitted!"); 625 626 if (OnBehalfOf) 627 return; 628 // Now emit constant islands from other functions that we may have used in 629 // this function. 630 for (BinaryFunction *ExternalFunc : Islands.Dependency) { 631 emitConstantIslands(*ExternalFunc, EmitColdPart, &BF); 632 } 633 } 634 635 SMLoc BinaryEmitter::emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, 636 SMLoc PrevLoc, bool FirstInstr) { 637 DWARFUnit *FunctionCU = BF.getDWARFUnit(); 638 const DWARFDebugLine::LineTable *FunctionLineTable = BF.getDWARFLineTable(); 639 assert(FunctionCU && "cannot emit line info for function without CU"); 640 641 DebugLineTableRowRef RowReference = DebugLineTableRowRef::fromSMLoc(NewLoc); 642 643 // Check if no new line info needs to be emitted. 644 if (RowReference == DebugLineTableRowRef::NULL_ROW || 645 NewLoc.getPointer() == PrevLoc.getPointer()) 646 return PrevLoc; 647 648 unsigned CurrentFilenum = 0; 649 const DWARFDebugLine::LineTable *CurrentLineTable = FunctionLineTable; 650 651 // If the CU id from the current instruction location does not 652 // match the CU id from the current function, it means that we 653 // have come across some inlined code. We must look up the CU 654 // for the instruction's original function and get the line table 655 // from that. 656 const uint64_t FunctionUnitIndex = FunctionCU->getOffset(); 657 const uint32_t CurrentUnitIndex = RowReference.DwCompileUnitIndex; 658 if (CurrentUnitIndex != FunctionUnitIndex) { 659 CurrentLineTable = BC.DwCtx->getLineTableForUnit( 660 BC.DwCtx->getCompileUnitForOffset(CurrentUnitIndex)); 661 // Add filename from the inlined function to the current CU. 662 CurrentFilenum = BC.addDebugFilenameToUnit( 663 FunctionUnitIndex, CurrentUnitIndex, 664 CurrentLineTable->Rows[RowReference.RowIndex - 1].File); 665 } 666 667 const DWARFDebugLine::Row &CurrentRow = 668 CurrentLineTable->Rows[RowReference.RowIndex - 1]; 669 if (!CurrentFilenum) 670 CurrentFilenum = CurrentRow.File; 671 672 unsigned Flags = (DWARF2_FLAG_IS_STMT * CurrentRow.IsStmt) | 673 (DWARF2_FLAG_BASIC_BLOCK * CurrentRow.BasicBlock) | 674 (DWARF2_FLAG_PROLOGUE_END * CurrentRow.PrologueEnd) | 675 (DWARF2_FLAG_EPILOGUE_BEGIN * CurrentRow.EpilogueBegin); 676 677 // Always emit is_stmt at the beginning of function fragment. 678 if (FirstInstr) 679 Flags |= DWARF2_FLAG_IS_STMT; 680 681 BC.Ctx->setCurrentDwarfLoc(CurrentFilenum, CurrentRow.Line, CurrentRow.Column, 682 Flags, CurrentRow.Isa, CurrentRow.Discriminator); 683 const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc(); 684 BC.Ctx->clearDwarfLocSeen(); 685 686 MCSymbol *LineSym = BC.Ctx->createTempSymbol(); 687 Streamer.emitLabel(LineSym); 688 689 BC.getDwarfLineTable(FunctionUnitIndex) 690 .getMCLineSections() 691 .addLineEntry(MCDwarfLineEntry(LineSym, DwarfLoc), 692 Streamer.getCurrentSectionOnly()); 693 694 return NewLoc; 695 } 696 697 void BinaryEmitter::emitLineInfoEnd(const BinaryFunction &BF, 698 MCSymbol *FunctionEndLabel) { 699 DWARFUnit *FunctionCU = BF.getDWARFUnit(); 700 assert(FunctionCU && "DWARF unit expected"); 701 BC.Ctx->setCurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_END_SEQUENCE, 0, 0); 702 const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc(); 703 BC.Ctx->clearDwarfLocSeen(); 704 BC.getDwarfLineTable(FunctionCU->getOffset()) 705 .getMCLineSections() 706 .addLineEntry(MCDwarfLineEntry(FunctionEndLabel, DwarfLoc), 707 Streamer.getCurrentSectionOnly()); 708 } 709 710 void BinaryEmitter::emitJumpTables(const BinaryFunction &BF) { 711 MCSection *ReadOnlySection = BC.MOFI->getReadOnlySection(); 712 MCSection *ReadOnlyColdSection = BC.MOFI->getContext().getELFSection( 713 ".rodata.cold", ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 714 715 if (!BF.hasJumpTables()) 716 return; 717 718 if (opts::PrintJumpTables) { 719 outs() << "BOLT-INFO: jump tables for function " << BF << ":\n"; 720 } 721 722 for (auto &JTI : BF.jumpTables()) { 723 JumpTable &JT = *JTI.second; 724 if (opts::PrintJumpTables) 725 JT.print(outs()); 726 if ((opts::JumpTables == JTS_BASIC || !BF.isSimple()) && 727 BC.HasRelocations) { 728 JT.updateOriginal(); 729 } else { 730 MCSection *HotSection, *ColdSection; 731 if (opts::JumpTables == JTS_BASIC) { 732 // In non-relocation mode we have to emit jump tables in local sections. 733 // This way we only overwrite them when the corresponding function is 734 // overwritten. 735 std::string Name = ".local." + JT.Labels[0]->getName().str(); 736 std::replace(Name.begin(), Name.end(), '/', '.'); 737 BinarySection &Section = 738 BC.registerOrUpdateSection(Name, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 739 Section.setAnonymous(true); 740 JT.setOutputSection(Section); 741 HotSection = BC.getDataSection(Name); 742 ColdSection = HotSection; 743 } else { 744 if (BF.isSimple()) { 745 HotSection = ReadOnlySection; 746 ColdSection = ReadOnlyColdSection; 747 } else { 748 HotSection = BF.hasProfile() ? ReadOnlySection : ReadOnlyColdSection; 749 ColdSection = HotSection; 750 } 751 } 752 emitJumpTable(JT, HotSection, ColdSection); 753 } 754 } 755 } 756 757 void BinaryEmitter::emitJumpTable(const JumpTable &JT, MCSection *HotSection, 758 MCSection *ColdSection) { 759 // Pre-process entries for aggressive splitting. 760 // Each label represents a separate switch table and gets its own count 761 // determining its destination. 762 std::map<MCSymbol *, uint64_t> LabelCounts; 763 if (opts::JumpTables > JTS_SPLIT && !JT.Counts.empty()) { 764 MCSymbol *CurrentLabel = JT.Labels.at(0); 765 uint64_t CurrentLabelCount = 0; 766 for (unsigned Index = 0; Index < JT.Entries.size(); ++Index) { 767 auto LI = JT.Labels.find(Index * JT.EntrySize); 768 if (LI != JT.Labels.end()) { 769 LabelCounts[CurrentLabel] = CurrentLabelCount; 770 CurrentLabel = LI->second; 771 CurrentLabelCount = 0; 772 } 773 CurrentLabelCount += JT.Counts[Index].Count; 774 } 775 LabelCounts[CurrentLabel] = CurrentLabelCount; 776 } else { 777 Streamer.SwitchSection(JT.Count > 0 ? HotSection : ColdSection); 778 Streamer.emitValueToAlignment(JT.EntrySize); 779 } 780 MCSymbol *LastLabel = nullptr; 781 uint64_t Offset = 0; 782 for (MCSymbol *Entry : JT.Entries) { 783 auto LI = JT.Labels.find(Offset); 784 if (LI != JT.Labels.end()) { 785 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitting jump table " 786 << LI->second->getName() 787 << " (originally was at address 0x" 788 << Twine::utohexstr(JT.getAddress() + Offset) 789 << (Offset ? "as part of larger jump table\n" : "\n")); 790 if (!LabelCounts.empty()) { 791 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump table count: " 792 << LabelCounts[LI->second] << '\n'); 793 if (LabelCounts[LI->second] > 0) { 794 Streamer.SwitchSection(HotSection); 795 } else { 796 Streamer.SwitchSection(ColdSection); 797 } 798 Streamer.emitValueToAlignment(JT.EntrySize); 799 } 800 Streamer.emitLabel(LI->second); 801 LastLabel = LI->second; 802 } 803 if (JT.Type == JumpTable::JTT_NORMAL) { 804 Streamer.emitSymbolValue(Entry, JT.OutputEntrySize); 805 } else { // JTT_PIC 806 const MCSymbolRefExpr *JTExpr = 807 MCSymbolRefExpr::create(LastLabel, Streamer.getContext()); 808 const MCSymbolRefExpr *E = 809 MCSymbolRefExpr::create(Entry, Streamer.getContext()); 810 const MCBinaryExpr *Value = 811 MCBinaryExpr::createSub(E, JTExpr, Streamer.getContext()); 812 Streamer.emitValue(Value, JT.EntrySize); 813 } 814 Offset += JT.EntrySize; 815 } 816 } 817 818 void BinaryEmitter::emitCFIInstruction(const MCCFIInstruction &Inst) const { 819 switch (Inst.getOperation()) { 820 default: 821 llvm_unreachable("Unexpected instruction"); 822 case MCCFIInstruction::OpDefCfaOffset: 823 Streamer.emitCFIDefCfaOffset(Inst.getOffset()); 824 break; 825 case MCCFIInstruction::OpAdjustCfaOffset: 826 Streamer.emitCFIAdjustCfaOffset(Inst.getOffset()); 827 break; 828 case MCCFIInstruction::OpDefCfa: 829 Streamer.emitCFIDefCfa(Inst.getRegister(), Inst.getOffset()); 830 break; 831 case MCCFIInstruction::OpDefCfaRegister: 832 Streamer.emitCFIDefCfaRegister(Inst.getRegister()); 833 break; 834 case MCCFIInstruction::OpOffset: 835 Streamer.emitCFIOffset(Inst.getRegister(), Inst.getOffset()); 836 break; 837 case MCCFIInstruction::OpRegister: 838 Streamer.emitCFIRegister(Inst.getRegister(), Inst.getRegister2()); 839 break; 840 case MCCFIInstruction::OpWindowSave: 841 Streamer.emitCFIWindowSave(); 842 break; 843 case MCCFIInstruction::OpNegateRAState: 844 Streamer.emitCFINegateRAState(); 845 break; 846 case MCCFIInstruction::OpSameValue: 847 Streamer.emitCFISameValue(Inst.getRegister()); 848 break; 849 case MCCFIInstruction::OpGnuArgsSize: 850 Streamer.emitCFIGnuArgsSize(Inst.getOffset()); 851 break; 852 case MCCFIInstruction::OpEscape: 853 Streamer.AddComment(Inst.getComment()); 854 Streamer.emitCFIEscape(Inst.getValues()); 855 break; 856 case MCCFIInstruction::OpRestore: 857 Streamer.emitCFIRestore(Inst.getRegister()); 858 break; 859 case MCCFIInstruction::OpUndefined: 860 Streamer.emitCFIUndefined(Inst.getRegister()); 861 break; 862 } 863 } 864 865 // The code is based on EHStreamer::emitExceptionTable(). 866 void BinaryEmitter::emitLSDA(BinaryFunction &BF, bool EmitColdPart) { 867 const BinaryFunction::CallSitesType *Sites = 868 EmitColdPart ? &BF.getColdCallSites() : &BF.getCallSites(); 869 if (Sites->empty()) { 870 return; 871 } 872 873 // Calculate callsite table size. Size of each callsite entry is: 874 // 875 // sizeof(start) + sizeof(length) + sizeof(LP) + sizeof(uleb128(action)) 876 // 877 // or 878 // 879 // sizeof(dwarf::DW_EH_PE_data4) * 3 + sizeof(uleb128(action)) 880 uint64_t CallSiteTableLength = Sites->size() * 4 * 3; 881 for (const BinaryFunction::CallSite &CallSite : *Sites) { 882 CallSiteTableLength += getULEB128Size(CallSite.Action); 883 } 884 885 Streamer.SwitchSection(BC.MOFI->getLSDASection()); 886 887 const unsigned TTypeEncoding = BC.TTypeEncoding; 888 const unsigned TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding); 889 const uint16_t TTypeAlignment = 4; 890 891 // Type tables have to be aligned at 4 bytes. 892 Streamer.emitValueToAlignment(TTypeAlignment); 893 894 // Emit the LSDA label. 895 MCSymbol *LSDASymbol = 896 EmitColdPart ? BF.getColdLSDASymbol() : BF.getLSDASymbol(); 897 assert(LSDASymbol && "no LSDA symbol set"); 898 Streamer.emitLabel(LSDASymbol); 899 900 // Corresponding FDE start. 901 const MCSymbol *StartSymbol = 902 EmitColdPart ? BF.getColdSymbol() : BF.getSymbol(); 903 904 // Emit the LSDA header. 905 906 // If LPStart is omitted, then the start of the FDE is used as a base for 907 // landing pad displacements. Then if a cold fragment starts with 908 // a landing pad, this means that the first landing pad offset will be 0. 909 // As a result, the exception handling runtime will ignore this landing pad 910 // because zero offset denotes the absence of a landing pad. 911 // For this reason, when the binary has fixed starting address we emit LPStart 912 // as 0 and output the absolute value of the landing pad in the table. 913 // 914 // If the base address can change, we cannot use absolute addresses for 915 // landing pads (at least not without runtime relocations). Hence, we fall 916 // back to emitting landing pads relative to the FDE start. 917 // As we are emitting label differences, we have to guarantee both labels are 918 // defined in the same section and hence cannot place the landing pad into a 919 // cold fragment when the corresponding call site is in the hot fragment. 920 // Because of this issue and the previously described issue of possible 921 // zero-offset landing pad we disable splitting of exception-handling 922 // code for shared objects. 923 std::function<void(const MCSymbol *)> emitLandingPad; 924 if (BC.HasFixedLoadAddress) { 925 Streamer.emitIntValue(dwarf::DW_EH_PE_udata4, 1); // LPStart format 926 Streamer.emitIntValue(0, 4); // LPStart 927 emitLandingPad = [&](const MCSymbol *LPSymbol) { 928 if (!LPSymbol) 929 Streamer.emitIntValue(0, 4); 930 else 931 Streamer.emitSymbolValue(LPSymbol, 4); 932 }; 933 } else { 934 assert(!EmitColdPart && 935 "cannot have exceptions in cold fragment for shared object"); 936 Streamer.emitIntValue(dwarf::DW_EH_PE_omit, 1); // LPStart format 937 emitLandingPad = [&](const MCSymbol *LPSymbol) { 938 if (!LPSymbol) 939 Streamer.emitIntValue(0, 4); 940 else 941 Streamer.emitAbsoluteSymbolDiff(LPSymbol, StartSymbol, 4); 942 }; 943 } 944 945 Streamer.emitIntValue(TTypeEncoding, 1); // TType format 946 947 // See the comment in EHStreamer::emitExceptionTable() on to use 948 // uleb128 encoding (which can use variable number of bytes to encode the same 949 // value) to ensure type info table is properly aligned at 4 bytes without 950 // iteratively fixing sizes of the tables. 951 unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength); 952 unsigned TTypeBaseOffset = 953 sizeof(int8_t) + // Call site format 954 CallSiteTableLengthSize + // Call site table length size 955 CallSiteTableLength + // Call site table length 956 BF.getLSDAActionTable().size() + // Actions table size 957 BF.getLSDATypeTable().size() * TTypeEncodingSize; // Types table size 958 unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset); 959 unsigned TotalSize = sizeof(int8_t) + // LPStart format 960 sizeof(int8_t) + // TType format 961 TTypeBaseOffsetSize + // TType base offset size 962 TTypeBaseOffset; // TType base offset 963 unsigned SizeAlign = (4 - TotalSize) & 3; 964 965 // Account for any extra padding that will be added to the call site table 966 // length. 967 Streamer.emitULEB128IntValue(TTypeBaseOffset, 968 /*PadTo=*/TTypeBaseOffsetSize + SizeAlign); 969 970 // Emit the landing pad call site table. We use signed data4 since we can emit 971 // a landing pad in a different part of the split function that could appear 972 // earlier in the address space than LPStart. 973 Streamer.emitIntValue(dwarf::DW_EH_PE_sdata4, 1); 974 Streamer.emitULEB128IntValue(CallSiteTableLength); 975 976 for (const BinaryFunction::CallSite &CallSite : *Sites) { 977 const MCSymbol *BeginLabel = CallSite.Start; 978 const MCSymbol *EndLabel = CallSite.End; 979 980 assert(BeginLabel && "start EH label expected"); 981 assert(EndLabel && "end EH label expected"); 982 983 // Start of the range is emitted relative to the start of current 984 // function split part. 985 Streamer.emitAbsoluteSymbolDiff(BeginLabel, StartSymbol, 4); 986 Streamer.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); 987 emitLandingPad(CallSite.LP); 988 Streamer.emitULEB128IntValue(CallSite.Action); 989 } 990 991 // Write out action, type, and type index tables at the end. 992 // 993 // For action and type index tables there's no need to change the original 994 // table format unless we are doing function splitting, in which case we can 995 // split and optimize the tables. 996 // 997 // For type table we (re-)encode the table using TTypeEncoding matching 998 // the current assembler mode. 999 for (uint8_t const &Byte : BF.getLSDAActionTable()) { 1000 Streamer.emitIntValue(Byte, 1); 1001 } 1002 1003 const BinaryFunction::LSDATypeTableTy &TypeTable = 1004 (TTypeEncoding & dwarf::DW_EH_PE_indirect) ? BF.getLSDATypeAddressTable() 1005 : BF.getLSDATypeTable(); 1006 assert(TypeTable.size() == BF.getLSDATypeTable().size() && 1007 "indirect type table size mismatch"); 1008 1009 for (int Index = TypeTable.size() - 1; Index >= 0; --Index) { 1010 const uint64_t TypeAddress = TypeTable[Index]; 1011 switch (TTypeEncoding & 0x70) { 1012 default: 1013 llvm_unreachable("unsupported TTypeEncoding"); 1014 case dwarf::DW_EH_PE_absptr: 1015 Streamer.emitIntValue(TypeAddress, TTypeEncodingSize); 1016 break; 1017 case dwarf::DW_EH_PE_pcrel: { 1018 if (TypeAddress) { 1019 const MCSymbol *TypeSymbol = 1020 BC.getOrCreateGlobalSymbol(TypeAddress, "TI", 0, TTypeAlignment); 1021 MCSymbol *DotSymbol = BC.Ctx->createNamedTempSymbol(); 1022 Streamer.emitLabel(DotSymbol); 1023 const MCBinaryExpr *SubDotExpr = MCBinaryExpr::createSub( 1024 MCSymbolRefExpr::create(TypeSymbol, *BC.Ctx), 1025 MCSymbolRefExpr::create(DotSymbol, *BC.Ctx), *BC.Ctx); 1026 Streamer.emitValue(SubDotExpr, TTypeEncodingSize); 1027 } else { 1028 Streamer.emitIntValue(0, TTypeEncodingSize); 1029 } 1030 break; 1031 } 1032 } 1033 } 1034 for (uint8_t const &Byte : BF.getLSDATypeIndexTable()) { 1035 Streamer.emitIntValue(Byte, 1); 1036 } 1037 } 1038 1039 void BinaryEmitter::emitDebugLineInfoForOriginalFunctions() { 1040 // If a function is in a CU containing at least one processed function, we 1041 // have to rewrite the whole line table for that CU. For unprocessed functions 1042 // we use data from the input line table. 1043 for (auto &It : BC.getBinaryFunctions()) { 1044 const BinaryFunction &Function = It.second; 1045 1046 // If the function was emitted, its line info was emitted with it. 1047 if (Function.isEmitted()) 1048 continue; 1049 1050 const DWARFDebugLine::LineTable *LineTable = Function.getDWARFLineTable(); 1051 if (!LineTable) 1052 continue; // nothing to update for this function 1053 1054 const uint64_t Address = Function.getAddress(); 1055 std::vector<uint32_t> Results; 1056 if (!LineTable->lookupAddressRange( 1057 {Address, object::SectionedAddress::UndefSection}, 1058 Function.getSize(), Results)) 1059 continue; 1060 1061 if (Results.empty()) 1062 continue; 1063 1064 // The first row returned could be the last row matching the start address. 1065 // Find the first row with the same address that is not the end of the 1066 // sequence. 1067 uint64_t FirstRow = Results.front(); 1068 while (FirstRow > 0) { 1069 const DWARFDebugLine::Row &PrevRow = LineTable->Rows[FirstRow - 1]; 1070 if (PrevRow.Address.Address != Address || PrevRow.EndSequence) 1071 break; 1072 --FirstRow; 1073 } 1074 1075 const uint64_t EndOfSequenceAddress = 1076 Function.getAddress() + Function.getMaxSize(); 1077 BC.getDwarfLineTable(Function.getDWARFUnit()->getOffset()) 1078 .addLineTableSequence(LineTable, FirstRow, Results.back(), 1079 EndOfSequenceAddress); 1080 } 1081 1082 // For units that are completely unprocessed, use original debug line contents 1083 // eliminating the need to regenerate line info program. 1084 emitDebugLineInfoForUnprocessedCUs(); 1085 } 1086 1087 void BinaryEmitter::emitDebugLineInfoForUnprocessedCUs() { 1088 // Sorted list of section offsets provides boundaries for section fragments, 1089 // where each fragment is the unit's contribution to debug line section. 1090 std::vector<uint64_t> StmtListOffsets; 1091 StmtListOffsets.reserve(BC.DwCtx->getNumCompileUnits()); 1092 for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) { 1093 DWARFDie CUDie = CU->getUnitDIE(); 1094 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list)); 1095 if (!StmtList) 1096 continue; 1097 1098 StmtListOffsets.push_back(*StmtList); 1099 } 1100 std::sort(StmtListOffsets.begin(), StmtListOffsets.end()); 1101 1102 // For each CU that was not processed, emit its line info as a binary blob. 1103 for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) { 1104 if (BC.ProcessedCUs.count(CU.get())) 1105 continue; 1106 1107 DWARFDie CUDie = CU->getUnitDIE(); 1108 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list)); 1109 if (!StmtList) 1110 continue; 1111 1112 StringRef DebugLineContents = CU->getLineSection().Data; 1113 1114 const uint64_t Begin = *StmtList; 1115 1116 // Statement list ends where the next unit contribution begins, or at the 1117 // end of the section. 1118 auto It = 1119 std::upper_bound(StmtListOffsets.begin(), StmtListOffsets.end(), Begin); 1120 const uint64_t End = 1121 It == StmtListOffsets.end() ? DebugLineContents.size() : *It; 1122 1123 BC.getDwarfLineTable(CU->getOffset()) 1124 .addRawContents(DebugLineContents.slice(Begin, End)); 1125 } 1126 } 1127 1128 void BinaryEmitter::emitDataSections(StringRef OrgSecPrefix) { 1129 for (BinarySection &Section : BC.sections()) { 1130 if (!Section.hasRelocations() || !Section.hasSectionRef()) 1131 continue; 1132 1133 StringRef SectionName = Section.getName(); 1134 std::string EmitName = Section.isReordered() 1135 ? std::string(Section.getOutputName()) 1136 : OrgSecPrefix.str() + std::string(SectionName); 1137 Section.emitAsData(Streamer, EmitName); 1138 Section.clearRelocations(); 1139 } 1140 } 1141 1142 namespace llvm { 1143 namespace bolt { 1144 1145 void emitBinaryContext(MCStreamer &Streamer, BinaryContext &BC, 1146 StringRef OrgSecPrefix) { 1147 BinaryEmitter(Streamer, BC).emitAll(OrgSecPrefix); 1148 } 1149 1150 void emitFunctionBody(MCStreamer &Streamer, BinaryFunction &BF, 1151 bool EmitColdPart, bool EmitCodeOnly) { 1152 BinaryEmitter(Streamer, BF.getBinaryContext()) 1153 .emitFunctionBody(BF, EmitColdPart, EmitCodeOnly); 1154 } 1155 1156 } // namespace bolt 1157 } // namespace llvm 1158