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