xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/EHStreamer.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer ---===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains support for writing exception info into assembly files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "EHStreamer.h"
140b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
150b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
160b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
170b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
220b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
230b57cec5SDimitry Andric #include "llvm/IR/Function.h"
240b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
250b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
280b57cec5SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
290b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
300b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
310b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <cassert>
340b57cec5SDimitry Andric #include <cstdint>
350b57cec5SDimitry Andric #include <vector>
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric using namespace llvm;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric EHStreamer::EHStreamer(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric EHStreamer::~EHStreamer() = default;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric /// How many leading type ids two landing pads have in common.
440b57cec5SDimitry Andric unsigned EHStreamer::sharedTypeIDs(const LandingPadInfo *L,
450b57cec5SDimitry Andric                                    const LandingPadInfo *R) {
460b57cec5SDimitry Andric   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
47*e8d8bef9SDimitry Andric   return std::mismatch(LIds.begin(), LIds.end(), RIds.begin(), RIds.end())
48*e8d8bef9SDimitry Andric              .first -
49*e8d8bef9SDimitry Andric          LIds.begin();
500b57cec5SDimitry Andric }
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric /// Compute the actions table and gather the first action index for each landing
530b57cec5SDimitry Andric /// pad site.
540b57cec5SDimitry Andric void EHStreamer::computeActionsTable(
550b57cec5SDimitry Andric     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
560b57cec5SDimitry Andric     SmallVectorImpl<ActionEntry> &Actions,
570b57cec5SDimitry Andric     SmallVectorImpl<unsigned> &FirstActions) {
580b57cec5SDimitry Andric   // The action table follows the call-site table in the LSDA. The individual
590b57cec5SDimitry Andric   // records are of two types:
600b57cec5SDimitry Andric   //
610b57cec5SDimitry Andric   //   * Catch clause
620b57cec5SDimitry Andric   //   * Exception specification
630b57cec5SDimitry Andric   //
640b57cec5SDimitry Andric   // The two record kinds have the same format, with only small differences.
650b57cec5SDimitry Andric   // They are distinguished by the "switch value" field: Catch clauses
660b57cec5SDimitry Andric   // (TypeInfos) have strictly positive switch values, and exception
670b57cec5SDimitry Andric   // specifications (FilterIds) have strictly negative switch values. Value 0
680b57cec5SDimitry Andric   // indicates a catch-all clause.
690b57cec5SDimitry Andric   //
700b57cec5SDimitry Andric   // Negative type IDs index into FilterIds. Positive type IDs index into
710b57cec5SDimitry Andric   // TypeInfos.  The value written for a positive type ID is just the type ID
720b57cec5SDimitry Andric   // itself.  For a negative type ID, however, the value written is the
730b57cec5SDimitry Andric   // (negative) byte offset of the corresponding FilterIds entry.  The byte
740b57cec5SDimitry Andric   // offset is usually equal to the type ID (because the FilterIds entries are
750b57cec5SDimitry Andric   // written using a variable width encoding, which outputs one byte per entry
760b57cec5SDimitry Andric   // as long as the value written is not too large) but can differ.  This kind
770b57cec5SDimitry Andric   // of complication does not occur for positive type IDs because type infos are
780b57cec5SDimitry Andric   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
790b57cec5SDimitry Andric   // offset corresponding to FilterIds[i].
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric   const std::vector<unsigned> &FilterIds = Asm->MF->getFilterIds();
820b57cec5SDimitry Andric   SmallVector<int, 16> FilterOffsets;
830b57cec5SDimitry Andric   FilterOffsets.reserve(FilterIds.size());
840b57cec5SDimitry Andric   int Offset = -1;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   for (std::vector<unsigned>::const_iterator
870b57cec5SDimitry Andric          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
880b57cec5SDimitry Andric     FilterOffsets.push_back(Offset);
890b57cec5SDimitry Andric     Offset -= getULEB128Size(*I);
900b57cec5SDimitry Andric   }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   FirstActions.reserve(LandingPads.size());
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   int FirstAction = 0;
950b57cec5SDimitry Andric   unsigned SizeActions = 0; // Total size of all action entries for a function
960b57cec5SDimitry Andric   const LandingPadInfo *PrevLPI = nullptr;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
990b57cec5SDimitry Andric          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
1000b57cec5SDimitry Andric     const LandingPadInfo *LPI = *I;
1010b57cec5SDimitry Andric     const std::vector<int> &TypeIds = LPI->TypeIds;
1020b57cec5SDimitry Andric     unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0;
1030b57cec5SDimitry Andric     unsigned SizeSiteActions = 0; // Total size of all entries for a landingpad
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric     if (NumShared < TypeIds.size()) {
1060b57cec5SDimitry Andric       // Size of one action entry (typeid + next action)
1070b57cec5SDimitry Andric       unsigned SizeActionEntry = 0;
1080b57cec5SDimitry Andric       unsigned PrevAction = (unsigned)-1;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric       if (NumShared) {
1110b57cec5SDimitry Andric         unsigned SizePrevIds = PrevLPI->TypeIds.size();
1120b57cec5SDimitry Andric         assert(Actions.size());
1130b57cec5SDimitry Andric         PrevAction = Actions.size() - 1;
1140b57cec5SDimitry Andric         SizeActionEntry = getSLEB128Size(Actions[PrevAction].NextAction) +
1150b57cec5SDimitry Andric                           getSLEB128Size(Actions[PrevAction].ValueForTypeID);
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
1180b57cec5SDimitry Andric           assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
1190b57cec5SDimitry Andric           SizeActionEntry -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
1200b57cec5SDimitry Andric           SizeActionEntry += -Actions[PrevAction].NextAction;
1210b57cec5SDimitry Andric           PrevAction = Actions[PrevAction].Previous;
1220b57cec5SDimitry Andric         }
1230b57cec5SDimitry Andric       }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric       // Compute the actions.
1260b57cec5SDimitry Andric       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
1270b57cec5SDimitry Andric         int TypeID = TypeIds[J];
1280b57cec5SDimitry Andric         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
1290b57cec5SDimitry Andric         int ValueForTypeID =
1300b57cec5SDimitry Andric             isFilterEHSelector(TypeID) ? FilterOffsets[-1 - TypeID] : TypeID;
1310b57cec5SDimitry Andric         unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric         int NextAction = SizeActionEntry ? -(SizeActionEntry + SizeTypeID) : 0;
1340b57cec5SDimitry Andric         SizeActionEntry = SizeTypeID + getSLEB128Size(NextAction);
1350b57cec5SDimitry Andric         SizeSiteActions += SizeActionEntry;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
1380b57cec5SDimitry Andric         Actions.push_back(Action);
1390b57cec5SDimitry Andric         PrevAction = Actions.size() - 1;
1400b57cec5SDimitry Andric       }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric       // Record the first action of the landing pad site.
1430b57cec5SDimitry Andric       FirstAction = SizeActions + SizeSiteActions - SizeActionEntry + 1;
1440b57cec5SDimitry Andric     } // else identical - re-use previous FirstAction
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     // Information used when creating the call-site table. The action record
1470b57cec5SDimitry Andric     // field of the call site record is the offset of the first associated
1480b57cec5SDimitry Andric     // action record, relative to the start of the actions table. This value is
1490b57cec5SDimitry Andric     // biased by 1 (1 indicating the start of the actions table), and 0
1500b57cec5SDimitry Andric     // indicates that there are no actions.
1510b57cec5SDimitry Andric     FirstActions.push_back(FirstAction);
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric     // Compute this sites contribution to size.
1540b57cec5SDimitry Andric     SizeActions += SizeSiteActions;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     PrevLPI = LPI;
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric /// Return `true' if this is a call to a function marked `nounwind'. Return
1610b57cec5SDimitry Andric /// `false' otherwise.
1620b57cec5SDimitry Andric bool EHStreamer::callToNoUnwindFunction(const MachineInstr *MI) {
1630b57cec5SDimitry Andric   assert(MI->isCall() && "This should be a call instruction!");
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   bool MarkedNoUnwind = false;
1660b57cec5SDimitry Andric   bool SawFunc = false;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
1690b57cec5SDimitry Andric     const MachineOperand &MO = MI->getOperand(I);
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric     if (!MO.isGlobal()) continue;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric     const Function *F = dyn_cast<Function>(MO.getGlobal());
1740b57cec5SDimitry Andric     if (!F) continue;
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric     if (SawFunc) {
1770b57cec5SDimitry Andric       // Be conservative. If we have more than one function operand for this
1780b57cec5SDimitry Andric       // call, then we can't make the assumption that it's the callee and
1790b57cec5SDimitry Andric       // not a parameter to the call.
1800b57cec5SDimitry Andric       //
1810b57cec5SDimitry Andric       // FIXME: Determine if there's a way to say that `F' is the callee or
1820b57cec5SDimitry Andric       // parameter.
1830b57cec5SDimitry Andric       MarkedNoUnwind = false;
1840b57cec5SDimitry Andric       break;
1850b57cec5SDimitry Andric     }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric     MarkedNoUnwind = F->doesNotThrow();
1880b57cec5SDimitry Andric     SawFunc = true;
1890b57cec5SDimitry Andric   }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   return MarkedNoUnwind;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric void EHStreamer::computePadMap(
1950b57cec5SDimitry Andric     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
1960b57cec5SDimitry Andric     RangeMapType &PadMap) {
1970b57cec5SDimitry Andric   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
1980b57cec5SDimitry Andric   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
1990b57cec5SDimitry Andric   // try-ranges for them need be deduced so we can put them in the LSDA.
2000b57cec5SDimitry Andric   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2010b57cec5SDimitry Andric     const LandingPadInfo *LandingPad = LandingPads[i];
2020b57cec5SDimitry Andric     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
2030b57cec5SDimitry Andric       MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
2040b57cec5SDimitry Andric       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
2050b57cec5SDimitry Andric       PadRange P = { i, j };
2060b57cec5SDimitry Andric       PadMap[BeginLabel] = P;
2070b57cec5SDimitry Andric     }
2080b57cec5SDimitry Andric   }
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric /// Compute the call-site table.  The entry for an invoke has a try-range
2120b57cec5SDimitry Andric /// containing the call, a non-zero landing pad, and an appropriate action.  The
2130b57cec5SDimitry Andric /// entry for an ordinary call has a try-range containing the call and zero for
2140b57cec5SDimitry Andric /// the landing pad and the action.  Calls marked 'nounwind' have no entry and
2150b57cec5SDimitry Andric /// must not be contained in the try-range of any entry - they form gaps in the
2160b57cec5SDimitry Andric /// table.  Entries must be ordered by try-range address.
217*e8d8bef9SDimitry Andric ///
218*e8d8bef9SDimitry Andric /// Call-sites are split into one or more call-site ranges associated with
219*e8d8bef9SDimitry Andric /// different sections of the function.
220*e8d8bef9SDimitry Andric ///
221*e8d8bef9SDimitry Andric ///   - Without -basic-block-sections, all call-sites are grouped into one
222*e8d8bef9SDimitry Andric ///     call-site-range corresponding to the function section.
223*e8d8bef9SDimitry Andric ///
224*e8d8bef9SDimitry Andric ///   - With -basic-block-sections, one call-site range is created for each
225*e8d8bef9SDimitry Andric ///     section, with its FragmentBeginLabel and FragmentEndLabel respectively
226*e8d8bef9SDimitry Andric //      set to the beginning and ending of the corresponding section and its
227*e8d8bef9SDimitry Andric //      ExceptionLabel set to the exception symbol dedicated for this section.
228*e8d8bef9SDimitry Andric //      Later, one LSDA header will be emitted for each call-site range with its
229*e8d8bef9SDimitry Andric //      call-sites following. The action table and type info table will be
230*e8d8bef9SDimitry Andric //      shared across all ranges.
231*e8d8bef9SDimitry Andric void EHStreamer::computeCallSiteTable(
232*e8d8bef9SDimitry Andric     SmallVectorImpl<CallSiteEntry> &CallSites,
233*e8d8bef9SDimitry Andric     SmallVectorImpl<CallSiteRange> &CallSiteRanges,
2340b57cec5SDimitry Andric     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
2350b57cec5SDimitry Andric     const SmallVectorImpl<unsigned> &FirstActions) {
2360b57cec5SDimitry Andric   RangeMapType PadMap;
2370b57cec5SDimitry Andric   computePadMap(LandingPads, PadMap);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   // The end label of the previous invoke or nounwind try-range.
240*e8d8bef9SDimitry Andric   MCSymbol *LastLabel = Asm->getFunctionBegin();
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   // Whether there is a potentially throwing instruction (currently this means
2430b57cec5SDimitry Andric   // an ordinary call) between the end of the previous try-range and now.
2440b57cec5SDimitry Andric   bool SawPotentiallyThrowing = false;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   // Whether the last CallSite entry was for an invoke.
2470b57cec5SDimitry Andric   bool PreviousIsInvoke = false;
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   // Visit all instructions in order of address.
2520b57cec5SDimitry Andric   for (const auto &MBB : *Asm->MF) {
253*e8d8bef9SDimitry Andric     if (&MBB == &Asm->MF->front() || MBB.isBeginSection()) {
254*e8d8bef9SDimitry Andric       // We start a call-site range upon function entry and at the beginning of
255*e8d8bef9SDimitry Andric       // every basic block section.
256*e8d8bef9SDimitry Andric       CallSiteRanges.push_back(
257*e8d8bef9SDimitry Andric           {Asm->MBBSectionRanges[MBB.getSectionIDNum()].BeginLabel,
258*e8d8bef9SDimitry Andric            Asm->MBBSectionRanges[MBB.getSectionIDNum()].EndLabel,
259*e8d8bef9SDimitry Andric            Asm->getMBBExceptionSym(MBB), CallSites.size()});
260*e8d8bef9SDimitry Andric       PreviousIsInvoke = false;
261*e8d8bef9SDimitry Andric       SawPotentiallyThrowing = false;
262*e8d8bef9SDimitry Andric       LastLabel = nullptr;
263*e8d8bef9SDimitry Andric     }
264*e8d8bef9SDimitry Andric 
265*e8d8bef9SDimitry Andric     if (MBB.isEHPad())
266*e8d8bef9SDimitry Andric       CallSiteRanges.back().IsLPRange = true;
267*e8d8bef9SDimitry Andric 
2680b57cec5SDimitry Andric     for (const auto &MI : MBB) {
2690b57cec5SDimitry Andric       if (!MI.isEHLabel()) {
2700b57cec5SDimitry Andric         if (MI.isCall())
2710b57cec5SDimitry Andric           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
2720b57cec5SDimitry Andric         continue;
2730b57cec5SDimitry Andric       }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric       // End of the previous try-range?
2760b57cec5SDimitry Andric       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
2770b57cec5SDimitry Andric       if (BeginLabel == LastLabel)
2780b57cec5SDimitry Andric         SawPotentiallyThrowing = false;
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric       // Beginning of a new try-range?
2810b57cec5SDimitry Andric       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
2820b57cec5SDimitry Andric       if (L == PadMap.end())
2830b57cec5SDimitry Andric         // Nope, it was just some random label.
2840b57cec5SDimitry Andric         continue;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric       const PadRange &P = L->second;
2870b57cec5SDimitry Andric       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
2880b57cec5SDimitry Andric       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
2890b57cec5SDimitry Andric              "Inconsistent landing pad map!");
2900b57cec5SDimitry Andric 
291*e8d8bef9SDimitry Andric       // For Dwarf and AIX exception handling (SjLj handling doesn't use this).
292*e8d8bef9SDimitry Andric       // If some instruction between the previous try-range and this one may
293*e8d8bef9SDimitry Andric       // throw, create a call-site entry with no landing pad for the region
294*e8d8bef9SDimitry Andric       // between the try-ranges.
295*e8d8bef9SDimitry Andric       if (SawPotentiallyThrowing &&
296*e8d8bef9SDimitry Andric           (Asm->MAI->usesCFIForEH() ||
297*e8d8bef9SDimitry Andric            Asm->MAI->getExceptionHandlingType() == ExceptionHandling::AIX)) {
298*e8d8bef9SDimitry Andric         CallSites.push_back({LastLabel, BeginLabel, nullptr, 0});
2990b57cec5SDimitry Andric         PreviousIsInvoke = false;
3000b57cec5SDimitry Andric       }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric       LastLabel = LandingPad->EndLabels[P.RangeIndex];
3030b57cec5SDimitry Andric       assert(BeginLabel && LastLabel && "Invalid landing pad!");
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric       if (!LandingPad->LandingPadLabel) {
3060b57cec5SDimitry Andric         // Create a gap.
3070b57cec5SDimitry Andric         PreviousIsInvoke = false;
3080b57cec5SDimitry Andric       } else {
3090b57cec5SDimitry Andric         // This try-range is for an invoke.
3100b57cec5SDimitry Andric         CallSiteEntry Site = {
3110b57cec5SDimitry Andric           BeginLabel,
3120b57cec5SDimitry Andric           LastLabel,
3130b57cec5SDimitry Andric           LandingPad,
3140b57cec5SDimitry Andric           FirstActions[P.PadIndex]
3150b57cec5SDimitry Andric         };
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric         // Try to merge with the previous call-site. SJLJ doesn't do this
3180b57cec5SDimitry Andric         if (PreviousIsInvoke && !IsSJLJ) {
3190b57cec5SDimitry Andric           CallSiteEntry &Prev = CallSites.back();
3200b57cec5SDimitry Andric           if (Site.LPad == Prev.LPad && Site.Action == Prev.Action) {
3210b57cec5SDimitry Andric             // Extend the range of the previous entry.
3220b57cec5SDimitry Andric             Prev.EndLabel = Site.EndLabel;
3230b57cec5SDimitry Andric             continue;
3240b57cec5SDimitry Andric           }
3250b57cec5SDimitry Andric         }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric         // Otherwise, create a new call-site.
3280b57cec5SDimitry Andric         if (!IsSJLJ)
3290b57cec5SDimitry Andric           CallSites.push_back(Site);
3300b57cec5SDimitry Andric         else {
3310b57cec5SDimitry Andric           // SjLj EH must maintain the call sites in the order assigned
3320b57cec5SDimitry Andric           // to them by the SjLjPrepare pass.
3330b57cec5SDimitry Andric           unsigned SiteNo = Asm->MF->getCallSiteBeginLabel(BeginLabel);
3340b57cec5SDimitry Andric           if (CallSites.size() < SiteNo)
3350b57cec5SDimitry Andric             CallSites.resize(SiteNo);
3360b57cec5SDimitry Andric           CallSites[SiteNo - 1] = Site;
3370b57cec5SDimitry Andric         }
3380b57cec5SDimitry Andric         PreviousIsInvoke = true;
3390b57cec5SDimitry Andric       }
3400b57cec5SDimitry Andric     }
3410b57cec5SDimitry Andric 
342*e8d8bef9SDimitry Andric     // We end the call-site range upon function exit and at the end of every
343*e8d8bef9SDimitry Andric     // basic block section.
344*e8d8bef9SDimitry Andric     if (&MBB == &Asm->MF->back() || MBB.isEndSection()) {
3450b57cec5SDimitry Andric       // If some instruction between the previous try-range and the end of the
346*e8d8bef9SDimitry Andric       // function may throw, create a call-site entry with no landing pad for
347*e8d8bef9SDimitry Andric       // the region following the try-range.
3480b57cec5SDimitry Andric       if (SawPotentiallyThrowing && !IsSJLJ) {
349*e8d8bef9SDimitry Andric         CallSiteEntry Site = {LastLabel, CallSiteRanges.back().FragmentEndLabel,
350*e8d8bef9SDimitry Andric                               nullptr, 0};
3510b57cec5SDimitry Andric         CallSites.push_back(Site);
352*e8d8bef9SDimitry Andric         SawPotentiallyThrowing = false;
353*e8d8bef9SDimitry Andric       }
354*e8d8bef9SDimitry Andric       CallSiteRanges.back().CallSiteEndIdx = CallSites.size();
355*e8d8bef9SDimitry Andric     }
3560b57cec5SDimitry Andric   }
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric /// Emit landing pads and actions.
3600b57cec5SDimitry Andric ///
3610b57cec5SDimitry Andric /// The general organization of the table is complex, but the basic concepts are
3620b57cec5SDimitry Andric /// easy.  First there is a header which describes the location and organization
3630b57cec5SDimitry Andric /// of the three components that follow.
3640b57cec5SDimitry Andric ///
3650b57cec5SDimitry Andric ///  1. The landing pad site information describes the range of code covered by
3660b57cec5SDimitry Andric ///     the try.  In our case it's an accumulation of the ranges covered by the
3670b57cec5SDimitry Andric ///     invokes in the try.  There is also a reference to the landing pad that
3680b57cec5SDimitry Andric ///     handles the exception once processed.  Finally an index into the actions
3690b57cec5SDimitry Andric ///     table.
3700b57cec5SDimitry Andric ///  2. The action table, in our case, is composed of pairs of type IDs and next
3710b57cec5SDimitry Andric ///     action offset.  Starting with the action index from the landing pad
3720b57cec5SDimitry Andric ///     site, each type ID is checked for a match to the current exception.  If
3730b57cec5SDimitry Andric ///     it matches then the exception and type id are passed on to the landing
3740b57cec5SDimitry Andric ///     pad.  Otherwise the next action is looked up.  This chain is terminated
3750b57cec5SDimitry Andric ///     with a next action of zero.  If no type id is found then the frame is
3760b57cec5SDimitry Andric ///     unwound and handling continues.
3770b57cec5SDimitry Andric ///  3. Type ID table contains references to all the C++ typeinfo for all
3780b57cec5SDimitry Andric ///     catches in the function.  This tables is reverse indexed base 1.
3790b57cec5SDimitry Andric ///
3800b57cec5SDimitry Andric /// Returns the starting symbol of an exception table.
3810b57cec5SDimitry Andric MCSymbol *EHStreamer::emitExceptionTable() {
3820b57cec5SDimitry Andric   const MachineFunction *MF = Asm->MF;
3830b57cec5SDimitry Andric   const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
3840b57cec5SDimitry Andric   const std::vector<unsigned> &FilterIds = MF->getFilterIds();
3850b57cec5SDimitry Andric   const std::vector<LandingPadInfo> &PadInfos = MF->getLandingPads();
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   // Sort the landing pads in order of their type ids.  This is used to fold
3880b57cec5SDimitry Andric   // duplicate actions.
3890b57cec5SDimitry Andric   SmallVector<const LandingPadInfo *, 64> LandingPads;
3900b57cec5SDimitry Andric   LandingPads.reserve(PadInfos.size());
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3930b57cec5SDimitry Andric     LandingPads.push_back(&PadInfos[i]);
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // Order landing pads lexicographically by type id.
3960b57cec5SDimitry Andric   llvm::sort(LandingPads, [](const LandingPadInfo *L, const LandingPadInfo *R) {
3970b57cec5SDimitry Andric     return L->TypeIds < R->TypeIds;
3980b57cec5SDimitry Andric   });
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   // Compute the actions table and gather the first action index for each
4010b57cec5SDimitry Andric   // landing pad site.
4020b57cec5SDimitry Andric   SmallVector<ActionEntry, 32> Actions;
4030b57cec5SDimitry Andric   SmallVector<unsigned, 64> FirstActions;
4040b57cec5SDimitry Andric   computeActionsTable(LandingPads, Actions, FirstActions);
4050b57cec5SDimitry Andric 
406*e8d8bef9SDimitry Andric   // Compute the call-site table and call-site ranges. Normally, there is only
407*e8d8bef9SDimitry Andric   // one call-site-range which covers the whole funciton. With
408*e8d8bef9SDimitry Andric   // -basic-block-sections, there is one call-site-range per basic block
409*e8d8bef9SDimitry Andric   // section.
4100b57cec5SDimitry Andric   SmallVector<CallSiteEntry, 64> CallSites;
411*e8d8bef9SDimitry Andric   SmallVector<CallSiteRange, 4> CallSiteRanges;
412*e8d8bef9SDimitry Andric   computeCallSiteTable(CallSites, CallSiteRanges, LandingPads, FirstActions);
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
4150b57cec5SDimitry Andric   bool IsWasm = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Wasm;
416*e8d8bef9SDimitry Andric   bool HasLEB128Directives = Asm->MAI->hasLEB128Directives();
4170b57cec5SDimitry Andric   unsigned CallSiteEncoding =
4180b57cec5SDimitry Andric       IsSJLJ ? static_cast<unsigned>(dwarf::DW_EH_PE_udata4) :
4190b57cec5SDimitry Andric                Asm->getObjFileLowering().getCallSiteEncoding();
4200b57cec5SDimitry Andric   bool HaveTTData = !TypeInfos.empty() || !FilterIds.empty();
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   // Type infos.
423*e8d8bef9SDimitry Andric   MCSection *LSDASection =
424*e8d8bef9SDimitry Andric       Asm->getObjFileLowering().getSectionForLSDA(MF->getFunction(), Asm->TM);
4250b57cec5SDimitry Andric   unsigned TTypeEncoding;
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   if (!HaveTTData) {
4280b57cec5SDimitry Andric     // If there is no TypeInfo, then we just explicitly say that we're omitting
4290b57cec5SDimitry Andric     // that bit.
4300b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_omit;
4310b57cec5SDimitry Andric   } else {
4320b57cec5SDimitry Andric     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
4330b57cec5SDimitry Andric     // pick a type encoding for them.  We're about to emit a list of pointers to
4340b57cec5SDimitry Andric     // typeinfo objects at the end of the LSDA.  However, unless we're in static
4350b57cec5SDimitry Andric     // mode, this reference will require a relocation by the dynamic linker.
4360b57cec5SDimitry Andric     //
4370b57cec5SDimitry Andric     // Because of this, we have a couple of options:
4380b57cec5SDimitry Andric     //
4390b57cec5SDimitry Andric     //   1) If we are in -static mode, we can always use an absolute reference
4400b57cec5SDimitry Andric     //      from the LSDA, because the static linker will resolve it.
4410b57cec5SDimitry Andric     //
4420b57cec5SDimitry Andric     //   2) Otherwise, if the LSDA section is writable, we can output the direct
4430b57cec5SDimitry Andric     //      reference to the typeinfo and allow the dynamic linker to relocate
4440b57cec5SDimitry Andric     //      it.  Since it is in a writable section, the dynamic linker won't
4450b57cec5SDimitry Andric     //      have a problem.
4460b57cec5SDimitry Andric     //
4470b57cec5SDimitry Andric     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
4480b57cec5SDimitry Andric     //      we need to use some form of indirection.  For example, on Darwin,
4490b57cec5SDimitry Andric     //      we can output a statically-relocatable reference to a dyld stub. The
4500b57cec5SDimitry Andric     //      offset to the stub is constant, but the contents are in a section
4510b57cec5SDimitry Andric     //      that is updated by the dynamic linker.  This is easy enough, but we
4520b57cec5SDimitry Andric     //      need to tell the personality function of the unwinder to indirect
4530b57cec5SDimitry Andric     //      through the dyld stub.
4540b57cec5SDimitry Andric     //
4550b57cec5SDimitry Andric     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
4560b57cec5SDimitry Andric     // somewhere.  This predicate should be moved to a shared location that is
4570b57cec5SDimitry Andric     // in target-independent code.
4580b57cec5SDimitry Andric     //
4590b57cec5SDimitry Andric     TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
4600b57cec5SDimitry Andric   }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   // Begin the exception table.
4630b57cec5SDimitry Andric   // Sometimes we want not to emit the data into separate section (e.g. ARM
4640b57cec5SDimitry Andric   // EHABI). In this case LSDASection will be NULL.
4650b57cec5SDimitry Andric   if (LSDASection)
4660b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(LSDASection);
4675ffd83dbSDimitry Andric   Asm->emitAlignment(Align(4));
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Emit the LSDA.
4700b57cec5SDimitry Andric   MCSymbol *GCCETSym =
4710b57cec5SDimitry Andric     Asm->OutContext.getOrCreateSymbol(Twine("GCC_except_table")+
4720b57cec5SDimitry Andric                                       Twine(Asm->getFunctionNumber()));
4735ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(GCCETSym);
474*e8d8bef9SDimitry Andric   MCSymbol *CstEndLabel = Asm->createTempSymbol(
475*e8d8bef9SDimitry Andric       CallSiteRanges.size() > 1 ? "action_table_base" : "cst_end");
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   MCSymbol *TTBaseLabel = nullptr;
478*e8d8bef9SDimitry Andric   if (HaveTTData)
479*e8d8bef9SDimitry Andric     TTBaseLabel = Asm->createTempSymbol("ttbase");
480*e8d8bef9SDimitry Andric 
481*e8d8bef9SDimitry Andric   const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
482*e8d8bef9SDimitry Andric 
483*e8d8bef9SDimitry Andric   // Helper for emitting references (offsets) for type table and the end of the
484*e8d8bef9SDimitry Andric   // call-site table (which marks the beginning of the action table).
485*e8d8bef9SDimitry Andric   //  * For Itanium, these references will be emitted for every callsite range.
486*e8d8bef9SDimitry Andric   //  * For SJLJ and Wasm, they will be emitted only once in the LSDA header.
487*e8d8bef9SDimitry Andric   auto EmitTypeTableRefAndCallSiteTableEndRef = [&]() {
488*e8d8bef9SDimitry Andric     Asm->emitEncodingByte(TTypeEncoding, "@TType");
4890b57cec5SDimitry Andric     if (HaveTTData) {
4900b57cec5SDimitry Andric       // N.B.: There is a dependency loop between the size of the TTBase uleb128
4910b57cec5SDimitry Andric       // here and the amount of padding before the aligned type table. The
492*e8d8bef9SDimitry Andric       // assembler must sometimes pad this uleb128 or insert extra padding
493*e8d8bef9SDimitry Andric       // before the type table. See PR35809 or GNU as bug 4029.
4940b57cec5SDimitry Andric       MCSymbol *TTBaseRefLabel = Asm->createTempSymbol("ttbaseref");
4955ffd83dbSDimitry Andric       Asm->emitLabelDifferenceAsULEB128(TTBaseLabel, TTBaseRefLabel);
4965ffd83dbSDimitry Andric       Asm->OutStreamer->emitLabel(TTBaseRefLabel);
4970b57cec5SDimitry Andric     }
4980b57cec5SDimitry Andric 
499*e8d8bef9SDimitry Andric     // The Action table follows the call-site table. So we emit the
500*e8d8bef9SDimitry Andric     // label difference from here (start of the call-site table for SJLJ and
501*e8d8bef9SDimitry Andric     // Wasm, and start of a call-site range for Itanium) to the end of the
502*e8d8bef9SDimitry Andric     // whole call-site table (end of the last call-site range for Itanium).
5030b57cec5SDimitry Andric     MCSymbol *CstBeginLabel = Asm->createTempSymbol("cst_begin");
5045ffd83dbSDimitry Andric     Asm->emitEncodingByte(CallSiteEncoding, "Call site");
5055ffd83dbSDimitry Andric     Asm->emitLabelDifferenceAsULEB128(CstEndLabel, CstBeginLabel);
5065ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(CstBeginLabel);
507*e8d8bef9SDimitry Andric   };
508*e8d8bef9SDimitry Andric 
509*e8d8bef9SDimitry Andric   // An alternative path to EmitTypeTableRefAndCallSiteTableEndRef.
510*e8d8bef9SDimitry Andric   // For some platforms, the system assembler does not accept the form of
511*e8d8bef9SDimitry Andric   // `.uleb128 label2 - label1`. In those situations, we would need to calculate
512*e8d8bef9SDimitry Andric   // the size between label1 and label2 manually.
513*e8d8bef9SDimitry Andric   // In this case, we would need to calculate the LSDA size and the call
514*e8d8bef9SDimitry Andric   // site table size.
515*e8d8bef9SDimitry Andric   auto EmitTypeTableOffsetAndCallSiteTableOffset = [&]() {
516*e8d8bef9SDimitry Andric     assert(CallSiteEncoding == dwarf::DW_EH_PE_udata4 && !HasLEB128Directives &&
517*e8d8bef9SDimitry Andric            "Targets supporting .uleb128 do not need to take this path.");
518*e8d8bef9SDimitry Andric     if (CallSiteRanges.size() > 1)
519*e8d8bef9SDimitry Andric       report_fatal_error(
520*e8d8bef9SDimitry Andric           "-fbasic-block-sections is not yet supported on "
521*e8d8bef9SDimitry Andric           "platforms that do not have general LEB128 directive support.");
522*e8d8bef9SDimitry Andric 
523*e8d8bef9SDimitry Andric     uint64_t CallSiteTableSize = 0;
524*e8d8bef9SDimitry Andric     const CallSiteRange &CSRange = CallSiteRanges.back();
525*e8d8bef9SDimitry Andric     for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
526*e8d8bef9SDimitry Andric          CallSiteIdx < CSRange.CallSiteEndIdx; ++CallSiteIdx) {
527*e8d8bef9SDimitry Andric       const CallSiteEntry &S = CallSites[CallSiteIdx];
528*e8d8bef9SDimitry Andric       // Each call site entry consists of 3 udata4 fields (12 bytes) and
529*e8d8bef9SDimitry Andric       // 1 ULEB128 field.
530*e8d8bef9SDimitry Andric       CallSiteTableSize += 12 + getULEB128Size(S.Action);
531*e8d8bef9SDimitry Andric       assert(isUInt<32>(CallSiteTableSize) && "CallSiteTableSize overflows.");
532*e8d8bef9SDimitry Andric     }
533*e8d8bef9SDimitry Andric 
534*e8d8bef9SDimitry Andric     Asm->emitEncodingByte(TTypeEncoding, "@TType");
535*e8d8bef9SDimitry Andric     if (HaveTTData) {
536*e8d8bef9SDimitry Andric       const unsigned ByteSizeOfCallSiteOffset =
537*e8d8bef9SDimitry Andric           getULEB128Size(CallSiteTableSize);
538*e8d8bef9SDimitry Andric       uint64_t ActionTableSize = 0;
539*e8d8bef9SDimitry Andric       for (const ActionEntry &Action : Actions) {
540*e8d8bef9SDimitry Andric         // Each action entry consists of two SLEB128 fields.
541*e8d8bef9SDimitry Andric         ActionTableSize += getSLEB128Size(Action.ValueForTypeID) +
542*e8d8bef9SDimitry Andric                            getSLEB128Size(Action.NextAction);
543*e8d8bef9SDimitry Andric         assert(isUInt<32>(ActionTableSize) && "ActionTableSize overflows.");
544*e8d8bef9SDimitry Andric       }
545*e8d8bef9SDimitry Andric 
546*e8d8bef9SDimitry Andric       const unsigned TypeInfoSize =
547*e8d8bef9SDimitry Andric           Asm->GetSizeOfEncodedValue(TTypeEncoding) * MF->getTypeInfos().size();
548*e8d8bef9SDimitry Andric 
549*e8d8bef9SDimitry Andric       const uint64_t LSDASizeBeforeAlign =
550*e8d8bef9SDimitry Andric           1                          // Call site encoding byte.
551*e8d8bef9SDimitry Andric           + ByteSizeOfCallSiteOffset // ULEB128 encoding of CallSiteTableSize.
552*e8d8bef9SDimitry Andric           + CallSiteTableSize        // Call site table content.
553*e8d8bef9SDimitry Andric           + ActionTableSize;         // Action table content.
554*e8d8bef9SDimitry Andric 
555*e8d8bef9SDimitry Andric       const uint64_t LSDASizeWithoutAlign = LSDASizeBeforeAlign + TypeInfoSize;
556*e8d8bef9SDimitry Andric       const unsigned ByteSizeOfLSDAWithoutAlign =
557*e8d8bef9SDimitry Andric           getULEB128Size(LSDASizeWithoutAlign);
558*e8d8bef9SDimitry Andric       const uint64_t DisplacementBeforeAlign =
559*e8d8bef9SDimitry Andric           2 // LPStartEncoding and TypeTableEncoding.
560*e8d8bef9SDimitry Andric           + ByteSizeOfLSDAWithoutAlign + LSDASizeBeforeAlign;
561*e8d8bef9SDimitry Andric 
562*e8d8bef9SDimitry Andric       // The type info area starts with 4 byte alignment.
563*e8d8bef9SDimitry Andric       const unsigned NeedAlignVal = (4 - DisplacementBeforeAlign % 4) % 4;
564*e8d8bef9SDimitry Andric       uint64_t LSDASizeWithAlign = LSDASizeWithoutAlign + NeedAlignVal;
565*e8d8bef9SDimitry Andric       const unsigned ByteSizeOfLSDAWithAlign =
566*e8d8bef9SDimitry Andric           getULEB128Size(LSDASizeWithAlign);
567*e8d8bef9SDimitry Andric 
568*e8d8bef9SDimitry Andric       // The LSDASizeWithAlign could use 1 byte less padding for alignment
569*e8d8bef9SDimitry Andric       // when the data we use to represent the LSDA Size "needs" to be 1 byte
570*e8d8bef9SDimitry Andric       // larger than the one previously calculated without alignment.
571*e8d8bef9SDimitry Andric       if (ByteSizeOfLSDAWithAlign > ByteSizeOfLSDAWithoutAlign)
572*e8d8bef9SDimitry Andric         LSDASizeWithAlign -= 1;
573*e8d8bef9SDimitry Andric 
574*e8d8bef9SDimitry Andric       Asm->OutStreamer->emitULEB128IntValue(LSDASizeWithAlign,
575*e8d8bef9SDimitry Andric                                             ByteSizeOfLSDAWithAlign);
576*e8d8bef9SDimitry Andric     }
577*e8d8bef9SDimitry Andric 
578*e8d8bef9SDimitry Andric     Asm->emitEncodingByte(CallSiteEncoding, "Call site");
579*e8d8bef9SDimitry Andric     Asm->OutStreamer->emitULEB128IntValue(CallSiteTableSize);
580*e8d8bef9SDimitry Andric   };
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   // SjLj / Wasm Exception handling
5830b57cec5SDimitry Andric   if (IsSJLJ || IsWasm) {
584*e8d8bef9SDimitry Andric     Asm->OutStreamer->emitLabel(Asm->getMBBExceptionSym(Asm->MF->front()));
585*e8d8bef9SDimitry Andric 
586*e8d8bef9SDimitry Andric     // emit the LSDA header.
587*e8d8bef9SDimitry Andric     Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
588*e8d8bef9SDimitry Andric     EmitTypeTableRefAndCallSiteTableEndRef();
589*e8d8bef9SDimitry Andric 
5900b57cec5SDimitry Andric     unsigned idx = 0;
5910b57cec5SDimitry Andric     for (SmallVectorImpl<CallSiteEntry>::const_iterator
5920b57cec5SDimitry Andric          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
5930b57cec5SDimitry Andric       const CallSiteEntry &S = *I;
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric       // Index of the call site entry.
5960b57cec5SDimitry Andric       if (VerboseAsm) {
5970b57cec5SDimitry Andric         Asm->OutStreamer->AddComment(">> Call Site " + Twine(idx) + " <<");
5980b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("  On exception at call site "+Twine(idx));
5990b57cec5SDimitry Andric       }
6005ffd83dbSDimitry Andric       Asm->emitULEB128(idx);
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric       // Offset of the first associated action record, relative to the start of
6030b57cec5SDimitry Andric       // the action table. This value is biased by 1 (1 indicates the start of
6040b57cec5SDimitry Andric       // the action table), and 0 indicates that there are no actions.
6050b57cec5SDimitry Andric       if (VerboseAsm) {
6060b57cec5SDimitry Andric         if (S.Action == 0)
6070b57cec5SDimitry Andric           Asm->OutStreamer->AddComment("  Action: cleanup");
6080b57cec5SDimitry Andric         else
6090b57cec5SDimitry Andric           Asm->OutStreamer->AddComment("  Action: " +
6100b57cec5SDimitry Andric                                        Twine((S.Action - 1) / 2 + 1));
6110b57cec5SDimitry Andric       }
6125ffd83dbSDimitry Andric       Asm->emitULEB128(S.Action);
6130b57cec5SDimitry Andric     }
614*e8d8bef9SDimitry Andric     Asm->OutStreamer->emitLabel(CstEndLabel);
6150b57cec5SDimitry Andric   } else {
6160b57cec5SDimitry Andric     // Itanium LSDA exception handling
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric     // The call-site table is a list of all call sites that may throw an
6190b57cec5SDimitry Andric     // exception (including C++ 'throw' statements) in the procedure
6200b57cec5SDimitry Andric     // fragment. It immediately follows the LSDA header. Each entry indicates,
6210b57cec5SDimitry Andric     // for a given call, the first corresponding action record and corresponding
6220b57cec5SDimitry Andric     // landing pad.
6230b57cec5SDimitry Andric     //
6240b57cec5SDimitry Andric     // The table begins with the number of bytes, stored as an LEB128
6250b57cec5SDimitry Andric     // compressed, unsigned integer. The records immediately follow the record
6260b57cec5SDimitry Andric     // count. They are sorted in increasing call-site address. Each record
6270b57cec5SDimitry Andric     // indicates:
6280b57cec5SDimitry Andric     //
6290b57cec5SDimitry Andric     //   * The position of the call-site.
6300b57cec5SDimitry Andric     //   * The position of the landing pad.
6310b57cec5SDimitry Andric     //   * The first action record for that call site.
6320b57cec5SDimitry Andric     //
6330b57cec5SDimitry Andric     // A missing entry in the call-site table indicates that a call is not
6340b57cec5SDimitry Andric     // supposed to throw.
6350b57cec5SDimitry Andric 
636*e8d8bef9SDimitry Andric     assert(CallSiteRanges.size() != 0 && "No call-site ranges!");
6370b57cec5SDimitry Andric 
638*e8d8bef9SDimitry Andric     // There should be only one call-site range which includes all the landing
639*e8d8bef9SDimitry Andric     // pads. Find that call-site range here.
640*e8d8bef9SDimitry Andric     const CallSiteRange *LandingPadRange = nullptr;
641*e8d8bef9SDimitry Andric     for (const CallSiteRange &CSRange : CallSiteRanges) {
642*e8d8bef9SDimitry Andric       if (CSRange.IsLPRange) {
643*e8d8bef9SDimitry Andric         assert(LandingPadRange == nullptr &&
644*e8d8bef9SDimitry Andric                "All landing pads must be in a single callsite range.");
645*e8d8bef9SDimitry Andric         LandingPadRange = &CSRange;
646*e8d8bef9SDimitry Andric       }
647*e8d8bef9SDimitry Andric     }
648*e8d8bef9SDimitry Andric 
649*e8d8bef9SDimitry Andric     // The call-site table is split into its call-site ranges, each being
650*e8d8bef9SDimitry Andric     // emitted as:
651*e8d8bef9SDimitry Andric     //              [ LPStartEncoding | LPStart ]
652*e8d8bef9SDimitry Andric     //              [ TypeTableEncoding | TypeTableOffset ]
653*e8d8bef9SDimitry Andric     //              [ CallSiteEncoding | CallSiteTableEndOffset ]
654*e8d8bef9SDimitry Andric     // cst_begin -> { call-site entries contained in this range }
655*e8d8bef9SDimitry Andric     //
656*e8d8bef9SDimitry Andric     // and is followed by the next call-site range.
657*e8d8bef9SDimitry Andric     //
658*e8d8bef9SDimitry Andric     // For each call-site range, CallSiteTableEndOffset is computed as the
659*e8d8bef9SDimitry Andric     // difference between cst_begin of that range and the last call-site-table's
660*e8d8bef9SDimitry Andric     // end label. This offset is used to find the action table.
661*e8d8bef9SDimitry Andric 
662*e8d8bef9SDimitry Andric     unsigned Entry = 0;
663*e8d8bef9SDimitry Andric     for (const CallSiteRange &CSRange : CallSiteRanges) {
664*e8d8bef9SDimitry Andric       if (CSRange.CallSiteBeginIdx != 0) {
665*e8d8bef9SDimitry Andric         // Align the call-site range for all ranges except the first. The
666*e8d8bef9SDimitry Andric         // first range is already aligned due to the exception table alignment.
667*e8d8bef9SDimitry Andric         Asm->emitAlignment(Align(4));
668*e8d8bef9SDimitry Andric       }
669*e8d8bef9SDimitry Andric       Asm->OutStreamer->emitLabel(CSRange.ExceptionLabel);
670*e8d8bef9SDimitry Andric 
671*e8d8bef9SDimitry Andric       // Emit the LSDA header.
672*e8d8bef9SDimitry Andric       // If only one call-site range exists, LPStart is omitted as it is the
673*e8d8bef9SDimitry Andric       // same as the function entry.
674*e8d8bef9SDimitry Andric       if (CallSiteRanges.size() == 1) {
675*e8d8bef9SDimitry Andric         Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
676*e8d8bef9SDimitry Andric       } else if (!Asm->isPositionIndependent()) {
677*e8d8bef9SDimitry Andric         // For more than one call-site ranges, LPStart must be explicitly
678*e8d8bef9SDimitry Andric         // specified.
679*e8d8bef9SDimitry Andric         // For non-PIC we can simply use the absolute value.
680*e8d8bef9SDimitry Andric         Asm->emitEncodingByte(dwarf::DW_EH_PE_absptr, "@LPStart");
681*e8d8bef9SDimitry Andric         Asm->OutStreamer->emitSymbolValue(LandingPadRange->FragmentBeginLabel,
682*e8d8bef9SDimitry Andric                                           Asm->MAI->getCodePointerSize());
683*e8d8bef9SDimitry Andric       } else {
684*e8d8bef9SDimitry Andric         // For PIC mode, we Emit a PC-relative address for LPStart.
685*e8d8bef9SDimitry Andric         Asm->emitEncodingByte(dwarf::DW_EH_PE_pcrel, "@LPStart");
686*e8d8bef9SDimitry Andric         MCContext &Context = Asm->OutStreamer->getContext();
687*e8d8bef9SDimitry Andric         MCSymbol *Dot = Context.createTempSymbol();
688*e8d8bef9SDimitry Andric         Asm->OutStreamer->emitLabel(Dot);
689*e8d8bef9SDimitry Andric         Asm->OutStreamer->emitValue(
690*e8d8bef9SDimitry Andric             MCBinaryExpr::createSub(
691*e8d8bef9SDimitry Andric                 MCSymbolRefExpr::create(LandingPadRange->FragmentBeginLabel,
692*e8d8bef9SDimitry Andric                                         Context),
693*e8d8bef9SDimitry Andric                 MCSymbolRefExpr::create(Dot, Context), Context),
694*e8d8bef9SDimitry Andric             Asm->MAI->getCodePointerSize());
695*e8d8bef9SDimitry Andric       }
696*e8d8bef9SDimitry Andric 
697*e8d8bef9SDimitry Andric       if (HasLEB128Directives)
698*e8d8bef9SDimitry Andric         EmitTypeTableRefAndCallSiteTableEndRef();
699*e8d8bef9SDimitry Andric       else
700*e8d8bef9SDimitry Andric         EmitTypeTableOffsetAndCallSiteTableOffset();
701*e8d8bef9SDimitry Andric 
702*e8d8bef9SDimitry Andric       for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
703*e8d8bef9SDimitry Andric            CallSiteIdx != CSRange.CallSiteEndIdx; ++CallSiteIdx) {
704*e8d8bef9SDimitry Andric         const CallSiteEntry &S = CallSites[CallSiteIdx];
705*e8d8bef9SDimitry Andric 
706*e8d8bef9SDimitry Andric         MCSymbol *EHFuncBeginSym = CSRange.FragmentBeginLabel;
707*e8d8bef9SDimitry Andric         MCSymbol *EHFuncEndSym = CSRange.FragmentEndLabel;
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric         MCSymbol *BeginLabel = S.BeginLabel;
7100b57cec5SDimitry Andric         if (!BeginLabel)
7110b57cec5SDimitry Andric           BeginLabel = EHFuncBeginSym;
7120b57cec5SDimitry Andric         MCSymbol *EndLabel = S.EndLabel;
7130b57cec5SDimitry Andric         if (!EndLabel)
714*e8d8bef9SDimitry Andric           EndLabel = EHFuncEndSym;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric         // Offset of the call site relative to the start of the procedure.
7170b57cec5SDimitry Andric         if (VerboseAsm)
718*e8d8bef9SDimitry Andric           Asm->OutStreamer->AddComment(">> Call Site " + Twine(++Entry) +
719*e8d8bef9SDimitry Andric                                        " <<");
7205ffd83dbSDimitry Andric         Asm->emitCallSiteOffset(BeginLabel, EHFuncBeginSym, CallSiteEncoding);
7210b57cec5SDimitry Andric         if (VerboseAsm)
7220b57cec5SDimitry Andric           Asm->OutStreamer->AddComment(Twine("  Call between ") +
7230b57cec5SDimitry Andric                                        BeginLabel->getName() + " and " +
7240b57cec5SDimitry Andric                                        EndLabel->getName());
7255ffd83dbSDimitry Andric         Asm->emitCallSiteOffset(EndLabel, BeginLabel, CallSiteEncoding);
7260b57cec5SDimitry Andric 
727*e8d8bef9SDimitry Andric         // Offset of the landing pad relative to the start of the landing pad
728*e8d8bef9SDimitry Andric         // fragment.
7290b57cec5SDimitry Andric         if (!S.LPad) {
7300b57cec5SDimitry Andric           if (VerboseAsm)
7310b57cec5SDimitry Andric             Asm->OutStreamer->AddComment("    has no landing pad");
7325ffd83dbSDimitry Andric           Asm->emitCallSiteValue(0, CallSiteEncoding);
7330b57cec5SDimitry Andric         } else {
7340b57cec5SDimitry Andric           if (VerboseAsm)
7350b57cec5SDimitry Andric             Asm->OutStreamer->AddComment(Twine("    jumps to ") +
7360b57cec5SDimitry Andric                                          S.LPad->LandingPadLabel->getName());
737*e8d8bef9SDimitry Andric           Asm->emitCallSiteOffset(S.LPad->LandingPadLabel,
738*e8d8bef9SDimitry Andric                                   LandingPadRange->FragmentBeginLabel,
7390b57cec5SDimitry Andric                                   CallSiteEncoding);
7400b57cec5SDimitry Andric         }
7410b57cec5SDimitry Andric 
742*e8d8bef9SDimitry Andric         // Offset of the first associated action record, relative to the start
743*e8d8bef9SDimitry Andric         // of the action table. This value is biased by 1 (1 indicates the start
744*e8d8bef9SDimitry Andric         // of the action table), and 0 indicates that there are no actions.
7450b57cec5SDimitry Andric         if (VerboseAsm) {
7460b57cec5SDimitry Andric           if (S.Action == 0)
7470b57cec5SDimitry Andric             Asm->OutStreamer->AddComment("  On action: cleanup");
7480b57cec5SDimitry Andric           else
7490b57cec5SDimitry Andric             Asm->OutStreamer->AddComment("  On action: " +
7500b57cec5SDimitry Andric                                          Twine((S.Action - 1) / 2 + 1));
7510b57cec5SDimitry Andric         }
7525ffd83dbSDimitry Andric         Asm->emitULEB128(S.Action);
7530b57cec5SDimitry Andric       }
7540b57cec5SDimitry Andric     }
7555ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(CstEndLabel);
756*e8d8bef9SDimitry Andric   }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   // Emit the Action Table.
7590b57cec5SDimitry Andric   int Entry = 0;
7600b57cec5SDimitry Andric   for (SmallVectorImpl<ActionEntry>::const_iterator
7610b57cec5SDimitry Andric          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
7620b57cec5SDimitry Andric     const ActionEntry &Action = *I;
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric     if (VerboseAsm) {
7650b57cec5SDimitry Andric       // Emit comments that decode the action table.
7660b57cec5SDimitry Andric       Asm->OutStreamer->AddComment(">> Action Record " + Twine(++Entry) + " <<");
7670b57cec5SDimitry Andric     }
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric     // Type Filter
7700b57cec5SDimitry Andric     //
7710b57cec5SDimitry Andric     //   Used by the runtime to match the type of the thrown exception to the
7720b57cec5SDimitry Andric     //   type of the catch clauses or the types in the exception specification.
7730b57cec5SDimitry Andric     if (VerboseAsm) {
7740b57cec5SDimitry Andric       if (Action.ValueForTypeID > 0)
7750b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("  Catch TypeInfo " +
7760b57cec5SDimitry Andric                                      Twine(Action.ValueForTypeID));
7770b57cec5SDimitry Andric       else if (Action.ValueForTypeID < 0)
7780b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("  Filter TypeInfo " +
7790b57cec5SDimitry Andric                                      Twine(Action.ValueForTypeID));
7800b57cec5SDimitry Andric       else
7810b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("  Cleanup");
7820b57cec5SDimitry Andric     }
7835ffd83dbSDimitry Andric     Asm->emitSLEB128(Action.ValueForTypeID);
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric     // Action Record
7860b57cec5SDimitry Andric     if (VerboseAsm) {
787*e8d8bef9SDimitry Andric       if (Action.Previous == unsigned(-1)) {
7880b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("  No further actions");
7890b57cec5SDimitry Andric       } else {
790*e8d8bef9SDimitry Andric         Asm->OutStreamer->AddComment("  Continue to action " +
791*e8d8bef9SDimitry Andric                                      Twine(Action.Previous + 1));
7920b57cec5SDimitry Andric       }
7930b57cec5SDimitry Andric     }
7945ffd83dbSDimitry Andric     Asm->emitSLEB128(Action.NextAction);
7950b57cec5SDimitry Andric   }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   if (HaveTTData) {
7985ffd83dbSDimitry Andric     Asm->emitAlignment(Align(4));
7990b57cec5SDimitry Andric     emitTypeInfos(TTypeEncoding, TTBaseLabel);
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric 
8025ffd83dbSDimitry Andric   Asm->emitAlignment(Align(4));
8030b57cec5SDimitry Andric   return GCCETSym;
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric void EHStreamer::emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel) {
8070b57cec5SDimitry Andric   const MachineFunction *MF = Asm->MF;
8080b57cec5SDimitry Andric   const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
8090b57cec5SDimitry Andric   const std::vector<unsigned> &FilterIds = MF->getFilterIds();
8100b57cec5SDimitry Andric 
811*e8d8bef9SDimitry Andric   const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   int Entry = 0;
8140b57cec5SDimitry Andric   // Emit the Catch TypeInfos.
8150b57cec5SDimitry Andric   if (VerboseAsm && !TypeInfos.empty()) {
8160b57cec5SDimitry Andric     Asm->OutStreamer->AddComment(">> Catch TypeInfos <<");
8170b57cec5SDimitry Andric     Asm->OutStreamer->AddBlankLine();
8180b57cec5SDimitry Andric     Entry = TypeInfos.size();
8190b57cec5SDimitry Andric   }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   for (const GlobalValue *GV : make_range(TypeInfos.rbegin(),
8220b57cec5SDimitry Andric                                           TypeInfos.rend())) {
8230b57cec5SDimitry Andric     if (VerboseAsm)
8240b57cec5SDimitry Andric       Asm->OutStreamer->AddComment("TypeInfo " + Twine(Entry--));
8255ffd83dbSDimitry Andric     Asm->emitTTypeReference(GV, TTypeEncoding);
8260b57cec5SDimitry Andric   }
8270b57cec5SDimitry Andric 
8285ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(TTBaseLabel);
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   // Emit the Exception Specifications.
8310b57cec5SDimitry Andric   if (VerboseAsm && !FilterIds.empty()) {
8320b57cec5SDimitry Andric     Asm->OutStreamer->AddComment(">> Filter TypeInfos <<");
8330b57cec5SDimitry Andric     Asm->OutStreamer->AddBlankLine();
8340b57cec5SDimitry Andric     Entry = 0;
8350b57cec5SDimitry Andric   }
8360b57cec5SDimitry Andric   for (std::vector<unsigned>::const_iterator
8370b57cec5SDimitry Andric          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
8380b57cec5SDimitry Andric     unsigned TypeID = *I;
8390b57cec5SDimitry Andric     if (VerboseAsm) {
8400b57cec5SDimitry Andric       --Entry;
8410b57cec5SDimitry Andric       if (isFilterEHSelector(TypeID))
8420b57cec5SDimitry Andric         Asm->OutStreamer->AddComment("FilterInfo " + Twine(Entry));
8430b57cec5SDimitry Andric     }
8440b57cec5SDimitry Andric 
8455ffd83dbSDimitry Andric     Asm->emitULEB128(TypeID);
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric }
848