xref: /llvm-project/bolt/lib/Core/BinaryEmitter.cpp (revision 101344af1af82d1633c773b718788eaa813d7f79)
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, bool EmitColdPart);
158 
159   /// Emit line number information corresponding to \p NewLoc. \p PrevLoc
160   /// provides a context for de-duplication of line number info.
161   /// \p FirstInstr indicates if \p NewLoc represents the first instruction
162   /// in a sequence, such as a function fragment.
163   ///
164   /// Return new current location which is either \p NewLoc or \p PrevLoc.
165   SMLoc emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, SMLoc PrevLoc,
166                      bool FirstInstr);
167 
168   /// Use \p FunctionEndSymbol to mark the end of the line info sequence.
169   /// Note that it does not automatically result in the insertion of the EOS
170   /// marker in the line table program, but provides one to the DWARF generator
171   /// when it needs it.
172   void emitLineInfoEnd(const BinaryFunction &BF, MCSymbol *FunctionEndSymbol);
173 
174   /// Emit debug line info for unprocessed functions from CUs that include
175   /// emitted functions.
176   void emitDebugLineInfoForOriginalFunctions();
177 
178   /// Emit debug line for CUs that were not modified.
179   void emitDebugLineInfoForUnprocessedCUs();
180 
181   /// Emit data sections that have code references in them.
182   void emitDataSections(StringRef OrgSecPrefix);
183 };
184 
185 } // anonymous namespace
186 
187 void BinaryEmitter::emitAll(StringRef OrgSecPrefix) {
188   Streamer.initSections(false, *BC.STI);
189 
190   if (opts::UpdateDebugSections && BC.isELF()) {
191     // Force the emission of debug line info into allocatable section to ensure
192     // RuntimeDyld will process it without ProcessAllSections flag.
193     //
194     // NB: on MachO all sections are required for execution, hence no need
195     //     to change flags/attributes.
196     MCSectionELF *ELFDwarfLineSection =
197         static_cast<MCSectionELF *>(BC.MOFI->getDwarfLineSection());
198     ELFDwarfLineSection->setFlags(ELF::SHF_ALLOC);
199   }
200 
201   if (RuntimeLibrary *RtLibrary = BC.getRuntimeLibrary())
202     RtLibrary->emitBinary(BC, Streamer);
203 
204   BC.getTextSection()->setAlignment(Align(opts::AlignText));
205 
206   emitFunctions();
207 
208   if (opts::UpdateDebugSections) {
209     emitDebugLineInfoForOriginalFunctions();
210     DwarfLineTable::emit(BC, Streamer);
211   }
212 
213   emitDataSections(OrgSecPrefix);
214 
215   Streamer.emitLabel(BC.Ctx->getOrCreateSymbol("_end"));
216 }
217 
218 void BinaryEmitter::emitFunctions() {
219   auto emit = [&](const std::vector<BinaryFunction *> &Functions) {
220     const bool HasProfile = BC.NumProfiledFuncs > 0;
221     const bool OriginalAllowAutoPadding = Streamer.getAllowAutoPadding();
222     for (BinaryFunction *Function : Functions) {
223       if (!BC.shouldEmit(*Function))
224         continue;
225 
226       LLVM_DEBUG(dbgs() << "BOLT: generating code for function \"" << *Function
227                         << "\" : " << Function->getFunctionNumber() << '\n');
228 
229       // Was any part of the function emitted.
230       bool Emitted = false;
231 
232       // Turn off Intel JCC Erratum mitigation for cold code if requested
233       if (HasProfile && opts::X86AlignBranchBoundaryHotOnly &&
234           !Function->hasValidProfile())
235         Streamer.setAllowAutoPadding(false);
236 
237       FunctionLayout &Layout = Function->getLayout();
238       Emitted |= emitFunction(*Function, Layout.getMainFragment());
239 
240       if (Function->isSplit()) {
241         if (opts::X86AlignBranchBoundaryHotOnly)
242           Streamer.setAllowAutoPadding(false);
243 
244         assert((Layout.fragment_size() == 1 || Function->isSimple()) &&
245                "Only simple functions can have fragments");
246         for (FunctionFragment &FF : Layout.getSplitFragments()) {
247           // Skip empty fragments so no symbols and sections for empty fragments
248           // are generated
249           if (FF.empty() && !Function->hasConstantIsland())
250             continue;
251           Emitted |= emitFunction(*Function, FF);
252         }
253       }
254 
255       Streamer.setAllowAutoPadding(OriginalAllowAutoPadding);
256 
257       if (Emitted)
258         Function->setEmitted(/*KeepCFG=*/opts::PrintCacheMetrics);
259     }
260   };
261 
262   // Mark the start of hot text.
263   if (opts::HotText) {
264     Streamer.switchSection(BC.getTextSection());
265     Streamer.emitLabel(BC.getHotTextStartSymbol());
266   }
267 
268   // Emit functions in sorted order.
269   std::vector<BinaryFunction *> SortedFunctions = BC.getSortedFunctions();
270   emit(SortedFunctions);
271 
272   // Emit functions added by BOLT.
273   emit(BC.getInjectedBinaryFunctions());
274 
275   // Mark the end of hot text.
276   if (opts::HotText) {
277     Streamer.switchSection(BC.getTextSection());
278     Streamer.emitLabel(BC.getHotTextEndSymbol());
279   }
280 }
281 
282 bool BinaryEmitter::emitFunction(BinaryFunction &Function,
283                                  FunctionFragment &FF) {
284   if (Function.size() == 0 && !Function.hasIslandsInfo())
285     return false;
286 
287   if (Function.getState() == BinaryFunction::State::Empty)
288     return false;
289 
290   MCSection *Section =
291       BC.getCodeSection(Function.getCodeSectionName(FF.getFragmentNum()));
292   Streamer.switchSection(Section);
293   Section->setHasInstructions(true);
294   BC.Ctx->addGenDwarfSection(Section);
295 
296   if (BC.HasRelocations) {
297     // Set section alignment to at least maximum possible object alignment.
298     // We need this to support LongJmp and other passes that calculates
299     // tentative layout.
300     if (Section->getAlignment() < opts::AlignFunctions)
301       Section->setAlignment(Align(opts::AlignFunctions));
302 
303     Streamer.emitCodeAlignment(BinaryFunction::MinAlign, &*BC.STI);
304     uint16_t MaxAlignBytes = FF.isSplitFragment()
305                                  ? Function.getMaxColdAlignmentBytes()
306                                  : Function.getMaxAlignmentBytes();
307     if (MaxAlignBytes > 0)
308       Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI,
309                                  MaxAlignBytes);
310   } else {
311     Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI);
312   }
313 
314   MCContext &Context = Streamer.getContext();
315   const MCAsmInfo *MAI = Context.getAsmInfo();
316 
317   MCSymbol *const StartSymbol = Function.getSymbol(FF.getFragmentNum());
318 
319   // Emit all symbols associated with the main function entry.
320   if (FF.isMainFragment()) {
321     for (MCSymbol *Symbol : Function.getSymbols()) {
322       Streamer.emitSymbolAttribute(Symbol, MCSA_ELF_TypeFunction);
323       Streamer.emitLabel(Symbol);
324     }
325   } else {
326     Streamer.emitSymbolAttribute(StartSymbol, MCSA_ELF_TypeFunction);
327     Streamer.emitLabel(StartSymbol);
328   }
329 
330   // Emit CFI start
331   if (Function.hasCFI()) {
332     Streamer.emitCFIStartProc(/*IsSimple=*/false);
333     if (Function.getPersonalityFunction() != nullptr)
334       Streamer.emitCFIPersonality(Function.getPersonalityFunction(),
335                                   Function.getPersonalityEncoding());
336     MCSymbol *LSDASymbol = FF.isSplitFragment()
337                                ? Function.getColdLSDASymbol(FF.getFragmentNum())
338                                : Function.getLSDASymbol();
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.isSplitFragment());
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->getAlignment(), &*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(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     if (opts::PrintJumpTables)
743       JT.print(outs());
744     if ((opts::JumpTables == JTS_BASIC || !BF.isSimple()) &&
745         BC.HasRelocations) {
746       JT.updateOriginal();
747     } else {
748       MCSection *HotSection, *ColdSection;
749       if (opts::JumpTables == JTS_BASIC) {
750         // In non-relocation mode we have to emit jump tables in local sections.
751         // This way we only overwrite them when the corresponding function is
752         // overwritten.
753         std::string Name = ".local." + JT.Labels[0]->getName().str();
754         std::replace(Name.begin(), Name.end(), '/', '.');
755         BinarySection &Section =
756             BC.registerOrUpdateSection(Name, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
757         Section.setAnonymous(true);
758         JT.setOutputSection(Section);
759         HotSection = BC.getDataSection(Name);
760         ColdSection = HotSection;
761       } else {
762         if (BF.isSimple()) {
763           HotSection = ReadOnlySection;
764           ColdSection = ReadOnlyColdSection;
765         } else {
766           HotSection = BF.hasProfile() ? ReadOnlySection : ReadOnlyColdSection;
767           ColdSection = HotSection;
768         }
769       }
770       emitJumpTable(JT, HotSection, ColdSection);
771     }
772   }
773 }
774 
775 void BinaryEmitter::emitJumpTable(const JumpTable &JT, MCSection *HotSection,
776                                   MCSection *ColdSection) {
777   // Pre-process entries for aggressive splitting.
778   // Each label represents a separate switch table and gets its own count
779   // determining its destination.
780   std::map<MCSymbol *, uint64_t> LabelCounts;
781   if (opts::JumpTables > JTS_SPLIT && !JT.Counts.empty()) {
782     MCSymbol *CurrentLabel = JT.Labels.at(0);
783     uint64_t CurrentLabelCount = 0;
784     for (unsigned Index = 0; Index < JT.Entries.size(); ++Index) {
785       auto LI = JT.Labels.find(Index * JT.EntrySize);
786       if (LI != JT.Labels.end()) {
787         LabelCounts[CurrentLabel] = CurrentLabelCount;
788         CurrentLabel = LI->second;
789         CurrentLabelCount = 0;
790       }
791       CurrentLabelCount += JT.Counts[Index].Count;
792     }
793     LabelCounts[CurrentLabel] = CurrentLabelCount;
794   } else {
795     Streamer.switchSection(JT.Count > 0 ? HotSection : ColdSection);
796     Streamer.emitValueToAlignment(JT.EntrySize);
797   }
798   MCSymbol *LastLabel = nullptr;
799   uint64_t Offset = 0;
800   for (MCSymbol *Entry : JT.Entries) {
801     auto LI = JT.Labels.find(Offset);
802     if (LI != JT.Labels.end()) {
803       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitting jump table "
804                         << LI->second->getName()
805                         << " (originally was at address 0x"
806                         << Twine::utohexstr(JT.getAddress() + Offset)
807                         << (Offset ? "as part of larger jump table\n" : "\n"));
808       if (!LabelCounts.empty()) {
809         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump table count: "
810                           << LabelCounts[LI->second] << '\n');
811         if (LabelCounts[LI->second] > 0)
812           Streamer.switchSection(HotSection);
813         else
814           Streamer.switchSection(ColdSection);
815         Streamer.emitValueToAlignment(JT.EntrySize);
816       }
817       Streamer.emitLabel(LI->second);
818       LastLabel = LI->second;
819     }
820     if (JT.Type == JumpTable::JTT_NORMAL) {
821       Streamer.emitSymbolValue(Entry, JT.OutputEntrySize);
822     } else { // JTT_PIC
823       const MCSymbolRefExpr *JTExpr =
824           MCSymbolRefExpr::create(LastLabel, Streamer.getContext());
825       const MCSymbolRefExpr *E =
826           MCSymbolRefExpr::create(Entry, Streamer.getContext());
827       const MCBinaryExpr *Value =
828           MCBinaryExpr::createSub(E, JTExpr, Streamer.getContext());
829       Streamer.emitValue(Value, JT.EntrySize);
830     }
831     Offset += JT.EntrySize;
832   }
833 }
834 
835 void BinaryEmitter::emitCFIInstruction(const MCCFIInstruction &Inst) const {
836   switch (Inst.getOperation()) {
837   default:
838     llvm_unreachable("Unexpected instruction");
839   case MCCFIInstruction::OpDefCfaOffset:
840     Streamer.emitCFIDefCfaOffset(Inst.getOffset());
841     break;
842   case MCCFIInstruction::OpAdjustCfaOffset:
843     Streamer.emitCFIAdjustCfaOffset(Inst.getOffset());
844     break;
845   case MCCFIInstruction::OpDefCfa:
846     Streamer.emitCFIDefCfa(Inst.getRegister(), Inst.getOffset());
847     break;
848   case MCCFIInstruction::OpDefCfaRegister:
849     Streamer.emitCFIDefCfaRegister(Inst.getRegister());
850     break;
851   case MCCFIInstruction::OpOffset:
852     Streamer.emitCFIOffset(Inst.getRegister(), Inst.getOffset());
853     break;
854   case MCCFIInstruction::OpRegister:
855     Streamer.emitCFIRegister(Inst.getRegister(), Inst.getRegister2());
856     break;
857   case MCCFIInstruction::OpWindowSave:
858     Streamer.emitCFIWindowSave();
859     break;
860   case MCCFIInstruction::OpNegateRAState:
861     Streamer.emitCFINegateRAState();
862     break;
863   case MCCFIInstruction::OpSameValue:
864     Streamer.emitCFISameValue(Inst.getRegister());
865     break;
866   case MCCFIInstruction::OpGnuArgsSize:
867     Streamer.emitCFIGnuArgsSize(Inst.getOffset());
868     break;
869   case MCCFIInstruction::OpEscape:
870     Streamer.AddComment(Inst.getComment());
871     Streamer.emitCFIEscape(Inst.getValues());
872     break;
873   case MCCFIInstruction::OpRestore:
874     Streamer.emitCFIRestore(Inst.getRegister());
875     break;
876   case MCCFIInstruction::OpUndefined:
877     Streamer.emitCFIUndefined(Inst.getRegister());
878     break;
879   }
880 }
881 
882 // The code is based on EHStreamer::emitExceptionTable().
883 void BinaryEmitter::emitLSDA(BinaryFunction &BF, bool EmitColdPart) {
884   const BinaryFunction::CallSitesType *Sites =
885       EmitColdPart ? &BF.getColdCallSites() : &BF.getCallSites();
886   if (Sites->empty())
887     return;
888 
889   // Calculate callsite table size. Size of each callsite entry is:
890   //
891   //  sizeof(start) + sizeof(length) + sizeof(LP) + sizeof(uleb128(action))
892   //
893   // or
894   //
895   //  sizeof(dwarf::DW_EH_PE_data4) * 3 + sizeof(uleb128(action))
896   uint64_t CallSiteTableLength = Sites->size() * 4 * 3;
897   for (const BinaryFunction::CallSite &CallSite : *Sites)
898     CallSiteTableLength += getULEB128Size(CallSite.Action);
899 
900   Streamer.switchSection(BC.MOFI->getLSDASection());
901 
902   const unsigned TTypeEncoding = BC.TTypeEncoding;
903   const unsigned TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding);
904   const uint16_t TTypeAlignment = 4;
905 
906   // Type tables have to be aligned at 4 bytes.
907   Streamer.emitValueToAlignment(TTypeAlignment);
908 
909   // Emit the LSDA label.
910   MCSymbol *LSDASymbol = EmitColdPart
911                              ? BF.getColdLSDASymbol(FragmentNum::cold())
912                              : BF.getLSDASymbol();
913   assert(LSDASymbol && "no LSDA symbol set");
914   Streamer.emitLabel(LSDASymbol);
915 
916   // Corresponding FDE start.
917   const MCSymbol *StartSymbol =
918       BF.getSymbol(EmitColdPart ? FragmentNum::cold() : FragmentNum::main());
919 
920   // Emit the LSDA header.
921 
922   // If LPStart is omitted, then the start of the FDE is used as a base for
923   // landing pad displacements. Then if a cold fragment starts with
924   // a landing pad, this means that the first landing pad offset will be 0.
925   // As a result, the exception handling runtime will ignore this landing pad
926   // because zero offset denotes the absence of a landing pad.
927   // For this reason, when the binary has fixed starting address we emit LPStart
928   // as 0 and output the absolute value of the landing pad in the table.
929   //
930   // If the base address can change, we cannot use absolute addresses for
931   // landing pads (at least not without runtime relocations). Hence, we fall
932   // back to emitting landing pads relative to the FDE start.
933   // As we are emitting label differences, we have to guarantee both labels are
934   // defined in the same section and hence cannot place the landing pad into a
935   // cold fragment when the corresponding call site is in the hot fragment.
936   // Because of this issue and the previously described issue of possible
937   // zero-offset landing pad we have to place landing pads in the same section
938   // as the corresponding invokes for shared objects.
939   std::function<void(const MCSymbol *)> emitLandingPad;
940   if (BC.HasFixedLoadAddress) {
941     Streamer.emitIntValue(dwarf::DW_EH_PE_udata4, 1); // LPStart format
942     Streamer.emitIntValue(0, 4);                      // LPStart
943     emitLandingPad = [&](const MCSymbol *LPSymbol) {
944       if (!LPSymbol)
945         Streamer.emitIntValue(0, 4);
946       else
947         Streamer.emitSymbolValue(LPSymbol, 4);
948     };
949   } else {
950     Streamer.emitIntValue(dwarf::DW_EH_PE_omit, 1); // LPStart format
951     emitLandingPad = [&](const MCSymbol *LPSymbol) {
952       if (!LPSymbol)
953         Streamer.emitIntValue(0, 4);
954       else
955         Streamer.emitAbsoluteSymbolDiff(LPSymbol, StartSymbol, 4);
956     };
957   }
958 
959   Streamer.emitIntValue(TTypeEncoding, 1); // TType format
960 
961   // See the comment in EHStreamer::emitExceptionTable() on to use
962   // uleb128 encoding (which can use variable number of bytes to encode the same
963   // value) to ensure type info table is properly aligned at 4 bytes without
964   // iteratively fixing sizes of the tables.
965   unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength);
966   unsigned TTypeBaseOffset =
967       sizeof(int8_t) +                 // Call site format
968       CallSiteTableLengthSize +        // Call site table length size
969       CallSiteTableLength +            // Call site table length
970       BF.getLSDAActionTable().size() + // Actions table size
971       BF.getLSDATypeTable().size() * TTypeEncodingSize; // Types table size
972   unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset);
973   unsigned TotalSize = sizeof(int8_t) +      // LPStart format
974                        sizeof(int8_t) +      // TType format
975                        TTypeBaseOffsetSize + // TType base offset size
976                        TTypeBaseOffset;      // TType base offset
977   unsigned SizeAlign = (4 - TotalSize) & 3;
978 
979   // Account for any extra padding that will be added to the call site table
980   // length.
981   Streamer.emitULEB128IntValue(TTypeBaseOffset,
982                                /*PadTo=*/TTypeBaseOffsetSize + SizeAlign);
983 
984   // Emit the landing pad call site table. We use signed data4 since we can emit
985   // a landing pad in a different part of the split function that could appear
986   // earlier in the address space than LPStart.
987   Streamer.emitIntValue(dwarf::DW_EH_PE_sdata4, 1);
988   Streamer.emitULEB128IntValue(CallSiteTableLength);
989 
990   for (const BinaryFunction::CallSite &CallSite : *Sites) {
991     const MCSymbol *BeginLabel = CallSite.Start;
992     const MCSymbol *EndLabel = CallSite.End;
993 
994     assert(BeginLabel && "start EH label expected");
995     assert(EndLabel && "end EH label expected");
996 
997     // Start of the range is emitted relative to the start of current
998     // function split part.
999     Streamer.emitAbsoluteSymbolDiff(BeginLabel, StartSymbol, 4);
1000     Streamer.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1001     emitLandingPad(CallSite.LP);
1002     Streamer.emitULEB128IntValue(CallSite.Action);
1003   }
1004 
1005   // Write out action, type, and type index tables at the end.
1006   //
1007   // For action and type index tables there's no need to change the original
1008   // table format unless we are doing function splitting, in which case we can
1009   // split and optimize the tables.
1010   //
1011   // For type table we (re-)encode the table using TTypeEncoding matching
1012   // the current assembler mode.
1013   for (uint8_t const &Byte : BF.getLSDAActionTable())
1014     Streamer.emitIntValue(Byte, 1);
1015 
1016   const BinaryFunction::LSDATypeTableTy &TypeTable =
1017       (TTypeEncoding & dwarf::DW_EH_PE_indirect) ? BF.getLSDATypeAddressTable()
1018                                                  : BF.getLSDATypeTable();
1019   assert(TypeTable.size() == BF.getLSDATypeTable().size() &&
1020          "indirect type table size mismatch");
1021 
1022   for (int Index = TypeTable.size() - 1; Index >= 0; --Index) {
1023     const uint64_t TypeAddress = TypeTable[Index];
1024     switch (TTypeEncoding & 0x70) {
1025     default:
1026       llvm_unreachable("unsupported TTypeEncoding");
1027     case dwarf::DW_EH_PE_absptr:
1028       Streamer.emitIntValue(TypeAddress, TTypeEncodingSize);
1029       break;
1030     case dwarf::DW_EH_PE_pcrel: {
1031       if (TypeAddress) {
1032         const MCSymbol *TypeSymbol =
1033             BC.getOrCreateGlobalSymbol(TypeAddress, "TI", 0, TTypeAlignment);
1034         MCSymbol *DotSymbol = BC.Ctx->createNamedTempSymbol();
1035         Streamer.emitLabel(DotSymbol);
1036         const MCBinaryExpr *SubDotExpr = MCBinaryExpr::createSub(
1037             MCSymbolRefExpr::create(TypeSymbol, *BC.Ctx),
1038             MCSymbolRefExpr::create(DotSymbol, *BC.Ctx), *BC.Ctx);
1039         Streamer.emitValue(SubDotExpr, TTypeEncodingSize);
1040       } else {
1041         Streamer.emitIntValue(0, TTypeEncodingSize);
1042       }
1043       break;
1044     }
1045     }
1046   }
1047   for (uint8_t const &Byte : BF.getLSDATypeIndexTable())
1048     Streamer.emitIntValue(Byte, 1);
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   llvm::sort(StmtListOffsets);
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 = llvm::upper_bound(StmtListOffsets, Begin);
1131     const uint64_t End =
1132         It == StmtListOffsets.end() ? DebugLineContents.size() : *It;
1133 
1134     BC.getDwarfLineTable(CU->getOffset())
1135         .addRawContents(DebugLineContents.slice(Begin, End));
1136   }
1137 }
1138 
1139 void BinaryEmitter::emitDataSections(StringRef OrgSecPrefix) {
1140   for (BinarySection &Section : BC.sections()) {
1141     if (!Section.hasRelocations() || !Section.hasSectionRef())
1142       continue;
1143 
1144     StringRef SectionName = Section.getName();
1145     std::string EmitName = Section.isReordered()
1146                                ? std::string(Section.getOutputName())
1147                                : OrgSecPrefix.str() + std::string(SectionName);
1148     Section.emitAsData(Streamer, EmitName);
1149     Section.clearRelocations();
1150   }
1151 }
1152 
1153 namespace llvm {
1154 namespace bolt {
1155 
1156 void emitBinaryContext(MCStreamer &Streamer, BinaryContext &BC,
1157                        StringRef OrgSecPrefix) {
1158   BinaryEmitter(Streamer, BC).emitAll(OrgSecPrefix);
1159 }
1160 
1161 void emitFunctionBody(MCStreamer &Streamer, BinaryFunction &BF,
1162                       FunctionFragment &FF, bool EmitCodeOnly) {
1163   BinaryEmitter(Streamer, BF.getBinaryContext())
1164       .emitFunctionBody(BF, FF, EmitCodeOnly);
1165 }
1166 
1167 } // namespace bolt
1168 } // namespace llvm
1169