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