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