LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - WinException.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 552 558 98.9 %
Date: 2017-09-14 15:23:50 Functions: 24 25 96.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains support for writing Win64 exception info into asm files.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "WinException.h"
      15             : #include "llvm/ADT/StringExtras.h"
      16             : #include "llvm/ADT/Twine.h"
      17             : #include "llvm/BinaryFormat/COFF.h"
      18             : #include "llvm/BinaryFormat/Dwarf.h"
      19             : #include "llvm/CodeGen/AsmPrinter.h"
      20             : #include "llvm/CodeGen/MachineFrameInfo.h"
      21             : #include "llvm/CodeGen/MachineFunction.h"
      22             : #include "llvm/CodeGen/MachineModuleInfo.h"
      23             : #include "llvm/CodeGen/WinEHFuncInfo.h"
      24             : #include "llvm/IR/DataLayout.h"
      25             : #include "llvm/IR/Mangler.h"
      26             : #include "llvm/IR/Module.h"
      27             : #include "llvm/MC/MCAsmInfo.h"
      28             : #include "llvm/MC/MCContext.h"
      29             : #include "llvm/MC/MCExpr.h"
      30             : #include "llvm/MC/MCSection.h"
      31             : #include "llvm/MC/MCStreamer.h"
      32             : #include "llvm/MC/MCSymbol.h"
      33             : #include "llvm/MC/MCWin64EH.h"
      34             : #include "llvm/Support/ErrorHandling.h"
      35             : #include "llvm/Support/FormattedStream.h"
      36             : #include "llvm/Target/TargetFrameLowering.h"
      37             : #include "llvm/Target/TargetLowering.h"
      38             : #include "llvm/Target/TargetLoweringObjectFile.h"
      39             : #include "llvm/Target/TargetOptions.h"
      40             : #include "llvm/Target/TargetRegisterInfo.h"
      41             : #include "llvm/Target/TargetSubtargetInfo.h"
      42             : using namespace llvm;
      43             : 
      44         472 : WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
      45             :   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
      46             :   // platforms use an imagerel32 relocation to refer to symbols.
      47         944 :   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
      48         472 : }
      49             : 
      50         469 : WinException::~WinException() {}
      51             : 
      52             : /// endModule - Emit all exception information that should come after the
      53             : /// content.
      54         469 : void WinException::endModule() {
      55         938 :   auto &OS = *Asm->OutStreamer;
      56         469 :   const Module *M = MMI->getModule();
      57        4595 :   for (const Function &F : *M)
      58        6376 :     if (F.hasFnAttribute("safeseh"))
      59          27 :       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
      60         469 : }
      61             : 
      62        1809 : void WinException::beginFunction(const MachineFunction *MF) {
      63        1809 :   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
      64             : 
      65             :   // If any landing pads survive, we need an EH table.
      66        3618 :   bool hasLandingPads = !MF->getLandingPads().empty();
      67        1809 :   bool hasEHFunclets = MF->hasEHFunclets();
      68             : 
      69        1809 :   const Function *F = MF->getFunction();
      70             : 
      71        2300 :   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
      72             : 
      73        1809 :   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
      74        1809 :   unsigned PerEncoding = TLOF.getPersonalityEncoding();
      75             : 
      76        1809 :   EHPersonality Per = EHPersonality::Unknown;
      77        1809 :   const Function *PerFn = nullptr;
      78        1809 :   if (F->hasPersonalityFn()) {
      79         330 :     PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
      80         110 :     Per = classifyEHPersonality(PerFn);
      81             :   }
      82             : 
      83        1809 :   bool forceEmitPersonality = F->hasPersonalityFn() &&
      84        1825 :                               !isNoOpWithoutInvoke(Per) &&
      85        1809 :                               F->needsUnwindTableEntry();
      86             : 
      87        1809 :   shouldEmitPersonality =
      88        1801 :       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
      89          97 :                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
      90             : 
      91        1809 :   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
      92        1809 :   shouldEmitLSDA = shouldEmitPersonality &&
      93             :     LSDAEncoding != dwarf::DW_EH_PE_omit;
      94             : 
      95             :   // If we're not using CFI, we don't want the CFI or the personality, but we
      96             :   // might want EH tables if we had EH pads.
      97        1809 :   if (!Asm->MAI->usesWindowsCFI()) {
      98         706 :     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
      99             :       // If this is 32-bit SEH and we don't have any funclets (really invokes),
     100             :       // make sure we emit the parent offset label. Some unreferenced filter
     101             :       // functions may still refer to it.
     102           1 :       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
     103             :       StringRef FLinkageName =
     104           1 :           GlobalValue::dropLLVMManglingEscape(MF->getFunction()->getName());
     105           1 :       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
     106             :     }
     107         706 :     shouldEmitLSDA = hasEHFunclets;
     108         706 :     shouldEmitPersonality = false;
     109         706 :     return;
     110             :   }
     111             : 
     112        2206 :   beginFunclet(MF->front(), Asm->CurrentFnSym);
     113             : }
     114             : 
     115             : /// endFunction - Gather and emit post-function exception information.
     116             : ///
     117        1809 : void WinException::endFunction(const MachineFunction *MF) {
     118        1809 :   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
     119             :     return;
     120             : 
     121         323 :   const Function *F = MF->getFunction();
     122         323 :   EHPersonality Per = EHPersonality::Unknown;
     123         323 :   if (F->hasPersonalityFn())
     124         194 :     Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
     125             : 
     126             :   // Get rid of any dead landing pads if we're not using funclets. In funclet
     127             :   // schemes, the landing pad is not actually reachable. It only exists so
     128             :   // that we can emit the right table data.
     129         239 :   if (!isFuncletEHPersonality(Per)) {
     130         239 :     MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
     131         239 :     NonConstMF->tidyLandingPads();
     132             :   }
     133             : 
     134         323 :   endFunclet();
     135             : 
     136             :   // endFunclet will emit the necessary .xdata tables for x64 SEH.
     137         323 :   if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
     138             :     return;
     139             : 
     140         312 :   if (shouldEmitPersonality || shouldEmitLSDA) {
     141         166 :     Asm->OutStreamer->PushSection();
     142             : 
     143             :     // Just switch sections to the right xdata section.
     144         166 :     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
     145         249 :         Asm->OutStreamer->getCurrentSectionOnly());
     146         166 :     Asm->OutStreamer->SwitchSection(XData);
     147             : 
     148             :     // Emit the tables appropriate to the personality function in use. If we
     149             :     // don't recognize the personality, assume it uses an Itanium-style LSDA.
     150          83 :     if (Per == EHPersonality::MSVC_Win64SEH)
     151           0 :       emitCSpecificHandlerTable(MF);
     152          83 :     else if (Per == EHPersonality::MSVC_X86SEH)
     153          12 :       emitExceptHandlerTable(MF);
     154          71 :     else if (Per == EHPersonality::MSVC_CXX)
     155          53 :       emitCXXFrameHandler3Table(MF);
     156          18 :     else if (Per == EHPersonality::CoreCLR)
     157           7 :       emitCLRExceptionTable(MF);
     158             :     else
     159          11 :       emitExceptionTable();
     160             : 
     161         166 :     Asm->OutStreamer->PopSection();
     162             :   }
     163             : }
     164             : 
     165             : /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
     166         416 : static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
     167             :                                    const MachineBasicBlock *MBB) {
     168         416 :   if (!MBB)
     169             :     return nullptr;
     170             : 
     171             :   assert(MBB->isEHFuncletEntry());
     172             : 
     173             :   // Give catches and cleanups a name based off of their parent function and
     174             :   // their funclet entry block's number.
     175         300 :   const MachineFunction *MF = MBB->getParent();
     176         300 :   const Function *F = MF->getFunction();
     177         300 :   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName());
     178         300 :   MCContext &Ctx = MF->getContext();
     179         600 :   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
     180        1500 :   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
     181        1800 :                                Twine(MBB->getNumber()) + "@?0?" +
     182        1200 :                                FuncLinkageName + "@4HA");
     183             : }
     184             : 
     185        1217 : void WinException::beginFunclet(const MachineBasicBlock &MBB,
     186             :                                 MCSymbol *Sym) {
     187        1217 :   CurrentFuncletEntry = &MBB;
     188             : 
     189        1217 :   const Function *F = Asm->MF->getFunction();
     190             :   // If a symbol was not provided for the funclet, invent one.
     191        1217 :   if (!Sym) {
     192         114 :     Sym = getMCSymbolForMBB(Asm, &MBB);
     193             : 
     194             :     // Describe our funclet symbol as a function with internal linkage.
     195         228 :     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
     196         228 :     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
     197         342 :     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
     198         114 :                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
     199         228 :     Asm->OutStreamer->EndCOFFSymbolDef();
     200             : 
     201             :     // We want our funclet's entry point to be aligned such that no nops will be
     202             :     // present after the label.
     203         228 :     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
     204             :                        F);
     205             : 
     206             :     // Now that we've emitted the alignment directive, point at our funclet.
     207         228 :     Asm->OutStreamer->EmitLabel(Sym);
     208             :   }
     209             : 
     210             :   // Mark 'Sym' as starting our funclet.
     211        1217 :   if (shouldEmitMoves || shouldEmitPersonality) {
     212        1134 :     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
     213         756 :     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
     214             :   }
     215             : 
     216        1217 :   if (shouldEmitPersonality) {
     217         149 :     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
     218         149 :     const Function *PerFn = nullptr;
     219             : 
     220             :     // Determine which personality routine we are using for this funclet.
     221         149 :     if (F->hasPersonalityFn())
     222         298 :       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
     223             :     const MCSymbol *PersHandlerSym =
     224         149 :         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
     225             : 
     226             :     // Do not emit a .seh_handler directives for cleanup funclets.
     227             :     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
     228             :     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
     229             :     // inliner doesn't allow inlining them, this isn't a major problem in
     230             :     // practice.
     231         149 :     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
     232         242 :       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
     233             :   }
     234        1217 : }
     235             : 
     236         437 : void WinException::endFunclet() {
     237             :   // No funclet to process?  Great, we have nothing to do.
     238         437 :   if (!CurrentFuncletEntry)
     239             :     return;
     240             : 
     241         407 :   const MachineFunction *MF = Asm->MF;
     242         407 :   if (shouldEmitMoves || shouldEmitPersonality) {
     243         378 :     const Function *F = MF->getFunction();
     244         378 :     EHPersonality Per = EHPersonality::Unknown;
     245         378 :     if (F->hasPersonalityFn())
     246         304 :       Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
     247             : 
     248             :     // Emit an UNWIND_INFO struct describing the prologue.
     249         756 :     Asm->OutStreamer->EmitWinEHHandlerData();
     250             : 
     251         474 :     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
     252          96 :         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
     253             :       // If this is a C++ catch funclet (or the parent function),
     254             :       // emit a reference to the LSDA for the parent function.
     255          81 :       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName());
     256          81 :       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
     257          81 :           Twine("$cppxdata$", FuncLinkageName));
     258         162 :       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
     259         313 :     } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
     260          16 :                !CurrentFuncletEntry->isEHFuncletEntry()) {
     261             :       // If this is the parent function in Win64 SEH, emit the LSDA immediately
     262             :       // following .seh_handlerdata.
     263          11 :       emitCSpecificHandlerTable(MF);
     264             :     }
     265             : 
     266             :     // Switch back to the funclet start .text section now that we are done
     267             :     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
     268             :     // the function.
     269         756 :     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
     270         756 :     Asm->OutStreamer->EmitWinCFIEndProc();
     271             :   }
     272             : 
     273             :   // Let's make sure we don't try to end the same funclet twice.
     274         407 :   CurrentFuncletEntry = nullptr;
     275             : }
     276             : 
     277         800 : const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
     278         800 :   if (!Value)
     279         142 :     return MCConstantExpr::create(0, Asm->OutContext);
     280        1316 :   return MCSymbolRefExpr::create(Value, useImageRel32
     281             :                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
     282             :                                             : MCSymbolRefExpr::VK_None,
     283        1316 :                                  Asm->OutContext);
     284             : }
     285             : 
     286          95 : const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
     287          95 :   if (!GV)
     288          47 :     return MCConstantExpr::create(0, Asm->OutContext);
     289          48 :   return create32bitRef(Asm->getSymbol(GV));
     290             : }
     291             : 
     292         130 : const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
     293         260 :   return MCBinaryExpr::createAdd(create32bitRef(Label),
     294         130 :                                  MCConstantExpr::create(1, Asm->OutContext),
     295         260 :                                  Asm->OutContext);
     296             : }
     297             : 
     298         141 : const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
     299             :                                       const MCSymbol *OffsetFrom) {
     300         141 :   return MCBinaryExpr::createSub(
     301         282 :       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
     302         564 :       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
     303             : }
     304             : 
     305          52 : const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
     306             :                                              const MCSymbol *OffsetFrom) {
     307         104 :   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
     308          52 :                                  MCConstantExpr::create(1, Asm->OutContext),
     309         104 :                                  Asm->OutContext);
     310             : }
     311             : 
     312          43 : int WinException::getFrameIndexOffset(int FrameIndex,
     313             :                                       const WinEHFuncInfo &FuncInfo) {
     314          43 :   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
     315             :   unsigned UnusedReg;
     316          43 :   if (Asm->MAI->usesWindowsCFI()) {
     317             :     int Offset =
     318          41 :         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
     319          82 :                                            /*IgnoreSPUpdates*/ true);
     320             :     assert(UnusedReg ==
     321             :            Asm->MF->getSubtarget()
     322             :                .getTargetLowering()
     323             :                ->getStackPointerRegisterToSaveRestore());
     324          41 :     return Offset;
     325             :   }
     326             : 
     327             :   // For 32-bit, offsets should be relative to the end of the EH registration
     328             :   // node. For 64-bit, it's relative to SP at the end of the prologue.
     329             :   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
     330           2 :   int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
     331           2 :   Offset += FuncInfo.EHRegNodeEndOffset;
     332           2 :   return Offset;
     333             : }
     334             : 
     335             : namespace {
     336             : 
     337             : /// Top-level state used to represent unwind to caller
     338             : const int NullState = -1;
     339             : 
     340             : struct InvokeStateChange {
     341             :   /// EH Label immediately after the last invoke in the previous state, or
     342             :   /// nullptr if the previous state was the null state.
     343             :   const MCSymbol *PreviousEndLabel;
     344             : 
     345             :   /// EH label immediately before the first invoke in the new state, or nullptr
     346             :   /// if the new state is the null state.
     347             :   const MCSymbol *NewStartLabel;
     348             : 
     349             :   /// State of the invoke following NewStartLabel, or NullState to indicate
     350             :   /// the presence of calls which may unwind to caller.
     351             :   int NewState;
     352             : };
     353             : 
     354             : /// Iterator that reports all the invoke state changes in a range of machine
     355             : /// basic blocks.  Changes to the null state are reported whenever a call that
     356             : /// may unwind to caller is encountered.  The MBB range is expected to be an
     357             : /// entire function or funclet, and the start and end of the range are treated
     358             : /// as being in the NullState even if there's not an unwind-to-caller call
     359             : /// before the first invoke or after the last one (i.e., the first state change
     360             : /// reported is the first change to something other than NullState, and a
     361             : /// change back to NullState is always reported at the end of iteration).
     362             : class InvokeStateChangeIterator {
     363             :   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
     364             :                             MachineFunction::const_iterator MFI,
     365             :                             MachineFunction::const_iterator MFE,
     366             :                             MachineBasicBlock::const_iterator MBBI,
     367             :                             int BaseState)
     368         236 :       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
     369         236 :     LastStateChange.PreviousEndLabel = nullptr;
     370         236 :     LastStateChange.NewStartLabel = nullptr;
     371         236 :     LastStateChange.NewState = BaseState;
     372         236 :     scan();
     373             :   }
     374             : 
     375             : public:
     376             :   static iterator_range<InvokeStateChangeIterator>
     377         118 :   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
     378             :         MachineFunction::const_iterator End, int BaseState = NullState) {
     379             :     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
     380             :     // the end of the last block.
     381             :     assert(Begin != End);
     382         236 :     auto BlockBegin = Begin->begin();
     383         354 :     auto BlockEnd = std::prev(End)->end();
     384             :     return make_range(
     385             :         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
     386         354 :         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
     387             :   }
     388             : 
     389             :   // Iterator methods.
     390             :   bool operator==(const InvokeStateChangeIterator &O) const {
     391             :     assert(BaseState == O.BaseState);
     392             :     // Must be visiting same block.
     393         534 :     if (MFI != O.MFI)
     394             :       return false;
     395             :     // Must be visiting same isntr.
     396         352 :     if (MBBI != O.MBBI)
     397             :       return false;
     398             :     // At end of block/instr iteration, we can still have two distinct states:
     399             :     // one to report the final EndLabel, and another indicating the end of the
     400             :     // state change iteration.  Check for CurrentEndLabel equality to
     401             :     // distinguish these.
     402         176 :     return CurrentEndLabel == O.CurrentEndLabel;
     403             :   }
     404             : 
     405             :   bool operator!=(const InvokeStateChangeIterator &O) const {
     406         176 :     return !operator==(O);
     407             :   }
     408             :   InvokeStateChange &operator*() { return LastStateChange; }
     409             :   InvokeStateChange *operator->() { return &LastStateChange; }
     410         149 :   InvokeStateChangeIterator &operator++() { return scan(); }
     411             : 
     412             : private:
     413             :   InvokeStateChangeIterator &scan();
     414             : 
     415             :   const WinEHFuncInfo &EHInfo;
     416             :   const MCSymbol *CurrentEndLabel = nullptr;
     417             :   MachineFunction::const_iterator MFI;
     418             :   MachineFunction::const_iterator MFE;
     419             :   MachineBasicBlock::const_iterator MBBI;
     420             :   InvokeStateChange LastStateChange;
     421             :   bool VisitingInvoke = false;
     422             :   int BaseState;
     423             : };
     424             : 
     425             : } // end anonymous namespace
     426             : 
     427         385 : InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
     428         385 :   bool IsNewBlock = false;
     429        1834 :   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
     430         357 :     if (IsNewBlock)
     431         444 :       MBBI = MFI->begin();
     432        5324 :     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
     433        4078 :       const MachineInstr &MI = *MBBI;
     434        4169 :       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
     435        2411 :           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
     436             :         // Indicate a change of state to the null state.  We don't have
     437             :         // start/end EH labels handy but the caller won't expect them for
     438             :         // null state regions.
     439           8 :         LastStateChange.PreviousEndLabel = CurrentEndLabel;
     440           8 :         LastStateChange.NewStartLabel = nullptr;
     441           8 :         LastStateChange.NewState = BaseState;
     442           8 :         CurrentEndLabel = nullptr;
     443             :         // Don't re-visit this instr on the next scan
     444          16 :         ++MBBI;
     445          99 :         return *this;
     446             :       }
     447             : 
     448             :       // All other state changes are at EH labels before/after invokes.
     449        2031 :       if (!MI.isEHLabel())
     450        3795 :         continue;
     451         184 :       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
     452         276 :       if (Label == CurrentEndLabel) {
     453          92 :         VisitingInvoke = false;
     454          92 :         continue;
     455             :       }
     456          92 :       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
     457             :       // Ignore EH labels that aren't the ones inserted before an invoke
     458         184 :       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
     459           0 :         continue;
     460          92 :       auto &StateAndEnd = InvokeMapIter->second;
     461          92 :       int NewState = StateAndEnd.first;
     462             :       // Keep track of the fact that we're between EH start/end labels so
     463             :       // we know not to treat the inoke we'll see as unwinding to caller.
     464          92 :       VisitingInvoke = true;
     465         101 :       if (NewState == LastStateChange.NewState) {
     466             :         // The state isn't actually changing here.  Record the new end and
     467             :         // keep going.
     468           9 :         CurrentEndLabel = StateAndEnd.second;
     469           9 :         continue;
     470             :       }
     471             :       // Found a state change to report
     472          83 :       LastStateChange.PreviousEndLabel = CurrentEndLabel;
     473          83 :       LastStateChange.NewStartLabel = Label;
     474          83 :       LastStateChange.NewState = NewState;
     475             :       // Start keeping track of the new current end
     476          83 :       CurrentEndLabel = StateAndEnd.second;
     477             :       // Don't re-visit this instr on the next scan
     478         166 :       ++MBBI;
     479          83 :       return *this;
     480             :     }
     481             :   }
     482             :   // Iteration hit the end of the block range.
     483         294 :   if (LastStateChange.NewState != BaseState) {
     484             :     // Report the end of the last new state
     485          58 :     LastStateChange.PreviousEndLabel = CurrentEndLabel;
     486          58 :     LastStateChange.NewStartLabel = nullptr;
     487          58 :     LastStateChange.NewState = BaseState;
     488             :     // Leave CurrentEndLabel non-null to distinguish this state from end.
     489             :     assert(CurrentEndLabel != nullptr);
     490          58 :     return *this;
     491             :   }
     492             :   // We've reported all state changes and hit the end state.
     493         236 :   CurrentEndLabel = nullptr;
     494         236 :   return *this;
     495             : }
     496             : 
     497             : /// Emit the language-specific data that __C_specific_handler expects.  This
     498             : /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
     499             : /// up after faults with __try, __except, and __finally.  The typeinfo values
     500             : /// are not really RTTI data, but pointers to filter functions that return an
     501             : /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
     502             : /// blocks and other cleanups, the landing pad label is zero, and the filter
     503             : /// function is actually a cleanup handler with the same prototype.  A catch-all
     504             : /// entry is modeled with a null filter function field and a non-zero landing
     505             : /// pad label.
     506             : ///
     507             : /// Possible filter function return values:
     508             : ///   EXCEPTION_EXECUTE_HANDLER (1):
     509             : ///     Jump to the landing pad label after cleanups.
     510             : ///   EXCEPTION_CONTINUE_SEARCH (0):
     511             : ///     Continue searching this table or continue unwinding.
     512             : ///   EXCEPTION_CONTINUE_EXECUTION (-1):
     513             : ///     Resume execution at the trapping PC.
     514             : ///
     515             : /// Inferred table structure:
     516             : ///   struct Table {
     517             : ///     int NumEntries;
     518             : ///     struct Entry {
     519             : ///       imagerel32 LabelStart;
     520             : ///       imagerel32 LabelEnd;
     521             : ///       imagerel32 FilterOrFinally;  // One means catch-all.
     522             : ///       imagerel32 LabelLPad;        // Zero means __finally.
     523             : ///     } Entries[NumEntries];
     524             : ///   };
     525          11 : void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
     526          22 :   auto &OS = *Asm->OutStreamer;
     527          11 :   MCContext &Ctx = Asm->OutContext;
     528          11 :   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
     529             : 
     530          11 :   bool VerboseAsm = OS.isVerboseAsm();
     531             :   auto AddComment = [&](const Twine &Comment) {
     532          11 :     if (VerboseAsm)
     533          11 :       OS.AddComment(Comment);
     534          11 :   };
     535             : 
     536             :   // Emit a label assignment with the SEH frame offset so we can use it for
     537             :   // llvm.x86.seh.recoverfp.
     538             :   StringRef FLinkageName =
     539          11 :       GlobalValue::dropLLVMManglingEscape(MF->getFunction()->getName());
     540             :   MCSymbol *ParentFrameOffset =
     541          11 :       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
     542             :   const MCExpr *MCOffset =
     543          11 :       MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
     544          22 :   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
     545             : 
     546             :   // Use the assembler to compute the number of table entries through label
     547             :   // difference and division.
     548             :   MCSymbol *TableBegin =
     549          11 :       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
     550             :   MCSymbol *TableEnd =
     551          11 :       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
     552          11 :   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
     553          11 :   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
     554          11 :   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
     555          22 :   AddComment("Number of call sites");
     556          11 :   OS.EmitValue(EntryCount, 4);
     557             : 
     558          11 :   OS.EmitLabel(TableBegin);
     559             : 
     560             :   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
     561             :   // models exceptions from invokes. LLVM also allows arbitrary reordering of
     562             :   // the code, so our tables end up looking a bit different. Rather than
     563             :   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
     564             :   // each range of invokes in the same state, we emit table entries for all
     565             :   // the actions that would be taken in that state. This means our tables are
     566             :   // slightly bigger, which is OK.
     567          11 :   const MCSymbol *LastStartLabel = nullptr;
     568          11 :   int LastEHState = -1;
     569             :   // Break out before we enter into a finally funclet.
     570             :   // FIXME: We need to emit separate EH tables for cleanups.
     571          11 :   MachineFunction::const_iterator End = MF->end();
     572          11 :   MachineFunction::const_iterator Stop = std::next(MF->begin());
     573          82 :   while (Stop != End && !Stop->isEHFuncletEntry())
     574             :     ++Stop;
     575             :   for (const auto &StateChange :
     576          39 :        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
     577             :     // Emit all the actions for the state we just transitioned out of
     578             :     // if it was not the null state
     579          26 :     if (LastEHState != -1)
     580          15 :       emitSEHActionsForRange(FuncInfo, LastStartLabel,
     581          15 :                              StateChange.PreviousEndLabel, LastEHState);
     582          26 :     LastStartLabel = StateChange.NewStartLabel;
     583          26 :     LastEHState = StateChange.NewState;
     584             :   }
     585             : 
     586          11 :   OS.EmitLabel(TableEnd);
     587          11 : }
     588             : 
     589          15 : void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
     590             :                                           const MCSymbol *BeginLabel,
     591             :                                           const MCSymbol *EndLabel, int State) {
     592          30 :   auto &OS = *Asm->OutStreamer;
     593          15 :   MCContext &Ctx = Asm->OutContext;
     594             : 
     595          15 :   bool VerboseAsm = OS.isVerboseAsm();
     596             :   auto AddComment = [&](const Twine &Comment) {
     597          84 :     if (VerboseAsm)
     598          84 :       OS.AddComment(Comment);
     599          15 :   };
     600             : 
     601             :   assert(BeginLabel && EndLabel);
     602          57 :   while (State != -1) {
     603          42 :     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
     604             :     const MCExpr *FilterOrFinally;
     605             :     const MCExpr *ExceptOrNull;
     606          42 :     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
     607          21 :     if (UME.IsFinally) {
     608           5 :       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
     609           5 :       ExceptOrNull = MCConstantExpr::create(0, Ctx);
     610             :     } else {
     611             :       // For an except, the filter can be 1 (catch-all) or a function
     612             :       // label.
     613          16 :       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
     614             :                                    : MCConstantExpr::create(1, Ctx);
     615          16 :       ExceptOrNull = create32bitRef(Handler->getSymbol());
     616             :     }
     617             : 
     618          42 :     AddComment("LabelStart");
     619          21 :     OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
     620          42 :     AddComment("LabelEnd");
     621          21 :     OS.EmitValue(getLabelPlusOne(EndLabel), 4);
     622          63 :     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
     623             :                                                              : "CatchAll");
     624          21 :     OS.EmitValue(FilterOrFinally, 4);
     625          63 :     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
     626          21 :     OS.EmitValue(ExceptOrNull, 4);
     627             : 
     628             :     assert(UME.ToState < State && "states should decrease");
     629          21 :     State = UME.ToState;
     630             :   }
     631          15 : }
     632             : 
     633          53 : void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
     634          53 :   const Function *F = MF->getFunction();
     635         106 :   auto &OS = *Asm->OutStreamer;
     636          53 :   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
     637             : 
     638          53 :   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName());
     639             : 
     640         106 :   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
     641          53 :   MCSymbol *FuncInfoXData = nullptr;
     642          53 :   if (shouldEmitPersonality) {
     643             :     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
     644             :     // IPs to state numbers.
     645          35 :     FuncInfoXData =
     646         105 :         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
     647          35 :     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
     648             :   } else {
     649          18 :     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
     650             :   }
     651             : 
     652          53 :   int UnwindHelpOffset = 0;
     653          53 :   if (Asm->MAI->usesWindowsCFI())
     654          35 :     UnwindHelpOffset =
     655          35 :         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
     656             : 
     657          53 :   MCSymbol *UnwindMapXData = nullptr;
     658          53 :   MCSymbol *TryBlockMapXData = nullptr;
     659          53 :   MCSymbol *IPToStateXData = nullptr;
     660          53 :   if (!FuncInfo.CxxUnwindMap.empty())
     661         106 :     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
     662         106 :         Twine("$stateUnwindMap$", FuncLinkageName));
     663          53 :   if (!FuncInfo.TryBlockMap.empty())
     664          45 :     TryBlockMapXData =
     665         135 :         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
     666          53 :   if (!IPToStateTable.empty())
     667          35 :     IPToStateXData =
     668         105 :         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
     669             : 
     670          53 :   bool VerboseAsm = OS.isVerboseAsm();
     671             :   auto AddComment = [&](const Twine &Comment) {
     672        1722 :     if (VerboseAsm)
     673        1722 :       OS.AddComment(Comment);
     674          53 :   };
     675             : 
     676             :   // FuncInfo {
     677             :   //   uint32_t           MagicNumber
     678             :   //   int32_t            MaxState;
     679             :   //   UnwindMapEntry    *UnwindMap;
     680             :   //   uint32_t           NumTryBlocks;
     681             :   //   TryBlockMapEntry  *TryBlockMap;
     682             :   //   uint32_t           IPMapEntries; // always 0 for x86
     683             :   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
     684             :   //   uint32_t           UnwindHelp;   // non-x86 only
     685             :   //   ESTypeList        *ESTypeList;
     686             :   //   int32_t            EHFlags;
     687             :   // }
     688             :   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
     689             :   // EHFlags & 2 -> ???
     690             :   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
     691          53 :   OS.EmitValueToAlignment(4);
     692          53 :   OS.EmitLabel(FuncInfoXData);
     693             : 
     694         106 :   AddComment("MagicNumber");
     695          53 :   OS.EmitIntValue(0x19930522, 4);
     696             : 
     697         106 :   AddComment("MaxState");
     698         106 :   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
     699             : 
     700         106 :   AddComment("UnwindMap");
     701          53 :   OS.EmitValue(create32bitRef(UnwindMapXData), 4);
     702             : 
     703         106 :   AddComment("NumTryBlocks");
     704         106 :   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
     705             : 
     706         106 :   AddComment("TryBlockMap");
     707          53 :   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
     708             : 
     709         106 :   AddComment("IPMapEntries");
     710         106 :   OS.EmitIntValue(IPToStateTable.size(), 4);
     711             : 
     712         106 :   AddComment("IPToStateXData");
     713          53 :   OS.EmitValue(create32bitRef(IPToStateXData), 4);
     714             : 
     715          53 :   if (Asm->MAI->usesWindowsCFI()) {
     716          70 :     AddComment("UnwindHelp");
     717          35 :     OS.EmitIntValue(UnwindHelpOffset, 4);
     718             :   }
     719             : 
     720         106 :   AddComment("ESTypeList");
     721          53 :   OS.EmitIntValue(0, 4);
     722             : 
     723         106 :   AddComment("EHFlags");
     724          53 :   OS.EmitIntValue(1, 4);
     725             : 
     726             :   // UnwindMapEntry {
     727             :   //   int32_t ToState;
     728             :   //   void  (*Action)();
     729             :   // };
     730          53 :   if (UnwindMapXData) {
     731          53 :     OS.EmitLabel(UnwindMapXData);
     732         297 :     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
     733             :       MCSymbol *CleanupSym =
     734         276 :           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
     735         276 :       AddComment("ToState");
     736         138 :       OS.EmitIntValue(UME.ToState, 4);
     737             : 
     738         276 :       AddComment("Action");
     739         138 :       OS.EmitValue(create32bitRef(CleanupSym), 4);
     740             :     }
     741             :   }
     742             : 
     743             :   // TryBlockMap {
     744             :   //   int32_t      TryLow;
     745             :   //   int32_t      TryHigh;
     746             :   //   int32_t      CatchHigh;
     747             :   //   int32_t      NumCatches;
     748             :   //   HandlerType *HandlerArray;
     749             :   // };
     750          53 :   if (TryBlockMapXData) {
     751          45 :     OS.EmitLabel(TryBlockMapXData);
     752          90 :     SmallVector<MCSymbol *, 1> HandlerMaps;
     753         148 :     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
     754         116 :       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
     755             : 
     756          58 :       MCSymbol *HandlerMapXData = nullptr;
     757          58 :       if (!TBME.HandlerArray.empty())
     758          58 :         HandlerMapXData =
     759         232 :             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
     760         116 :                                                   .concat(Twine(I))
     761         116 :                                                   .concat("$")
     762         116 :                                                   .concat(FuncLinkageName));
     763          58 :       HandlerMaps.push_back(HandlerMapXData);
     764             : 
     765             :       // TBMEs should form intervals.
     766             :       assert(0 <= TBME.TryLow && "bad trymap interval");
     767             :       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
     768             :       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
     769             :       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
     770             :              "bad trymap interval");
     771             : 
     772         116 :       AddComment("TryLow");
     773          58 :       OS.EmitIntValue(TBME.TryLow, 4);
     774             : 
     775         116 :       AddComment("TryHigh");
     776          58 :       OS.EmitIntValue(TBME.TryHigh, 4);
     777             : 
     778         116 :       AddComment("CatchHigh");
     779          58 :       OS.EmitIntValue(TBME.CatchHigh, 4);
     780             : 
     781         116 :       AddComment("NumCatches");
     782         116 :       OS.EmitIntValue(TBME.HandlerArray.size(), 4);
     783             : 
     784         116 :       AddComment("HandlerArray");
     785          58 :       OS.EmitValue(create32bitRef(HandlerMapXData), 4);
     786             :     }
     787             : 
     788             :     // All funclets use the same parent frame offset currently.
     789          45 :     unsigned ParentFrameOffset = 0;
     790          45 :     if (shouldEmitPersonality) {
     791          31 :       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
     792          31 :       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
     793             :     }
     794             : 
     795         148 :     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
     796         116 :       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
     797          58 :       MCSymbol *HandlerMapXData = HandlerMaps[I];
     798          58 :       if (!HandlerMapXData)
     799           0 :         continue;
     800             :       // HandlerType {
     801             :       //   int32_t         Adjectives;
     802             :       //   TypeDescriptor *Type;
     803             :       //   int32_t         CatchObjOffset;
     804             :       //   void          (*Handler)();
     805             :       //   int32_t         ParentFrameOffset; // x64 only
     806             :       // };
     807          58 :       OS.EmitLabel(HandlerMapXData);
     808         239 :       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
     809             :         // Get the frame escape label with the offset of the catch object. If
     810             :         // the index is INT_MAX, then there is no catch object, and we should
     811             :         // emit an offset of zero, indicating that no copy will occur.
     812          65 :         const MCExpr *FrameAllocOffsetRef = nullptr;
     813          65 :         if (HT.CatchObj.FrameIndex != INT_MAX) {
     814           8 :           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
     815             :           assert(Offset != 0 && "Illegal offset for catch object!");
     816           8 :           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
     817             :         } else {
     818          57 :           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
     819             :         }
     820             : 
     821             :         MCSymbol *HandlerSym =
     822         130 :             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
     823             : 
     824         130 :         AddComment("Adjectives");
     825          65 :         OS.EmitIntValue(HT.Adjectives, 4);
     826             : 
     827         130 :         AddComment("Type");
     828          65 :         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
     829             : 
     830         130 :         AddComment("CatchObjOffset");
     831          65 :         OS.EmitValue(FrameAllocOffsetRef, 4);
     832             : 
     833         130 :         AddComment("Handler");
     834          65 :         OS.EmitValue(create32bitRef(HandlerSym), 4);
     835             : 
     836          65 :         if (shouldEmitPersonality) {
     837          92 :           AddComment("ParentFrameOffset");
     838          46 :           OS.EmitIntValue(ParentFrameOffset, 4);
     839             :         }
     840             :       }
     841             :     }
     842             :   }
     843             : 
     844             :   // IPToStateMapEntry {
     845             :   //   void   *IP;
     846             :   //   int32_t State;
     847             :   // };
     848          53 :   if (IPToStateXData) {
     849          35 :     OS.EmitLabel(IPToStateXData);
     850         274 :     for (auto &IPStatePair : IPToStateTable) {
     851         338 :       AddComment("IP");
     852         169 :       OS.EmitValue(IPStatePair.first, 4);
     853         338 :       AddComment("ToState");
     854         169 :       OS.EmitIntValue(IPStatePair.second, 4);
     855             :     }
     856             :   }
     857          53 : }
     858             : 
     859          35 : void WinException::computeIP2StateTable(
     860             :     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
     861             :     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
     862             : 
     863          35 :   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
     864          35 :                                        FuncletEnd = MF->begin(),
     865          35 :                                        End = MF->end();
     866         131 :        FuncletStart != End; FuncletStart = FuncletEnd) {
     867             :     // Find the end of the funclet
     868         188 :     while (++FuncletEnd != End) {
     869         153 :       if (FuncletEnd->isEHFuncletEntry()) {
     870             :         break;
     871             :       }
     872             :     }
     873             : 
     874             :     // Don't emit ip2state entries for cleanup funclets. Any interesting
     875             :     // exceptional actions in cleanups must be handled in a separate IR
     876             :     // function.
     877          96 :     if (FuncletStart->isCleanupFuncletEntry())
     878          15 :       continue;
     879             : 
     880             :     MCSymbol *StartLabel;
     881             :     int BaseState;
     882          81 :     if (FuncletStart == MF->begin()) {
     883          35 :       BaseState = NullState;
     884          35 :       StartLabel = Asm->getFunctionBegin();
     885             :     } else {
     886             :       auto *FuncletPad =
     887          92 :           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
     888             :       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
     889          46 :       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
     890          46 :       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
     891             :     }
     892             :     assert(StartLabel && "need local function start label");
     893         162 :     IPToStateTable.push_back(
     894         243 :         std::make_pair(create32bitRef(StartLabel), BaseState));
     895             : 
     896             :     for (const auto &StateChange : InvokeStateChangeIterator::range(
     897         280 :              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
     898             :       // Compute the label to report as the start of this entry; use the EH
     899             :       // start label for the invoke if we have one, otherwise (this is a call
     900             :       // which may unwind to our caller and does not have an EH start label, so)
     901             :       // use the previous end label.
     902          88 :       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
     903          88 :       if (!ChangeLabel)
     904          39 :         ChangeLabel = StateChange.PreviousEndLabel;
     905             :       // Emit an entry indicating that PCs after 'Label' have this EH state.
     906          88 :       IPToStateTable.push_back(
     907         264 :           std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
     908             :       // FIXME: assert that NewState is between CatchLow and CatchHigh.
     909             :     }
     910             :   }
     911          35 : }
     912             : 
     913          13 : void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
     914             :                                                  StringRef FLinkageName) {
     915             :   // Outlined helpers called by the EH runtime need to know the offset of the EH
     916             :   // registration in order to recover the parent frame pointer. Now that we know
     917             :   // we've code generated the parent, we can emit the label assignment that
     918             :   // those helpers use to get the offset of the registration node.
     919             : 
     920             :   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
     921             :   // after optimization all the invokes were eliminated. We still need to emit
     922             :   // the parent frame offset label, but it should be garbage and should never be
     923             :   // used.
     924          13 :   int64_t Offset = 0;
     925          13 :   int FI = FuncInfo.EHRegNodeFrameIndex;
     926          13 :   if (FI != INT_MAX) {
     927          12 :     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
     928             :     unsigned UnusedReg;
     929          12 :     Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
     930             :   }
     931             : 
     932          13 :   MCContext &Ctx = Asm->OutContext;
     933             :   MCSymbol *ParentFrameOffset =
     934          13 :       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
     935          39 :   Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
     936          13 :                                    MCConstantExpr::create(Offset, Ctx));
     937          13 : }
     938             : 
     939             : /// Emit the language-specific data that _except_handler3 and 4 expect. This is
     940             : /// functionally equivalent to the __C_specific_handler table, except it is
     941             : /// indexed by state number instead of IP.
     942          12 : void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
     943          24 :   MCStreamer &OS = *Asm->OutStreamer;
     944          12 :   const Function *F = MF->getFunction();
     945          12 :   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName());
     946             : 
     947          12 :   bool VerboseAsm = OS.isVerboseAsm();
     948             :   auto AddComment = [&](const Twine &Comment) {
     949          65 :     if (VerboseAsm)
     950          65 :       OS.AddComment(Comment);
     951          12 :   };
     952             : 
     953          12 :   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
     954          12 :   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
     955             : 
     956             :   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
     957          12 :   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
     958          12 :   OS.EmitValueToAlignment(4);
     959          12 :   OS.EmitLabel(LSDALabel);
     960             : 
     961             :   const Function *Per =
     962          36 :       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
     963          12 :   StringRef PerName = Per->getName();
     964          12 :   int BaseState = -1;
     965          14 :   if (PerName == "_except_handler4") {
     966             :     // The LSDA for _except_handler4 starts with this struct, followed by the
     967             :     // scope table:
     968             :     //
     969             :     // struct EH4ScopeTable {
     970             :     //   int32_t GSCookieOffset;
     971             :     //   int32_t GSCookieXOROffset;
     972             :     //   int32_t EHCookieOffset;
     973             :     //   int32_t EHCookieXOROffset;
     974             :     //   ScopeTableEntry ScopeRecord[];
     975             :     // };
     976             :     //
     977             :     // Offsets are %ebp relative.
     978             :     //
     979             :     // The GS cookie is present only if the function needs stack protection.
     980             :     // GSCookieOffset = -2 means that GS cookie is not used.
     981             :     //
     982             :     // The EH cookie is always present.
     983             :     //
     984             :     // Check is done the following way:
     985             :     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
     986             : 
     987             :     // Retrieve the Guard Stack slot.
     988           2 :     int GSCookieOffset = -2;
     989           2 :     const MachineFrameInfo &MFI = MF->getFrameInfo();
     990           2 :     if (MFI.hasStackProtectorIndex()) {
     991             :       unsigned UnusedReg;
     992           0 :       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
     993           0 :       int SSPIdx = MFI.getStackProtectorIndex();
     994           0 :       GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
     995             :     }
     996             : 
     997             :     // Retrieve the EH Guard slot.
     998             :     // TODO(etienneb): Get rid of this value and change it for and assertion.
     999           2 :     int EHCookieOffset = 9999;
    1000           2 :     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
    1001             :       unsigned UnusedReg;
    1002           2 :       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
    1003           2 :       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
    1004           2 :       EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
    1005             :     }
    1006             : 
    1007           4 :     AddComment("GSCookieOffset");
    1008           2 :     OS.EmitIntValue(GSCookieOffset, 4);
    1009           4 :     AddComment("GSCookieXOROffset");
    1010           2 :     OS.EmitIntValue(0, 4);
    1011           4 :     AddComment("EHCookieOffset");
    1012           2 :     OS.EmitIntValue(EHCookieOffset, 4);
    1013           4 :     AddComment("EHCookieXOROffset");
    1014           2 :     OS.EmitIntValue(0, 4);
    1015           2 :     BaseState = -2;
    1016             :   }
    1017             : 
    1018             :   assert(!FuncInfo.SEHUnwindMap.empty());
    1019          55 :   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
    1020          38 :     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
    1021             :     const MCSymbol *ExceptOrFinally =
    1022          19 :         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
    1023             :     // -1 is usually the base state for "unwind to caller", but for
    1024             :     // _except_handler4 it's -2. Do that replacement here if necessary.
    1025          19 :     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
    1026          38 :     AddComment("ToState");
    1027          19 :     OS.EmitIntValue(ToState, 4);
    1028          57 :     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
    1029          19 :     OS.EmitValue(create32bitRef(UME.Filter), 4);
    1030          57 :     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
    1031          19 :     OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
    1032             :   }
    1033          12 : }
    1034             : 
    1035             : static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
    1036          35 :   int Rank = 0;
    1037         126 :   while (State != -1) {
    1038          56 :     ++Rank;
    1039         112 :     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
    1040             :   }
    1041             :   return Rank;
    1042             : }
    1043             : 
    1044          35 : static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
    1045             :   int LeftRank = getTryRank(FuncInfo, Left);
    1046             :   int RightRank = getTryRank(FuncInfo, Right);
    1047             : 
    1048          85 :   while (LeftRank < RightRank) {
    1049          50 :     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
    1050          25 :     --RightRank;
    1051             :   }
    1052             : 
    1053          85 :   while (RightRank < LeftRank) {
    1054          50 :     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
    1055          25 :     --LeftRank;
    1056             :   }
    1057             : 
    1058          37 :   while (Left != Right) {
    1059           2 :     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
    1060           2 :     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
    1061             :   }
    1062             : 
    1063          35 :   return Left;
    1064             : }
    1065             : 
    1066           7 : void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
    1067             :   // CLR EH "states" are really just IDs that identify handlers/funclets;
    1068             :   // states, handlers, and funclets all have 1:1 mappings between them, and a
    1069             :   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
    1070          14 :   MCStreamer &OS = *Asm->OutStreamer;
    1071           7 :   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
    1072           7 :   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
    1073           7 :   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
    1074             : 
    1075             :   // A ClrClause describes a protected region.
    1076             :   struct ClrClause {
    1077             :     const MCSymbol *StartLabel; // Start of protected region
    1078             :     const MCSymbol *EndLabel;   // End of protected region
    1079             :     int State;          // Index of handler protecting the protected region
    1080             :     int EnclosingState; // Index of funclet enclosing the protected region
    1081             :   };
    1082          14 :   SmallVector<ClrClause, 8> Clauses;
    1083             : 
    1084             :   // Build a map from handler MBBs to their corresponding states (i.e. their
    1085             :   // indices in the ClrEHUnwindMap).
    1086          14 :   int NumStates = FuncInfo.ClrEHUnwindMap.size();
    1087             :   assert(NumStates > 0 && "Don't need exception table!");
    1088          14 :   DenseMap<const MachineBasicBlock *, int> HandlerStates;
    1089          26 :   for (int State = 0; State < NumStates; ++State) {
    1090             :     MachineBasicBlock *HandlerBlock =
    1091          57 :         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
    1092          38 :     HandlerStates[HandlerBlock] = State;
    1093             :     // Use this loop through all handlers to verify our assumption (used in
    1094             :     // the MinEnclosingState computation) that enclosing funclets have lower
    1095             :     // state numbers than their enclosed funclets.
    1096             :     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
    1097             :            "ill-formed state numbering");
    1098             :   }
    1099             :   // Map the main function to the NullState.
    1100          14 :   HandlerStates[&MF->front()] = NullState;
    1101             : 
    1102             :   // Write out a sentinel indicating the end of the standard (Windows) xdata
    1103             :   // and the start of the additional (CLR) info.
    1104           7 :   OS.EmitIntValue(0xffffffff, 4);
    1105             :   // Write out the number of funclets
    1106           7 :   OS.EmitIntValue(NumStates, 4);
    1107             : 
    1108             :   // Walk the machine blocks/instrs, computing and emitting a few things:
    1109             :   // 1. Emit a list of the offsets to each handler entry, in lexical order.
    1110             :   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
    1111             :   // 3. Compute the list of ClrClauses, in the required order (inner before
    1112             :   //    outer, earlier before later; the order by which a forward scan with
    1113             :   //    early termination will find the innermost enclosing clause covering
    1114             :   //    a given address).
    1115             :   // 4. A map (MinClauseMap) from each handler index to the index of the
    1116             :   //    outermost funclet/function which contains a try clause targeting the
    1117             :   //    key handler.  This will be used to determine IsDuplicate-ness when
    1118             :   //    emitting ClrClauses.  The NullState value is used to indicate that the
    1119             :   //    top-level function contains a try clause targeting the key handler.
    1120             :   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
    1121             :   // try regions we entered before entering the PendingState try but which
    1122             :   // we haven't yet exited.
    1123          14 :   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
    1124             :   // EndSymbolMap and MinClauseMap are maps described above.
    1125          21 :   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
    1126          21 :   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
    1127             : 
    1128             :   // Visit the root function and each funclet.
    1129          33 :   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
    1130           7 :                                        FuncletEnd = MF->begin(),
    1131           7 :                                        End = MF->end();
    1132          59 :        FuncletStart != End; FuncletStart = FuncletEnd) {
    1133          52 :     int FuncletState = HandlerStates[&*FuncletStart];
    1134             :     // Find the end of the funclet
    1135          26 :     MCSymbol *EndSymbol = FuncEndSym;
    1136          49 :     while (++FuncletEnd != End) {
    1137          42 :       if (FuncletEnd->isEHFuncletEntry()) {
    1138          19 :         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
    1139          19 :         break;
    1140             :       }
    1141             :     }
    1142             :     // Emit the function/funclet end and, if this is a funclet (and not the
    1143             :     // root function), record it in the EndSymbolMap.
    1144          26 :     OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
    1145          26 :     if (FuncletState != NullState) {
    1146             :       // Record the end of the handler.
    1147          38 :       EndSymbolMap[FuncletState] = EndSymbol;
    1148             :     }
    1149             : 
    1150             :     // Walk the state changes in this function/funclet and compute its clauses.
    1151             :     // Funclets always start in the null state.
    1152          26 :     const MCSymbol *CurrentStartLabel = nullptr;
    1153          26 :     int CurrentState = NullState;
    1154             :     assert(HandlerStack.empty());
    1155             :     for (const auto &StateChange :
    1156          93 :          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
    1157             :       // Close any try regions we're not still under
    1158             :       int StillPendingState =
    1159          35 :           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
    1160          61 :       while (CurrentState != StillPendingState) {
    1161             :         assert(CurrentState != NullState &&
    1162             :                "Failed to find still-pending state!");
    1163             :         // Close the pending clause
    1164          26 :         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
    1165             :                            CurrentState, FuncletState});
    1166             :         // Now the next-outer try region is current
    1167          52 :         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
    1168             :         // Pop the new start label from the handler stack if we've exited all
    1169             :         // inner try regions of the corresponding try region.
    1170          52 :         if (HandlerStack.back().second == CurrentState)
    1171          19 :           CurrentStartLabel = HandlerStack.pop_back_val().first;
    1172             :       }
    1173             : 
    1174          35 :       if (StateChange.NewState != CurrentState) {
    1175             :         // For each clause we're starting, update the MinClauseMap so we can
    1176             :         // know which is the topmost funclet containing a clause targeting
    1177             :         // it.
    1178          26 :         for (int EnteredState = StateChange.NewState;
    1179          45 :              EnteredState != CurrentState;
    1180          26 :              EnteredState =
    1181          52 :                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
    1182          52 :           int &MinEnclosingState = MinClauseMap[EnteredState];
    1183          26 :           if (FuncletState < MinEnclosingState)
    1184          22 :             MinEnclosingState = FuncletState;
    1185             :         }
    1186             :         // Save the previous current start/label on the stack and update to
    1187             :         // the newly-current start/state.
    1188          19 :         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
    1189          19 :         CurrentStartLabel = StateChange.NewStartLabel;
    1190          19 :         CurrentState = StateChange.NewState;
    1191             :       }
    1192             :     }
    1193             :     assert(HandlerStack.empty());
    1194             :   }
    1195             : 
    1196             :   // Now emit the clause info, starting with the number of clauses.
    1197          14 :   OS.EmitIntValue(Clauses.size(), 4);
    1198          47 :   for (ClrClause &Clause : Clauses) {
    1199             :     // Emit a CORINFO_EH_CLAUSE :
    1200             :     /*
    1201             :       struct CORINFO_EH_CLAUSE
    1202             :       {
    1203             :           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
    1204             :           DWORD                   TryOffset;
    1205             :           DWORD                   TryLength;     // actually TryEndOffset
    1206             :           DWORD                   HandlerOffset;
    1207             :           DWORD                   HandlerLength; // actually HandlerEndOffset
    1208             :           union
    1209             :           {
    1210             :               DWORD               ClassToken;   // use for catch clauses
    1211             :               DWORD               FilterOffset; // use for filter clauses
    1212             :           };
    1213             :       };
    1214             : 
    1215             :       enum CORINFO_EH_CLAUSE_FLAGS
    1216             :       {
    1217             :           CORINFO_EH_CLAUSE_NONE    = 0,
    1218             :           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
    1219             :           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
    1220             :           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
    1221             :       };
    1222             :       typedef enum CorExceptionFlag
    1223             :       {
    1224             :           COR_ILEXCEPTION_CLAUSE_NONE,
    1225             :           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
    1226             :           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
    1227             :           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
    1228             :           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
    1229             :                                                       // clause was duplicated
    1230             :                                                       // to a funclet which was
    1231             :                                                       // pulled out of line
    1232             :       } CorExceptionFlag;
    1233             :     */
    1234             :     // Add 1 to the start/end of the EH clause; the IP associated with a
    1235             :     // call when the runtime does its scan is the IP of the next instruction
    1236             :     // (the one to which control will return after the call), so we need
    1237             :     // to add 1 to the end of the clause to cover that offset.  We also add
    1238             :     // 1 to the start of the clause to make sure that the ranges reported
    1239             :     // for all clauses are disjoint.  Note that we'll need some additional
    1240             :     // logic when machine traps are supported, since in that case the IP
    1241             :     // that the runtime uses is the offset of the faulting instruction
    1242             :     // itself; if such an instruction immediately follows a call but the
    1243             :     // two belong to different clauses, we'll need to insert a nop between
    1244             :     // them so the runtime can distinguish the point to which the call will
    1245             :     // return from the point at which the fault occurs.
    1246             : 
    1247             :     const MCExpr *ClauseBegin =
    1248          26 :         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
    1249          26 :     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
    1250             : 
    1251          52 :     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
    1252          52 :     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
    1253          26 :     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
    1254          26 :     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
    1255          52 :     MCSymbol *EndSym = EndSymbolMap[Clause.State];
    1256          26 :     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
    1257             : 
    1258          26 :     uint32_t Flags = 0;
    1259          26 :     switch (Entry.HandlerType) {
    1260             :     case ClrHandlerType::Catch:
    1261             :       // Leaving bits 0-2 clear indicates catch.
    1262             :       break;
    1263             :     case ClrHandlerType::Filter:
    1264             :       Flags |= 1;
    1265             :       break;
    1266             :     case ClrHandlerType::Finally:
    1267             :       Flags |= 2;
    1268             :       break;
    1269             :     case ClrHandlerType::Fault:
    1270             :       Flags |= 4;
    1271             :       break;
    1272             :     }
    1273          52 :     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
    1274             :       // This is a "duplicate" clause; the handler needs to be entered from a
    1275             :       // frame above the one holding the invoke.
    1276             :       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
    1277           7 :       Flags |= 8;
    1278             :     }
    1279          26 :     OS.EmitIntValue(Flags, 4);
    1280             : 
    1281             :     // Write the clause start/end
    1282          26 :     OS.EmitValue(ClauseBegin, 4);
    1283          26 :     OS.EmitValue(ClauseEnd, 4);
    1284             : 
    1285             :     // Write out the handler start/end
    1286          26 :     OS.EmitValue(HandlerBegin, 4);
    1287          26 :     OS.EmitValue(HandlerEnd, 4);
    1288             : 
    1289             :     // Write out the type token or filter offset
    1290             :     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
    1291          26 :     OS.EmitIntValue(Entry.TypeToken, 4);
    1292             :   }
    1293           7 : }

Generated by: LCOV version 1.13