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