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