xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
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 Win64 exception info into asm files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "WinException.h"
140b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
150b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
160b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
250b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
260b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
270b57cec5SDimitry Andric #include "llvm/IR/Module.h"
280b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
290b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
300b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
310b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
320b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
330b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
340b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
350b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
360b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
375ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
380b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
420b57cec5SDimitry Andric   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
430b57cec5SDimitry Andric   // platforms use an imagerel32 relocation to refer to symbols.
440b57cec5SDimitry Andric   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
450b57cec5SDimitry Andric   isAArch64 = Asm->TM.getTargetTriple().isAArch64();
46*349cc55cSDimitry Andric   isThumb = Asm->TM.getTargetTriple().isThumb();
470b57cec5SDimitry Andric }
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric WinException::~WinException() {}
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric /// endModule - Emit all exception information that should come after the
520b57cec5SDimitry Andric /// content.
530b57cec5SDimitry Andric void WinException::endModule() {
540b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
550b57cec5SDimitry Andric   const Module *M = MMI->getModule();
560b57cec5SDimitry Andric   for (const Function &F : *M)
570b57cec5SDimitry Andric     if (F.hasFnAttribute("safeseh"))
580b57cec5SDimitry Andric       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
59fe6060f1SDimitry Andric 
60fe6060f1SDimitry Andric   if (M->getModuleFlag("ehcontguard") && !EHContTargets.empty()) {
61fe6060f1SDimitry Andric     // Emit the symbol index of each ehcont target.
62fe6060f1SDimitry Andric     OS.SwitchSection(Asm->OutContext.getObjectFileInfo()->getGEHContSection());
63fe6060f1SDimitry Andric     for (const MCSymbol *S : EHContTargets) {
64fe6060f1SDimitry Andric       OS.EmitCOFFSymbolIndex(S);
65fe6060f1SDimitry Andric     }
66fe6060f1SDimitry Andric   }
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric void WinException::beginFunction(const MachineFunction *MF) {
700b57cec5SDimitry Andric   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric   // If any landing pads survive, we need an EH table.
730b57cec5SDimitry Andric   bool hasLandingPads = !MF->getLandingPads().empty();
740b57cec5SDimitry Andric   bool hasEHFunclets = MF->hasEHFunclets();
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric   const Function &F = MF->getFunction();
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
810b57cec5SDimitry Andric   unsigned PerEncoding = TLOF.getPersonalityEncoding();
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
840b57cec5SDimitry Andric   const Function *PerFn = nullptr;
850b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
860b57cec5SDimitry Andric     PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
870b57cec5SDimitry Andric     Per = classifyEHPersonality(PerFn);
880b57cec5SDimitry Andric   }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   bool forceEmitPersonality = F.hasPersonalityFn() &&
910b57cec5SDimitry Andric                               !isNoOpWithoutInvoke(Per) &&
920b57cec5SDimitry Andric                               F.needsUnwindTableEntry();
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   shouldEmitPersonality =
950b57cec5SDimitry Andric       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
960b57cec5SDimitry Andric                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
990b57cec5SDimitry Andric   shouldEmitLSDA = shouldEmitPersonality &&
1000b57cec5SDimitry Andric     LSDAEncoding != dwarf::DW_EH_PE_omit;
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   // If we're not using CFI, we don't want the CFI or the personality, but we
1030b57cec5SDimitry Andric   // might want EH tables if we had EH pads.
1040b57cec5SDimitry Andric   if (!Asm->MAI->usesWindowsCFI()) {
1050b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
1060b57cec5SDimitry Andric       // If this is 32-bit SEH and we don't have any funclets (really invokes),
1070b57cec5SDimitry Andric       // make sure we emit the parent offset label. Some unreferenced filter
1080b57cec5SDimitry Andric       // functions may still refer to it.
1090b57cec5SDimitry Andric       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1100b57cec5SDimitry Andric       StringRef FLinkageName =
1110b57cec5SDimitry Andric           GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
1120b57cec5SDimitry Andric       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
1130b57cec5SDimitry Andric     }
1140b57cec5SDimitry Andric     shouldEmitLSDA = hasEHFunclets;
1150b57cec5SDimitry Andric     shouldEmitPersonality = false;
1160b57cec5SDimitry Andric     return;
1170b57cec5SDimitry Andric   }
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   beginFunclet(MF->front(), Asm->CurrentFnSym);
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric void WinException::markFunctionEnd() {
1230b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
1240b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality))
1250b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric /// endFunction - Gather and emit post-function exception information.
1290b57cec5SDimitry Andric ///
1300b57cec5SDimitry Andric void WinException::endFunction(const MachineFunction *MF) {
1310b57cec5SDimitry Andric   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
1320b57cec5SDimitry Andric     return;
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   const Function &F = MF->getFunction();
1350b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
1360b57cec5SDimitry Andric   if (F.hasPersonalityFn())
1370b57cec5SDimitry Andric     Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Get rid of any dead landing pads if we're not using funclets. In funclet
1400b57cec5SDimitry Andric   // schemes, the landing pad is not actually reachable. It only exists so
1410b57cec5SDimitry Andric   // that we can emit the right table data.
1420b57cec5SDimitry Andric   if (!isFuncletEHPersonality(Per)) {
1430b57cec5SDimitry Andric     MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
1440b57cec5SDimitry Andric     NonConstMF->tidyLandingPads();
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   endFuncletImpl();
1480b57cec5SDimitry Andric 
149e8d8bef9SDimitry Andric   // endFunclet will emit the necessary .xdata tables for table-based SEH.
150e8d8bef9SDimitry Andric   if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets())
1510b57cec5SDimitry Andric     return;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   if (shouldEmitPersonality || shouldEmitLSDA) {
1540b57cec5SDimitry Andric     Asm->OutStreamer->PushSection();
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     // Just switch sections to the right xdata section.
1570b57cec5SDimitry Andric     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
1580b57cec5SDimitry Andric         Asm->OutStreamer->getCurrentSectionOnly());
1590b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(XData);
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric     // Emit the tables appropriate to the personality function in use. If we
1620b57cec5SDimitry Andric     // don't recognize the personality, assume it uses an Itanium-style LSDA.
163e8d8bef9SDimitry Andric     if (Per == EHPersonality::MSVC_TableSEH)
1640b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
1650b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_X86SEH)
1660b57cec5SDimitry Andric       emitExceptHandlerTable(MF);
1670b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_CXX)
1680b57cec5SDimitry Andric       emitCXXFrameHandler3Table(MF);
1690b57cec5SDimitry Andric     else if (Per == EHPersonality::CoreCLR)
1700b57cec5SDimitry Andric       emitCLRExceptionTable(MF);
1710b57cec5SDimitry Andric     else
1720b57cec5SDimitry Andric       emitExceptionTable();
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric     Asm->OutStreamer->PopSection();
1750b57cec5SDimitry Andric   }
176fe6060f1SDimitry Andric 
177fe6060f1SDimitry Andric   if (!MF->getCatchretTargets().empty()) {
178fe6060f1SDimitry Andric     // Copy the function's catchret targets to a module-level list.
179fe6060f1SDimitry Andric     EHContTargets.insert(EHContTargets.end(), MF->getCatchretTargets().begin(),
180fe6060f1SDimitry Andric                          MF->getCatchretTargets().end());
181fe6060f1SDimitry Andric   }
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
1850b57cec5SDimitry Andric static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
1860b57cec5SDimitry Andric                                    const MachineBasicBlock *MBB) {
1870b57cec5SDimitry Andric   if (!MBB)
1880b57cec5SDimitry Andric     return nullptr;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   assert(MBB->isEHFuncletEntry());
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Give catches and cleanups a name based off of their parent function and
1930b57cec5SDimitry Andric   // their funclet entry block's number.
1940b57cec5SDimitry Andric   const MachineFunction *MF = MBB->getParent();
1950b57cec5SDimitry Andric   const Function &F = MF->getFunction();
1960b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
1970b57cec5SDimitry Andric   MCContext &Ctx = MF->getContext();
1980b57cec5SDimitry Andric   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
1990b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
2000b57cec5SDimitry Andric                                Twine(MBB->getNumber()) + "@?0?" +
2010b57cec5SDimitry Andric                                FuncLinkageName + "@4HA");
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric void WinException::beginFunclet(const MachineBasicBlock &MBB,
2050b57cec5SDimitry Andric                                 MCSymbol *Sym) {
2060b57cec5SDimitry Andric   CurrentFuncletEntry = &MBB;
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   const Function &F = Asm->MF->getFunction();
2090b57cec5SDimitry Andric   // If a symbol was not provided for the funclet, invent one.
2100b57cec5SDimitry Andric   if (!Sym) {
2110b57cec5SDimitry Andric     Sym = getMCSymbolForMBB(Asm, &MBB);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     // Describe our funclet symbol as a function with internal linkage.
2140b57cec5SDimitry Andric     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
2150b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
2160b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
2170b57cec5SDimitry Andric                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
2180b57cec5SDimitry Andric     Asm->OutStreamer->EndCOFFSymbolDef();
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric     // We want our funclet's entry point to be aligned such that no nops will be
2210b57cec5SDimitry Andric     // present after the label.
2225ffd83dbSDimitry Andric     Asm->emitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
2230b57cec5SDimitry Andric                        &F);
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric     // Now that we've emitted the alignment directive, point at our funclet.
2265ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(Sym);
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   // Mark 'Sym' as starting our funclet.
2300b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
2310b57cec5SDimitry Andric     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
2320b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
2330b57cec5SDimitry Andric   }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric   if (shouldEmitPersonality) {
2360b57cec5SDimitry Andric     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2370b57cec5SDimitry Andric     const Function *PerFn = nullptr;
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     // Determine which personality routine we are using for this funclet.
2400b57cec5SDimitry Andric     if (F.hasPersonalityFn())
2410b57cec5SDimitry Andric       PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2420b57cec5SDimitry Andric     const MCSymbol *PersHandlerSym =
2430b57cec5SDimitry Andric         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric     // Do not emit a .seh_handler directives for cleanup funclets.
2460b57cec5SDimitry Andric     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
2470b57cec5SDimitry Andric     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
2480b57cec5SDimitry Andric     // inliner doesn't allow inlining them, this isn't a major problem in
2490b57cec5SDimitry Andric     // practice.
2500b57cec5SDimitry Andric     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
2510b57cec5SDimitry Andric       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric void WinException::endFunclet() {
2560b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
2570b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality)) {
2580b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
2590b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric   endFuncletImpl();
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric void WinException::endFuncletImpl() {
2650b57cec5SDimitry Andric   // No funclet to process?  Great, we have nothing to do.
2660b57cec5SDimitry Andric   if (!CurrentFuncletEntry)
2670b57cec5SDimitry Andric     return;
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric   const MachineFunction *MF = Asm->MF;
2700b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
2710b57cec5SDimitry Andric     const Function &F = MF->getFunction();
2720b57cec5SDimitry Andric     EHPersonality Per = EHPersonality::Unknown;
2730b57cec5SDimitry Andric     if (F.hasPersonalityFn())
2740b57cec5SDimitry Andric       Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
2750b57cec5SDimitry Andric 
276e8d8bef9SDimitry Andric     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
277e8d8bef9SDimitry Andric         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
2780b57cec5SDimitry Andric       // Emit an UNWIND_INFO struct describing the prologue.
2790b57cec5SDimitry Andric       Asm->OutStreamer->EmitWinEHHandlerData();
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric       // If this is a C++ catch funclet (or the parent function),
2820b57cec5SDimitry Andric       // emit a reference to the LSDA for the parent function.
2830b57cec5SDimitry Andric       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
2840b57cec5SDimitry Andric       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
2850b57cec5SDimitry Andric           Twine("$cppxdata$", FuncLinkageName));
2865ffd83dbSDimitry Andric       Asm->OutStreamer->emitValue(create32bitRef(FuncInfoXData), 4);
287e8d8bef9SDimitry Andric     } else if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets() &&
2880b57cec5SDimitry Andric                !CurrentFuncletEntry->isEHFuncletEntry()) {
289e8d8bef9SDimitry Andric       // Emit an UNWIND_INFO struct describing the prologue.
290e8d8bef9SDimitry Andric       Asm->OutStreamer->EmitWinEHHandlerData();
291e8d8bef9SDimitry Andric 
2920b57cec5SDimitry Andric       // If this is the parent function in Win64 SEH, emit the LSDA immediately
2930b57cec5SDimitry Andric       // following .seh_handlerdata.
2940b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
295e8d8bef9SDimitry Andric     } else if (shouldEmitPersonality || shouldEmitLSDA) {
296e8d8bef9SDimitry Andric       // Emit an UNWIND_INFO struct describing the prologue.
297e8d8bef9SDimitry Andric       Asm->OutStreamer->EmitWinEHHandlerData();
298e8d8bef9SDimitry Andric       // In these cases, no further info is written to the .xdata section
299e8d8bef9SDimitry Andric       // right here, but is written by e.g. emitExceptionTable in endFunction()
300e8d8bef9SDimitry Andric       // above.
301e8d8bef9SDimitry Andric     } else {
302e8d8bef9SDimitry Andric       // No need to emit the EH handler data right here if nothing needs
303e8d8bef9SDimitry Andric       // writing to the .xdata section; it will be emitted for all
304e8d8bef9SDimitry Andric       // functions that need it in the end anyway.
3050b57cec5SDimitry Andric     }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     // Switch back to the funclet start .text section now that we are done
3080b57cec5SDimitry Andric     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
3090b57cec5SDimitry Andric     // the function.
3100b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
3110b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIEndProc();
3120b57cec5SDimitry Andric   }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Let's make sure we don't try to end the same funclet twice.
3150b57cec5SDimitry Andric   CurrentFuncletEntry = nullptr;
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
3190b57cec5SDimitry Andric   if (!Value)
3200b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
3210b57cec5SDimitry Andric   return MCSymbolRefExpr::create(Value, useImageRel32
3220b57cec5SDimitry Andric                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
3230b57cec5SDimitry Andric                                             : MCSymbolRefExpr::VK_None,
3240b57cec5SDimitry Andric                                  Asm->OutContext);
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
3280b57cec5SDimitry Andric   if (!GV)
3290b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
3300b57cec5SDimitry Andric   return create32bitRef(Asm->getSymbol(GV));
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric const MCExpr *WinException::getLabel(const MCSymbol *Label) {
3340b57cec5SDimitry Andric   return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
3350b57cec5SDimitry Andric                                  Asm->OutContext);
336*349cc55cSDimitry Andric }
337*349cc55cSDimitry Andric 
338*349cc55cSDimitry Andric const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
339*349cc55cSDimitry Andric   return MCBinaryExpr::createAdd(getLabel(Label),
3400b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3410b57cec5SDimitry Andric                                  Asm->OutContext);
3420b57cec5SDimitry Andric }
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
3450b57cec5SDimitry Andric                                       const MCSymbol *OffsetFrom) {
3460b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
3470b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
3480b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
3490b57cec5SDimitry Andric }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
3520b57cec5SDimitry Andric                                              const MCSymbol *OffsetFrom) {
3530b57cec5SDimitry Andric   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
3540b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3550b57cec5SDimitry Andric                                  Asm->OutContext);
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric int WinException::getFrameIndexOffset(int FrameIndex,
3590b57cec5SDimitry Andric                                       const WinEHFuncInfo &FuncInfo) {
3600b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
3615ffd83dbSDimitry Andric   Register UnusedReg;
3620b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
363e8d8bef9SDimitry Andric     StackOffset Offset =
3640b57cec5SDimitry Andric         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
3650b57cec5SDimitry Andric                                            /*IgnoreSPUpdates*/ true);
3660b57cec5SDimitry Andric     assert(UnusedReg ==
3670b57cec5SDimitry Andric            Asm->MF->getSubtarget()
3680b57cec5SDimitry Andric                .getTargetLowering()
3690b57cec5SDimitry Andric                ->getStackPointerRegisterToSaveRestore());
370e8d8bef9SDimitry Andric     return Offset.getFixed();
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // For 32-bit, offsets should be relative to the end of the EH registration
3740b57cec5SDimitry Andric   // node. For 64-bit, it's relative to SP at the end of the prologue.
3750b57cec5SDimitry Andric   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
376e8d8bef9SDimitry Andric   StackOffset Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
377e8d8bef9SDimitry Andric   Offset += StackOffset::getFixed(FuncInfo.EHRegNodeEndOffset);
378e8d8bef9SDimitry Andric   assert(!Offset.getScalable() &&
379e8d8bef9SDimitry Andric          "Frame offsets with a scalable component are not supported");
380e8d8bef9SDimitry Andric   return Offset.getFixed();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric namespace {
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric /// Top-level state used to represent unwind to caller
3860b57cec5SDimitry Andric const int NullState = -1;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric struct InvokeStateChange {
3890b57cec5SDimitry Andric   /// EH Label immediately after the last invoke in the previous state, or
3900b57cec5SDimitry Andric   /// nullptr if the previous state was the null state.
3910b57cec5SDimitry Andric   const MCSymbol *PreviousEndLabel;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   /// EH label immediately before the first invoke in the new state, or nullptr
3940b57cec5SDimitry Andric   /// if the new state is the null state.
3950b57cec5SDimitry Andric   const MCSymbol *NewStartLabel;
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   /// State of the invoke following NewStartLabel, or NullState to indicate
3980b57cec5SDimitry Andric   /// the presence of calls which may unwind to caller.
3990b57cec5SDimitry Andric   int NewState;
4000b57cec5SDimitry Andric };
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric /// Iterator that reports all the invoke state changes in a range of machine
4030b57cec5SDimitry Andric /// basic blocks.  Changes to the null state are reported whenever a call that
4040b57cec5SDimitry Andric /// may unwind to caller is encountered.  The MBB range is expected to be an
4050b57cec5SDimitry Andric /// entire function or funclet, and the start and end of the range are treated
4060b57cec5SDimitry Andric /// as being in the NullState even if there's not an unwind-to-caller call
4070b57cec5SDimitry Andric /// before the first invoke or after the last one (i.e., the first state change
4080b57cec5SDimitry Andric /// reported is the first change to something other than NullState, and a
4090b57cec5SDimitry Andric /// change back to NullState is always reported at the end of iteration).
4100b57cec5SDimitry Andric class InvokeStateChangeIterator {
4110b57cec5SDimitry Andric   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
4120b57cec5SDimitry Andric                             MachineFunction::const_iterator MFI,
4130b57cec5SDimitry Andric                             MachineFunction::const_iterator MFE,
4140b57cec5SDimitry Andric                             MachineBasicBlock::const_iterator MBBI,
4150b57cec5SDimitry Andric                             int BaseState)
4160b57cec5SDimitry Andric       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
4170b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = nullptr;
4180b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
4190b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
4200b57cec5SDimitry Andric     scan();
4210b57cec5SDimitry Andric   }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric public:
4240b57cec5SDimitry Andric   static iterator_range<InvokeStateChangeIterator>
4250b57cec5SDimitry Andric   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
4260b57cec5SDimitry Andric         MachineFunction::const_iterator End, int BaseState = NullState) {
4270b57cec5SDimitry Andric     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
4280b57cec5SDimitry Andric     // the end of the last block.
4290b57cec5SDimitry Andric     assert(Begin != End);
4300b57cec5SDimitry Andric     auto BlockBegin = Begin->begin();
4310b57cec5SDimitry Andric     auto BlockEnd = std::prev(End)->end();
4320b57cec5SDimitry Andric     return make_range(
4330b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
4340b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   // Iterator methods.
4380b57cec5SDimitry Andric   bool operator==(const InvokeStateChangeIterator &O) const {
4390b57cec5SDimitry Andric     assert(BaseState == O.BaseState);
4400b57cec5SDimitry Andric     // Must be visiting same block.
4410b57cec5SDimitry Andric     if (MFI != O.MFI)
4420b57cec5SDimitry Andric       return false;
4430b57cec5SDimitry Andric     // Must be visiting same isntr.
4440b57cec5SDimitry Andric     if (MBBI != O.MBBI)
4450b57cec5SDimitry Andric       return false;
4460b57cec5SDimitry Andric     // At end of block/instr iteration, we can still have two distinct states:
4470b57cec5SDimitry Andric     // one to report the final EndLabel, and another indicating the end of the
4480b57cec5SDimitry Andric     // state change iteration.  Check for CurrentEndLabel equality to
4490b57cec5SDimitry Andric     // distinguish these.
4500b57cec5SDimitry Andric     return CurrentEndLabel == O.CurrentEndLabel;
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   bool operator!=(const InvokeStateChangeIterator &O) const {
4540b57cec5SDimitry Andric     return !operator==(O);
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric   InvokeStateChange &operator*() { return LastStateChange; }
4570b57cec5SDimitry Andric   InvokeStateChange *operator->() { return &LastStateChange; }
4580b57cec5SDimitry Andric   InvokeStateChangeIterator &operator++() { return scan(); }
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric private:
4610b57cec5SDimitry Andric   InvokeStateChangeIterator &scan();
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   const WinEHFuncInfo &EHInfo;
4640b57cec5SDimitry Andric   const MCSymbol *CurrentEndLabel = nullptr;
4650b57cec5SDimitry Andric   MachineFunction::const_iterator MFI;
4660b57cec5SDimitry Andric   MachineFunction::const_iterator MFE;
4670b57cec5SDimitry Andric   MachineBasicBlock::const_iterator MBBI;
4680b57cec5SDimitry Andric   InvokeStateChange LastStateChange;
4690b57cec5SDimitry Andric   bool VisitingInvoke = false;
4700b57cec5SDimitry Andric   int BaseState;
4710b57cec5SDimitry Andric };
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric } // end anonymous namespace
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
4760b57cec5SDimitry Andric   bool IsNewBlock = false;
4770b57cec5SDimitry Andric   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
4780b57cec5SDimitry Andric     if (IsNewBlock)
4790b57cec5SDimitry Andric       MBBI = MFI->begin();
4800b57cec5SDimitry Andric     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
4810b57cec5SDimitry Andric       const MachineInstr &MI = *MBBI;
4820b57cec5SDimitry Andric       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
4830b57cec5SDimitry Andric           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
4840b57cec5SDimitry Andric         // Indicate a change of state to the null state.  We don't have
4850b57cec5SDimitry Andric         // start/end EH labels handy but the caller won't expect them for
4860b57cec5SDimitry Andric         // null state regions.
4870b57cec5SDimitry Andric         LastStateChange.PreviousEndLabel = CurrentEndLabel;
4880b57cec5SDimitry Andric         LastStateChange.NewStartLabel = nullptr;
4890b57cec5SDimitry Andric         LastStateChange.NewState = BaseState;
4900b57cec5SDimitry Andric         CurrentEndLabel = nullptr;
4910b57cec5SDimitry Andric         // Don't re-visit this instr on the next scan
4920b57cec5SDimitry Andric         ++MBBI;
4930b57cec5SDimitry Andric         return *this;
4940b57cec5SDimitry Andric       }
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric       // All other state changes are at EH labels before/after invokes.
4970b57cec5SDimitry Andric       if (!MI.isEHLabel())
4980b57cec5SDimitry Andric         continue;
4990b57cec5SDimitry Andric       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
5000b57cec5SDimitry Andric       if (Label == CurrentEndLabel) {
5010b57cec5SDimitry Andric         VisitingInvoke = false;
5020b57cec5SDimitry Andric         continue;
5030b57cec5SDimitry Andric       }
5040b57cec5SDimitry Andric       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
5050b57cec5SDimitry Andric       // Ignore EH labels that aren't the ones inserted before an invoke
5060b57cec5SDimitry Andric       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
5070b57cec5SDimitry Andric         continue;
5080b57cec5SDimitry Andric       auto &StateAndEnd = InvokeMapIter->second;
5090b57cec5SDimitry Andric       int NewState = StateAndEnd.first;
5100b57cec5SDimitry Andric       // Keep track of the fact that we're between EH start/end labels so
5110b57cec5SDimitry Andric       // we know not to treat the inoke we'll see as unwinding to caller.
5120b57cec5SDimitry Andric       VisitingInvoke = true;
5130b57cec5SDimitry Andric       if (NewState == LastStateChange.NewState) {
5140b57cec5SDimitry Andric         // The state isn't actually changing here.  Record the new end and
5150b57cec5SDimitry Andric         // keep going.
5160b57cec5SDimitry Andric         CurrentEndLabel = StateAndEnd.second;
5170b57cec5SDimitry Andric         continue;
5180b57cec5SDimitry Andric       }
5190b57cec5SDimitry Andric       // Found a state change to report
5200b57cec5SDimitry Andric       LastStateChange.PreviousEndLabel = CurrentEndLabel;
5210b57cec5SDimitry Andric       LastStateChange.NewStartLabel = Label;
5220b57cec5SDimitry Andric       LastStateChange.NewState = NewState;
5230b57cec5SDimitry Andric       // Start keeping track of the new current end
5240b57cec5SDimitry Andric       CurrentEndLabel = StateAndEnd.second;
5250b57cec5SDimitry Andric       // Don't re-visit this instr on the next scan
5260b57cec5SDimitry Andric       ++MBBI;
5270b57cec5SDimitry Andric       return *this;
5280b57cec5SDimitry Andric     }
5290b57cec5SDimitry Andric   }
5300b57cec5SDimitry Andric   // Iteration hit the end of the block range.
5310b57cec5SDimitry Andric   if (LastStateChange.NewState != BaseState) {
5320b57cec5SDimitry Andric     // Report the end of the last new state
5330b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = CurrentEndLabel;
5340b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
5350b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
5360b57cec5SDimitry Andric     // Leave CurrentEndLabel non-null to distinguish this state from end.
5370b57cec5SDimitry Andric     assert(CurrentEndLabel != nullptr);
5380b57cec5SDimitry Andric     return *this;
5390b57cec5SDimitry Andric   }
5400b57cec5SDimitry Andric   // We've reported all state changes and hit the end state.
5410b57cec5SDimitry Andric   CurrentEndLabel = nullptr;
5420b57cec5SDimitry Andric   return *this;
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric /// Emit the language-specific data that __C_specific_handler expects.  This
5460b57cec5SDimitry Andric /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
5470b57cec5SDimitry Andric /// up after faults with __try, __except, and __finally.  The typeinfo values
5480b57cec5SDimitry Andric /// are not really RTTI data, but pointers to filter functions that return an
5490b57cec5SDimitry Andric /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
5500b57cec5SDimitry Andric /// blocks and other cleanups, the landing pad label is zero, and the filter
5510b57cec5SDimitry Andric /// function is actually a cleanup handler with the same prototype.  A catch-all
5520b57cec5SDimitry Andric /// entry is modeled with a null filter function field and a non-zero landing
5530b57cec5SDimitry Andric /// pad label.
5540b57cec5SDimitry Andric ///
5550b57cec5SDimitry Andric /// Possible filter function return values:
5560b57cec5SDimitry Andric ///   EXCEPTION_EXECUTE_HANDLER (1):
5570b57cec5SDimitry Andric ///     Jump to the landing pad label after cleanups.
5580b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_SEARCH (0):
5590b57cec5SDimitry Andric ///     Continue searching this table or continue unwinding.
5600b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_EXECUTION (-1):
5610b57cec5SDimitry Andric ///     Resume execution at the trapping PC.
5620b57cec5SDimitry Andric ///
5630b57cec5SDimitry Andric /// Inferred table structure:
5640b57cec5SDimitry Andric ///   struct Table {
5650b57cec5SDimitry Andric ///     int NumEntries;
5660b57cec5SDimitry Andric ///     struct Entry {
567*349cc55cSDimitry Andric ///       imagerel32 LabelStart;       // Inclusive
568*349cc55cSDimitry Andric ///       imagerel32 LabelEnd;         // Exclusive
5690b57cec5SDimitry Andric ///       imagerel32 FilterOrFinally;  // One means catch-all.
5700b57cec5SDimitry Andric ///       imagerel32 LabelLPad;        // Zero means __finally.
5710b57cec5SDimitry Andric ///     } Entries[NumEntries];
5720b57cec5SDimitry Andric ///   };
5730b57cec5SDimitry Andric void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
5740b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
5750b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
5760b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
5790b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
5800b57cec5SDimitry Andric     if (VerboseAsm)
5810b57cec5SDimitry Andric       OS.AddComment(Comment);
5820b57cec5SDimitry Andric   };
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   if (!isAArch64) {
5850b57cec5SDimitry Andric     // Emit a label assignment with the SEH frame offset so we can use it for
5860b57cec5SDimitry Andric     // llvm.eh.recoverfp.
5870b57cec5SDimitry Andric     StringRef FLinkageName =
5880b57cec5SDimitry Andric         GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
5890b57cec5SDimitry Andric     MCSymbol *ParentFrameOffset =
5900b57cec5SDimitry Andric         Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
5910b57cec5SDimitry Andric     const MCExpr *MCOffset =
5920b57cec5SDimitry Andric         MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
5935ffd83dbSDimitry Andric     Asm->OutStreamer->emitAssignment(ParentFrameOffset, MCOffset);
5940b57cec5SDimitry Andric   }
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // Use the assembler to compute the number of table entries through label
5970b57cec5SDimitry Andric   // difference and division.
5980b57cec5SDimitry Andric   MCSymbol *TableBegin =
5990b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
6000b57cec5SDimitry Andric   MCSymbol *TableEnd =
6010b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
6020b57cec5SDimitry Andric   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
6030b57cec5SDimitry Andric   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
6040b57cec5SDimitry Andric   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
6050b57cec5SDimitry Andric   AddComment("Number of call sites");
6065ffd83dbSDimitry Andric   OS.emitValue(EntryCount, 4);
6070b57cec5SDimitry Andric 
6085ffd83dbSDimitry Andric   OS.emitLabel(TableBegin);
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
6110b57cec5SDimitry Andric   // models exceptions from invokes. LLVM also allows arbitrary reordering of
6120b57cec5SDimitry Andric   // the code, so our tables end up looking a bit different. Rather than
6130b57cec5SDimitry Andric   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
6140b57cec5SDimitry Andric   // each range of invokes in the same state, we emit table entries for all
6150b57cec5SDimitry Andric   // the actions that would be taken in that state. This means our tables are
6160b57cec5SDimitry Andric   // slightly bigger, which is OK.
6170b57cec5SDimitry Andric   const MCSymbol *LastStartLabel = nullptr;
6180b57cec5SDimitry Andric   int LastEHState = -1;
6190b57cec5SDimitry Andric   // Break out before we enter into a finally funclet.
6200b57cec5SDimitry Andric   // FIXME: We need to emit separate EH tables for cleanups.
6210b57cec5SDimitry Andric   MachineFunction::const_iterator End = MF->end();
6220b57cec5SDimitry Andric   MachineFunction::const_iterator Stop = std::next(MF->begin());
6230b57cec5SDimitry Andric   while (Stop != End && !Stop->isEHFuncletEntry())
6240b57cec5SDimitry Andric     ++Stop;
6250b57cec5SDimitry Andric   for (const auto &StateChange :
6260b57cec5SDimitry Andric        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
6270b57cec5SDimitry Andric     // Emit all the actions for the state we just transitioned out of
6280b57cec5SDimitry Andric     // if it was not the null state
6290b57cec5SDimitry Andric     if (LastEHState != -1)
6300b57cec5SDimitry Andric       emitSEHActionsForRange(FuncInfo, LastStartLabel,
6310b57cec5SDimitry Andric                              StateChange.PreviousEndLabel, LastEHState);
6320b57cec5SDimitry Andric     LastStartLabel = StateChange.NewStartLabel;
6330b57cec5SDimitry Andric     LastEHState = StateChange.NewState;
6340b57cec5SDimitry Andric   }
6350b57cec5SDimitry Andric 
6365ffd83dbSDimitry Andric   OS.emitLabel(TableEnd);
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
6400b57cec5SDimitry Andric                                           const MCSymbol *BeginLabel,
6410b57cec5SDimitry Andric                                           const MCSymbol *EndLabel, int State) {
6420b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
6430b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
6440b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
6450b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
6460b57cec5SDimitry Andric     if (VerboseAsm)
6470b57cec5SDimitry Andric       OS.AddComment(Comment);
6480b57cec5SDimitry Andric   };
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   assert(BeginLabel && EndLabel);
6510b57cec5SDimitry Andric   while (State != -1) {
6520b57cec5SDimitry Andric     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
6530b57cec5SDimitry Andric     const MCExpr *FilterOrFinally;
6540b57cec5SDimitry Andric     const MCExpr *ExceptOrNull;
6550b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
6560b57cec5SDimitry Andric     if (UME.IsFinally) {
6570b57cec5SDimitry Andric       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
6580b57cec5SDimitry Andric       ExceptOrNull = MCConstantExpr::create(0, Ctx);
6590b57cec5SDimitry Andric     } else {
6600b57cec5SDimitry Andric       // For an except, the filter can be 1 (catch-all) or a function
6610b57cec5SDimitry Andric       // label.
6620b57cec5SDimitry Andric       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
6630b57cec5SDimitry Andric                                    : MCConstantExpr::create(1, Ctx);
6640b57cec5SDimitry Andric       ExceptOrNull = create32bitRef(Handler->getSymbol());
6650b57cec5SDimitry Andric     }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric     AddComment("LabelStart");
6685ffd83dbSDimitry Andric     OS.emitValue(getLabel(BeginLabel), 4);
6690b57cec5SDimitry Andric     AddComment("LabelEnd");
670*349cc55cSDimitry Andric     OS.emitValue(getLabelPlusOne(EndLabel), 4);
6710b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
6720b57cec5SDimitry Andric                                                              : "CatchAll");
6735ffd83dbSDimitry Andric     OS.emitValue(FilterOrFinally, 4);
6740b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
6755ffd83dbSDimitry Andric     OS.emitValue(ExceptOrNull, 4);
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric     assert(UME.ToState < State && "states should decrease");
6780b57cec5SDimitry Andric     State = UME.ToState;
6790b57cec5SDimitry Andric   }
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
6830b57cec5SDimitry Andric   const Function &F = MF->getFunction();
6840b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
6850b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
6900b57cec5SDimitry Andric   MCSymbol *FuncInfoXData = nullptr;
6910b57cec5SDimitry Andric   if (shouldEmitPersonality) {
6920b57cec5SDimitry Andric     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
6930b57cec5SDimitry Andric     // IPs to state numbers.
6940b57cec5SDimitry Andric     FuncInfoXData =
6950b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
6960b57cec5SDimitry Andric     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
6970b57cec5SDimitry Andric   } else {
6980b57cec5SDimitry Andric     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
6990b57cec5SDimitry Andric   }
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   int UnwindHelpOffset = 0;
7020b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI())
7030b57cec5SDimitry Andric     UnwindHelpOffset =
7040b57cec5SDimitry Andric         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   MCSymbol *UnwindMapXData = nullptr;
7070b57cec5SDimitry Andric   MCSymbol *TryBlockMapXData = nullptr;
7080b57cec5SDimitry Andric   MCSymbol *IPToStateXData = nullptr;
7090b57cec5SDimitry Andric   if (!FuncInfo.CxxUnwindMap.empty())
7100b57cec5SDimitry Andric     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
7110b57cec5SDimitry Andric         Twine("$stateUnwindMap$", FuncLinkageName));
7120b57cec5SDimitry Andric   if (!FuncInfo.TryBlockMap.empty())
7130b57cec5SDimitry Andric     TryBlockMapXData =
7140b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
7150b57cec5SDimitry Andric   if (!IPToStateTable.empty())
7160b57cec5SDimitry Andric     IPToStateXData =
7170b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
7200b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
7210b57cec5SDimitry Andric     if (VerboseAsm)
7220b57cec5SDimitry Andric       OS.AddComment(Comment);
7230b57cec5SDimitry Andric   };
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   // FuncInfo {
7260b57cec5SDimitry Andric   //   uint32_t           MagicNumber
7270b57cec5SDimitry Andric   //   int32_t            MaxState;
7280b57cec5SDimitry Andric   //   UnwindMapEntry    *UnwindMap;
7290b57cec5SDimitry Andric   //   uint32_t           NumTryBlocks;
7300b57cec5SDimitry Andric   //   TryBlockMapEntry  *TryBlockMap;
7310b57cec5SDimitry Andric   //   uint32_t           IPMapEntries; // always 0 for x86
7320b57cec5SDimitry Andric   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
7330b57cec5SDimitry Andric   //   uint32_t           UnwindHelp;   // non-x86 only
7340b57cec5SDimitry Andric   //   ESTypeList        *ESTypeList;
7350b57cec5SDimitry Andric   //   int32_t            EHFlags;
7360b57cec5SDimitry Andric   // }
7370b57cec5SDimitry Andric   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
7380b57cec5SDimitry Andric   // EHFlags & 2 -> ???
7390b57cec5SDimitry Andric   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
7405ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
7415ffd83dbSDimitry Andric   OS.emitLabel(FuncInfoXData);
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   AddComment("MagicNumber");
7445ffd83dbSDimitry Andric   OS.emitInt32(0x19930522);
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   AddComment("MaxState");
7475ffd83dbSDimitry Andric   OS.emitInt32(FuncInfo.CxxUnwindMap.size());
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   AddComment("UnwindMap");
7505ffd83dbSDimitry Andric   OS.emitValue(create32bitRef(UnwindMapXData), 4);
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric   AddComment("NumTryBlocks");
7535ffd83dbSDimitry Andric   OS.emitInt32(FuncInfo.TryBlockMap.size());
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   AddComment("TryBlockMap");
7565ffd83dbSDimitry Andric   OS.emitValue(create32bitRef(TryBlockMapXData), 4);
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   AddComment("IPMapEntries");
7595ffd83dbSDimitry Andric   OS.emitInt32(IPToStateTable.size());
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   AddComment("IPToStateXData");
7625ffd83dbSDimitry Andric   OS.emitValue(create32bitRef(IPToStateXData), 4);
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
7650b57cec5SDimitry Andric     AddComment("UnwindHelp");
7665ffd83dbSDimitry Andric     OS.emitInt32(UnwindHelpOffset);
7670b57cec5SDimitry Andric   }
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   AddComment("ESTypeList");
7705ffd83dbSDimitry Andric   OS.emitInt32(0);
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   AddComment("EHFlags");
7735ffd83dbSDimitry Andric   OS.emitInt32(1);
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // UnwindMapEntry {
7760b57cec5SDimitry Andric   //   int32_t ToState;
7770b57cec5SDimitry Andric   //   void  (*Action)();
7780b57cec5SDimitry Andric   // };
7790b57cec5SDimitry Andric   if (UnwindMapXData) {
7805ffd83dbSDimitry Andric     OS.emitLabel(UnwindMapXData);
7810b57cec5SDimitry Andric     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
7820b57cec5SDimitry Andric       MCSymbol *CleanupSym =
7830b57cec5SDimitry Andric           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
7840b57cec5SDimitry Andric       AddComment("ToState");
7855ffd83dbSDimitry Andric       OS.emitInt32(UME.ToState);
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric       AddComment("Action");
7885ffd83dbSDimitry Andric       OS.emitValue(create32bitRef(CleanupSym), 4);
7890b57cec5SDimitry Andric     }
7900b57cec5SDimitry Andric   }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   // TryBlockMap {
7930b57cec5SDimitry Andric   //   int32_t      TryLow;
7940b57cec5SDimitry Andric   //   int32_t      TryHigh;
7950b57cec5SDimitry Andric   //   int32_t      CatchHigh;
7960b57cec5SDimitry Andric   //   int32_t      NumCatches;
7970b57cec5SDimitry Andric   //   HandlerType *HandlerArray;
7980b57cec5SDimitry Andric   // };
7990b57cec5SDimitry Andric   if (TryBlockMapXData) {
8005ffd83dbSDimitry Andric     OS.emitLabel(TryBlockMapXData);
8010b57cec5SDimitry Andric     SmallVector<MCSymbol *, 1> HandlerMaps;
8020b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
8030b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = nullptr;
8060b57cec5SDimitry Andric       if (!TBME.HandlerArray.empty())
8070b57cec5SDimitry Andric         HandlerMapXData =
8080b57cec5SDimitry Andric             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
8090b57cec5SDimitry Andric                                                   .concat(Twine(I))
8100b57cec5SDimitry Andric                                                   .concat("$")
8110b57cec5SDimitry Andric                                                   .concat(FuncLinkageName));
8120b57cec5SDimitry Andric       HandlerMaps.push_back(HandlerMapXData);
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric       // TBMEs should form intervals.
8150b57cec5SDimitry Andric       assert(0 <= TBME.TryLow && "bad trymap interval");
8160b57cec5SDimitry Andric       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
8170b57cec5SDimitry Andric       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
8180b57cec5SDimitry Andric       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
8190b57cec5SDimitry Andric              "bad trymap interval");
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric       AddComment("TryLow");
8225ffd83dbSDimitry Andric       OS.emitInt32(TBME.TryLow);
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric       AddComment("TryHigh");
8255ffd83dbSDimitry Andric       OS.emitInt32(TBME.TryHigh);
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric       AddComment("CatchHigh");
8285ffd83dbSDimitry Andric       OS.emitInt32(TBME.CatchHigh);
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric       AddComment("NumCatches");
8315ffd83dbSDimitry Andric       OS.emitInt32(TBME.HandlerArray.size());
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric       AddComment("HandlerArray");
8345ffd83dbSDimitry Andric       OS.emitValue(create32bitRef(HandlerMapXData), 4);
8350b57cec5SDimitry Andric     }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric     // All funclets use the same parent frame offset currently.
8380b57cec5SDimitry Andric     unsigned ParentFrameOffset = 0;
8390b57cec5SDimitry Andric     if (shouldEmitPersonality) {
8400b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
8410b57cec5SDimitry Andric       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
8420b57cec5SDimitry Andric     }
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
8450b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
8460b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = HandlerMaps[I];
8470b57cec5SDimitry Andric       if (!HandlerMapXData)
8480b57cec5SDimitry Andric         continue;
8490b57cec5SDimitry Andric       // HandlerType {
8500b57cec5SDimitry Andric       //   int32_t         Adjectives;
8510b57cec5SDimitry Andric       //   TypeDescriptor *Type;
8520b57cec5SDimitry Andric       //   int32_t         CatchObjOffset;
8530b57cec5SDimitry Andric       //   void          (*Handler)();
8540b57cec5SDimitry Andric       //   int32_t         ParentFrameOffset; // x64 and AArch64 only
8550b57cec5SDimitry Andric       // };
8565ffd83dbSDimitry Andric       OS.emitLabel(HandlerMapXData);
8570b57cec5SDimitry Andric       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
8580b57cec5SDimitry Andric         // Get the frame escape label with the offset of the catch object. If
8590b57cec5SDimitry Andric         // the index is INT_MAX, then there is no catch object, and we should
8600b57cec5SDimitry Andric         // emit an offset of zero, indicating that no copy will occur.
8610b57cec5SDimitry Andric         const MCExpr *FrameAllocOffsetRef = nullptr;
8620b57cec5SDimitry Andric         if (HT.CatchObj.FrameIndex != INT_MAX) {
8630b57cec5SDimitry Andric           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
8640b57cec5SDimitry Andric           assert(Offset != 0 && "Illegal offset for catch object!");
8650b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
8660b57cec5SDimitry Andric         } else {
8670b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
8680b57cec5SDimitry Andric         }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric         MCSymbol *HandlerSym =
8710b57cec5SDimitry Andric             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric         AddComment("Adjectives");
8745ffd83dbSDimitry Andric         OS.emitInt32(HT.Adjectives);
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric         AddComment("Type");
8775ffd83dbSDimitry Andric         OS.emitValue(create32bitRef(HT.TypeDescriptor), 4);
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric         AddComment("CatchObjOffset");
8805ffd83dbSDimitry Andric         OS.emitValue(FrameAllocOffsetRef, 4);
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric         AddComment("Handler");
8835ffd83dbSDimitry Andric         OS.emitValue(create32bitRef(HandlerSym), 4);
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric         if (shouldEmitPersonality) {
8860b57cec5SDimitry Andric           AddComment("ParentFrameOffset");
8875ffd83dbSDimitry Andric           OS.emitInt32(ParentFrameOffset);
8880b57cec5SDimitry Andric         }
8890b57cec5SDimitry Andric       }
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric   }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // IPToStateMapEntry {
8940b57cec5SDimitry Andric   //   void   *IP;
8950b57cec5SDimitry Andric   //   int32_t State;
8960b57cec5SDimitry Andric   // };
8970b57cec5SDimitry Andric   if (IPToStateXData) {
8985ffd83dbSDimitry Andric     OS.emitLabel(IPToStateXData);
8990b57cec5SDimitry Andric     for (auto &IPStatePair : IPToStateTable) {
9000b57cec5SDimitry Andric       AddComment("IP");
9015ffd83dbSDimitry Andric       OS.emitValue(IPStatePair.first, 4);
9020b57cec5SDimitry Andric       AddComment("ToState");
9035ffd83dbSDimitry Andric       OS.emitInt32(IPStatePair.second);
9040b57cec5SDimitry Andric     }
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric void WinException::computeIP2StateTable(
9090b57cec5SDimitry Andric     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
9100b57cec5SDimitry Andric     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
9130b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
9140b57cec5SDimitry Andric                                        End = MF->end();
9150b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
9160b57cec5SDimitry Andric     // Find the end of the funclet
9170b57cec5SDimitry Andric     while (++FuncletEnd != End) {
9180b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
9190b57cec5SDimitry Andric         break;
9200b57cec5SDimitry Andric       }
9210b57cec5SDimitry Andric     }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     // Don't emit ip2state entries for cleanup funclets. Any interesting
9240b57cec5SDimitry Andric     // exceptional actions in cleanups must be handled in a separate IR
9250b57cec5SDimitry Andric     // function.
9260b57cec5SDimitry Andric     if (FuncletStart->isCleanupFuncletEntry())
9270b57cec5SDimitry Andric       continue;
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric     MCSymbol *StartLabel;
9300b57cec5SDimitry Andric     int BaseState;
9310b57cec5SDimitry Andric     if (FuncletStart == MF->begin()) {
9320b57cec5SDimitry Andric       BaseState = NullState;
9330b57cec5SDimitry Andric       StartLabel = Asm->getFunctionBegin();
9340b57cec5SDimitry Andric     } else {
9350b57cec5SDimitry Andric       auto *FuncletPad =
9360b57cec5SDimitry Andric           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
9370b57cec5SDimitry Andric       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
9380b57cec5SDimitry Andric       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
9390b57cec5SDimitry Andric       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
9400b57cec5SDimitry Andric     }
9410b57cec5SDimitry Andric     assert(StartLabel && "need local function start label");
9420b57cec5SDimitry Andric     IPToStateTable.push_back(
9430b57cec5SDimitry Andric         std::make_pair(create32bitRef(StartLabel), BaseState));
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric     for (const auto &StateChange : InvokeStateChangeIterator::range(
9460b57cec5SDimitry Andric              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
9470b57cec5SDimitry Andric       // Compute the label to report as the start of this entry; use the EH
9480b57cec5SDimitry Andric       // start label for the invoke if we have one, otherwise (this is a call
9490b57cec5SDimitry Andric       // which may unwind to our caller and does not have an EH start label, so)
9500b57cec5SDimitry Andric       // use the previous end label.
9510b57cec5SDimitry Andric       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
9520b57cec5SDimitry Andric       if (!ChangeLabel)
9530b57cec5SDimitry Andric         ChangeLabel = StateChange.PreviousEndLabel;
9540b57cec5SDimitry Andric       // Emit an entry indicating that PCs after 'Label' have this EH state.
955*349cc55cSDimitry Andric       // NOTE: On ARM architectures, the StateFromIp automatically takes into
956*349cc55cSDimitry Andric       // account that the return address is after the call instruction (whose EH
957*349cc55cSDimitry Andric       // state we should be using), but on other platforms we need to +1 to the
958*349cc55cSDimitry Andric       // label so that we are using the correct EH state.
959*349cc55cSDimitry Andric       const MCExpr *LabelExpression = (isAArch64 || isThumb)
960*349cc55cSDimitry Andric                                           ? getLabel(ChangeLabel)
961*349cc55cSDimitry Andric                                           : getLabelPlusOne(ChangeLabel);
9620b57cec5SDimitry Andric       IPToStateTable.push_back(
963*349cc55cSDimitry Andric           std::make_pair(LabelExpression, StateChange.NewState));
9640b57cec5SDimitry Andric       // FIXME: assert that NewState is between CatchLow and CatchHigh.
9650b57cec5SDimitry Andric     }
9660b57cec5SDimitry Andric   }
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
9700b57cec5SDimitry Andric                                                  StringRef FLinkageName) {
9710b57cec5SDimitry Andric   // Outlined helpers called by the EH runtime need to know the offset of the EH
9720b57cec5SDimitry Andric   // registration in order to recover the parent frame pointer. Now that we know
9730b57cec5SDimitry Andric   // we've code generated the parent, we can emit the label assignment that
9740b57cec5SDimitry Andric   // those helpers use to get the offset of the registration node.
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
9770b57cec5SDimitry Andric   // after optimization all the invokes were eliminated. We still need to emit
9780b57cec5SDimitry Andric   // the parent frame offset label, but it should be garbage and should never be
9790b57cec5SDimitry Andric   // used.
9800b57cec5SDimitry Andric   int64_t Offset = 0;
9810b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
9820b57cec5SDimitry Andric   if (FI != INT_MAX) {
9830b57cec5SDimitry Andric     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
984e8d8bef9SDimitry Andric     Offset = TFI->getNonLocalFrameIndexReference(*Asm->MF, FI).getFixed();
9850b57cec5SDimitry Andric   }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
9880b57cec5SDimitry Andric   MCSymbol *ParentFrameOffset =
9890b57cec5SDimitry Andric       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
9905ffd83dbSDimitry Andric   Asm->OutStreamer->emitAssignment(ParentFrameOffset,
9910b57cec5SDimitry Andric                                    MCConstantExpr::create(Offset, Ctx));
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric /// Emit the language-specific data that _except_handler3 and 4 expect. This is
9950b57cec5SDimitry Andric /// functionally equivalent to the __C_specific_handler table, except it is
9960b57cec5SDimitry Andric /// indexed by state number instead of IP.
9970b57cec5SDimitry Andric void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
9980b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
9990b57cec5SDimitry Andric   const Function &F = MF->getFunction();
10000b57cec5SDimitry Andric   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
10030b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
10040b57cec5SDimitry Andric     if (VerboseAsm)
10050b57cec5SDimitry Andric       OS.AddComment(Comment);
10060b57cec5SDimitry Andric   };
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
10090b57cec5SDimitry Andric   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
10120b57cec5SDimitry Andric   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
10135ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
10145ffd83dbSDimitry Andric   OS.emitLabel(LSDALabel);
10150b57cec5SDimitry Andric 
10168bcb0991SDimitry Andric   const auto *Per = cast<Function>(F.getPersonalityFn()->stripPointerCasts());
10170b57cec5SDimitry Andric   StringRef PerName = Per->getName();
10180b57cec5SDimitry Andric   int BaseState = -1;
10190b57cec5SDimitry Andric   if (PerName == "_except_handler4") {
10200b57cec5SDimitry Andric     // The LSDA for _except_handler4 starts with this struct, followed by the
10210b57cec5SDimitry Andric     // scope table:
10220b57cec5SDimitry Andric     //
10230b57cec5SDimitry Andric     // struct EH4ScopeTable {
10240b57cec5SDimitry Andric     //   int32_t GSCookieOffset;
10250b57cec5SDimitry Andric     //   int32_t GSCookieXOROffset;
10260b57cec5SDimitry Andric     //   int32_t EHCookieOffset;
10270b57cec5SDimitry Andric     //   int32_t EHCookieXOROffset;
10280b57cec5SDimitry Andric     //   ScopeTableEntry ScopeRecord[];
10290b57cec5SDimitry Andric     // };
10300b57cec5SDimitry Andric     //
10310b57cec5SDimitry Andric     // Offsets are %ebp relative.
10320b57cec5SDimitry Andric     //
10330b57cec5SDimitry Andric     // The GS cookie is present only if the function needs stack protection.
10340b57cec5SDimitry Andric     // GSCookieOffset = -2 means that GS cookie is not used.
10350b57cec5SDimitry Andric     //
10360b57cec5SDimitry Andric     // The EH cookie is always present.
10370b57cec5SDimitry Andric     //
10380b57cec5SDimitry Andric     // Check is done the following way:
10390b57cec5SDimitry Andric     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric     // Retrieve the Guard Stack slot.
10420b57cec5SDimitry Andric     int GSCookieOffset = -2;
10430b57cec5SDimitry Andric     const MachineFrameInfo &MFI = MF->getFrameInfo();
10440b57cec5SDimitry Andric     if (MFI.hasStackProtectorIndex()) {
10455ffd83dbSDimitry Andric       Register UnusedReg;
10460b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
10470b57cec5SDimitry Andric       int SSPIdx = MFI.getStackProtectorIndex();
1048e8d8bef9SDimitry Andric       GSCookieOffset =
1049e8d8bef9SDimitry Andric           TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg).getFixed();
10500b57cec5SDimitry Andric     }
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric     // Retrieve the EH Guard slot.
10530b57cec5SDimitry Andric     // TODO(etienneb): Get rid of this value and change it for and assertion.
10540b57cec5SDimitry Andric     int EHCookieOffset = 9999;
10550b57cec5SDimitry Andric     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
10565ffd83dbSDimitry Andric       Register UnusedReg;
10570b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
10580b57cec5SDimitry Andric       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1059e8d8bef9SDimitry Andric       EHCookieOffset =
1060e8d8bef9SDimitry Andric           TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg).getFixed();
10610b57cec5SDimitry Andric     }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric     AddComment("GSCookieOffset");
10645ffd83dbSDimitry Andric     OS.emitInt32(GSCookieOffset);
10650b57cec5SDimitry Andric     AddComment("GSCookieXOROffset");
10665ffd83dbSDimitry Andric     OS.emitInt32(0);
10670b57cec5SDimitry Andric     AddComment("EHCookieOffset");
10685ffd83dbSDimitry Andric     OS.emitInt32(EHCookieOffset);
10690b57cec5SDimitry Andric     AddComment("EHCookieXOROffset");
10705ffd83dbSDimitry Andric     OS.emitInt32(0);
10710b57cec5SDimitry Andric     BaseState = -2;
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   assert(!FuncInfo.SEHUnwindMap.empty());
10750b57cec5SDimitry Andric   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
10760b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
10770b57cec5SDimitry Andric     const MCSymbol *ExceptOrFinally =
10780b57cec5SDimitry Andric         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
10790b57cec5SDimitry Andric     // -1 is usually the base state for "unwind to caller", but for
10800b57cec5SDimitry Andric     // _except_handler4 it's -2. Do that replacement here if necessary.
10810b57cec5SDimitry Andric     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
10820b57cec5SDimitry Andric     AddComment("ToState");
10835ffd83dbSDimitry Andric     OS.emitInt32(ToState);
10840b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
10855ffd83dbSDimitry Andric     OS.emitValue(create32bitRef(UME.Filter), 4);
10860b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
10875ffd83dbSDimitry Andric     OS.emitValue(create32bitRef(ExceptOrFinally), 4);
10880b57cec5SDimitry Andric   }
10890b57cec5SDimitry Andric }
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
10920b57cec5SDimitry Andric   int Rank = 0;
10930b57cec5SDimitry Andric   while (State != -1) {
10940b57cec5SDimitry Andric     ++Rank;
10950b57cec5SDimitry Andric     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
10960b57cec5SDimitry Andric   }
10970b57cec5SDimitry Andric   return Rank;
10980b57cec5SDimitry Andric }
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
11010b57cec5SDimitry Andric   int LeftRank = getTryRank(FuncInfo, Left);
11020b57cec5SDimitry Andric   int RightRank = getTryRank(FuncInfo, Right);
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric   while (LeftRank < RightRank) {
11050b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
11060b57cec5SDimitry Andric     --RightRank;
11070b57cec5SDimitry Andric   }
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   while (RightRank < LeftRank) {
11100b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
11110b57cec5SDimitry Andric     --LeftRank;
11120b57cec5SDimitry Andric   }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric   while (Left != Right) {
11150b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
11160b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
11170b57cec5SDimitry Andric   }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   return Left;
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
11230b57cec5SDimitry Andric   // CLR EH "states" are really just IDs that identify handlers/funclets;
11240b57cec5SDimitry Andric   // states, handlers, and funclets all have 1:1 mappings between them, and a
11250b57cec5SDimitry Andric   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
11260b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
11270b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
11280b57cec5SDimitry Andric   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
11290b57cec5SDimitry Andric   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric   // A ClrClause describes a protected region.
11320b57cec5SDimitry Andric   struct ClrClause {
11330b57cec5SDimitry Andric     const MCSymbol *StartLabel; // Start of protected region
11340b57cec5SDimitry Andric     const MCSymbol *EndLabel;   // End of protected region
11350b57cec5SDimitry Andric     int State;          // Index of handler protecting the protected region
11360b57cec5SDimitry Andric     int EnclosingState; // Index of funclet enclosing the protected region
11370b57cec5SDimitry Andric   };
11380b57cec5SDimitry Andric   SmallVector<ClrClause, 8> Clauses;
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric   // Build a map from handler MBBs to their corresponding states (i.e. their
11410b57cec5SDimitry Andric   // indices in the ClrEHUnwindMap).
11420b57cec5SDimitry Andric   int NumStates = FuncInfo.ClrEHUnwindMap.size();
11430b57cec5SDimitry Andric   assert(NumStates > 0 && "Don't need exception table!");
11440b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, int> HandlerStates;
11450b57cec5SDimitry Andric   for (int State = 0; State < NumStates; ++State) {
11460b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock =
11470b57cec5SDimitry Andric         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
11480b57cec5SDimitry Andric     HandlerStates[HandlerBlock] = State;
11490b57cec5SDimitry Andric     // Use this loop through all handlers to verify our assumption (used in
11500b57cec5SDimitry Andric     // the MinEnclosingState computation) that enclosing funclets have lower
11510b57cec5SDimitry Andric     // state numbers than their enclosed funclets.
11520b57cec5SDimitry Andric     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
11530b57cec5SDimitry Andric            "ill-formed state numbering");
11540b57cec5SDimitry Andric   }
11550b57cec5SDimitry Andric   // Map the main function to the NullState.
11560b57cec5SDimitry Andric   HandlerStates[&MF->front()] = NullState;
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric   // Write out a sentinel indicating the end of the standard (Windows) xdata
11590b57cec5SDimitry Andric   // and the start of the additional (CLR) info.
11605ffd83dbSDimitry Andric   OS.emitInt32(0xffffffff);
11610b57cec5SDimitry Andric   // Write out the number of funclets
11625ffd83dbSDimitry Andric   OS.emitInt32(NumStates);
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // Walk the machine blocks/instrs, computing and emitting a few things:
11650b57cec5SDimitry Andric   // 1. Emit a list of the offsets to each handler entry, in lexical order.
11660b57cec5SDimitry Andric   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
11670b57cec5SDimitry Andric   // 3. Compute the list of ClrClauses, in the required order (inner before
11680b57cec5SDimitry Andric   //    outer, earlier before later; the order by which a forward scan with
11690b57cec5SDimitry Andric   //    early termination will find the innermost enclosing clause covering
11700b57cec5SDimitry Andric   //    a given address).
11710b57cec5SDimitry Andric   // 4. A map (MinClauseMap) from each handler index to the index of the
11720b57cec5SDimitry Andric   //    outermost funclet/function which contains a try clause targeting the
11730b57cec5SDimitry Andric   //    key handler.  This will be used to determine IsDuplicate-ness when
11740b57cec5SDimitry Andric   //    emitting ClrClauses.  The NullState value is used to indicate that the
11750b57cec5SDimitry Andric   //    top-level function contains a try clause targeting the key handler.
11760b57cec5SDimitry Andric   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
11770b57cec5SDimitry Andric   // try regions we entered before entering the PendingState try but which
11780b57cec5SDimitry Andric   // we haven't yet exited.
11790b57cec5SDimitry Andric   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
11800b57cec5SDimitry Andric   // EndSymbolMap and MinClauseMap are maps described above.
11810b57cec5SDimitry Andric   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
11820b57cec5SDimitry Andric   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric   // Visit the root function and each funclet.
11850b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
11860b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
11870b57cec5SDimitry Andric                                        End = MF->end();
11880b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
11890b57cec5SDimitry Andric     int FuncletState = HandlerStates[&*FuncletStart];
11900b57cec5SDimitry Andric     // Find the end of the funclet
11910b57cec5SDimitry Andric     MCSymbol *EndSymbol = FuncEndSym;
11920b57cec5SDimitry Andric     while (++FuncletEnd != End) {
11930b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
11940b57cec5SDimitry Andric         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
11950b57cec5SDimitry Andric         break;
11960b57cec5SDimitry Andric       }
11970b57cec5SDimitry Andric     }
11980b57cec5SDimitry Andric     // Emit the function/funclet end and, if this is a funclet (and not the
11990b57cec5SDimitry Andric     // root function), record it in the EndSymbolMap.
12005ffd83dbSDimitry Andric     OS.emitValue(getOffset(EndSymbol, FuncBeginSym), 4);
12010b57cec5SDimitry Andric     if (FuncletState != NullState) {
12020b57cec5SDimitry Andric       // Record the end of the handler.
12030b57cec5SDimitry Andric       EndSymbolMap[FuncletState] = EndSymbol;
12040b57cec5SDimitry Andric     }
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric     // Walk the state changes in this function/funclet and compute its clauses.
12070b57cec5SDimitry Andric     // Funclets always start in the null state.
12080b57cec5SDimitry Andric     const MCSymbol *CurrentStartLabel = nullptr;
12090b57cec5SDimitry Andric     int CurrentState = NullState;
12100b57cec5SDimitry Andric     assert(HandlerStack.empty());
12110b57cec5SDimitry Andric     for (const auto &StateChange :
12120b57cec5SDimitry Andric          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
12130b57cec5SDimitry Andric       // Close any try regions we're not still under
12140b57cec5SDimitry Andric       int StillPendingState =
12150b57cec5SDimitry Andric           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
12160b57cec5SDimitry Andric       while (CurrentState != StillPendingState) {
12170b57cec5SDimitry Andric         assert(CurrentState != NullState &&
12180b57cec5SDimitry Andric                "Failed to find still-pending state!");
12190b57cec5SDimitry Andric         // Close the pending clause
12200b57cec5SDimitry Andric         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
12210b57cec5SDimitry Andric                            CurrentState, FuncletState});
12220b57cec5SDimitry Andric         // Now the next-outer try region is current
12230b57cec5SDimitry Andric         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
12240b57cec5SDimitry Andric         // Pop the new start label from the handler stack if we've exited all
12250b57cec5SDimitry Andric         // inner try regions of the corresponding try region.
12260b57cec5SDimitry Andric         if (HandlerStack.back().second == CurrentState)
12270b57cec5SDimitry Andric           CurrentStartLabel = HandlerStack.pop_back_val().first;
12280b57cec5SDimitry Andric       }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric       if (StateChange.NewState != CurrentState) {
12310b57cec5SDimitry Andric         // For each clause we're starting, update the MinClauseMap so we can
12320b57cec5SDimitry Andric         // know which is the topmost funclet containing a clause targeting
12330b57cec5SDimitry Andric         // it.
12340b57cec5SDimitry Andric         for (int EnteredState = StateChange.NewState;
12350b57cec5SDimitry Andric              EnteredState != CurrentState;
12360b57cec5SDimitry Andric              EnteredState =
12370b57cec5SDimitry Andric                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
12380b57cec5SDimitry Andric           int &MinEnclosingState = MinClauseMap[EnteredState];
12390b57cec5SDimitry Andric           if (FuncletState < MinEnclosingState)
12400b57cec5SDimitry Andric             MinEnclosingState = FuncletState;
12410b57cec5SDimitry Andric         }
12420b57cec5SDimitry Andric         // Save the previous current start/label on the stack and update to
12430b57cec5SDimitry Andric         // the newly-current start/state.
12440b57cec5SDimitry Andric         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
12450b57cec5SDimitry Andric         CurrentStartLabel = StateChange.NewStartLabel;
12460b57cec5SDimitry Andric         CurrentState = StateChange.NewState;
12470b57cec5SDimitry Andric       }
12480b57cec5SDimitry Andric     }
12490b57cec5SDimitry Andric     assert(HandlerStack.empty());
12500b57cec5SDimitry Andric   }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   // Now emit the clause info, starting with the number of clauses.
12535ffd83dbSDimitry Andric   OS.emitInt32(Clauses.size());
12540b57cec5SDimitry Andric   for (ClrClause &Clause : Clauses) {
12550b57cec5SDimitry Andric     // Emit a CORINFO_EH_CLAUSE :
12560b57cec5SDimitry Andric     /*
12570b57cec5SDimitry Andric       struct CORINFO_EH_CLAUSE
12580b57cec5SDimitry Andric       {
12590b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
12600b57cec5SDimitry Andric           DWORD                   TryOffset;
12610b57cec5SDimitry Andric           DWORD                   TryLength;     // actually TryEndOffset
12620b57cec5SDimitry Andric           DWORD                   HandlerOffset;
12630b57cec5SDimitry Andric           DWORD                   HandlerLength; // actually HandlerEndOffset
12640b57cec5SDimitry Andric           union
12650b57cec5SDimitry Andric           {
12660b57cec5SDimitry Andric               DWORD               ClassToken;   // use for catch clauses
12670b57cec5SDimitry Andric               DWORD               FilterOffset; // use for filter clauses
12680b57cec5SDimitry Andric           };
12690b57cec5SDimitry Andric       };
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric       enum CORINFO_EH_CLAUSE_FLAGS
12720b57cec5SDimitry Andric       {
12730b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_NONE    = 0,
12740b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
12750b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
12760b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
12770b57cec5SDimitry Andric       };
12780b57cec5SDimitry Andric       typedef enum CorExceptionFlag
12790b57cec5SDimitry Andric       {
12800b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_NONE,
12810b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
12820b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
12830b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
12840b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
12850b57cec5SDimitry Andric                                                       // clause was duplicated
12860b57cec5SDimitry Andric                                                       // to a funclet which was
12870b57cec5SDimitry Andric                                                       // pulled out of line
12880b57cec5SDimitry Andric       } CorExceptionFlag;
12890b57cec5SDimitry Andric     */
12900b57cec5SDimitry Andric     // Add 1 to the start/end of the EH clause; the IP associated with a
12910b57cec5SDimitry Andric     // call when the runtime does its scan is the IP of the next instruction
12920b57cec5SDimitry Andric     // (the one to which control will return after the call), so we need
12930b57cec5SDimitry Andric     // to add 1 to the end of the clause to cover that offset.  We also add
12940b57cec5SDimitry Andric     // 1 to the start of the clause to make sure that the ranges reported
12950b57cec5SDimitry Andric     // for all clauses are disjoint.  Note that we'll need some additional
12960b57cec5SDimitry Andric     // logic when machine traps are supported, since in that case the IP
12970b57cec5SDimitry Andric     // that the runtime uses is the offset of the faulting instruction
12980b57cec5SDimitry Andric     // itself; if such an instruction immediately follows a call but the
12990b57cec5SDimitry Andric     // two belong to different clauses, we'll need to insert a nop between
13000b57cec5SDimitry Andric     // them so the runtime can distinguish the point to which the call will
13010b57cec5SDimitry Andric     // return from the point at which the fault occurs.
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric     const MCExpr *ClauseBegin =
13040b57cec5SDimitry Andric         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
13050b57cec5SDimitry Andric     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
13080b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
13090b57cec5SDimitry Andric     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
13100b57cec5SDimitry Andric     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
13110b57cec5SDimitry Andric     MCSymbol *EndSym = EndSymbolMap[Clause.State];
13120b57cec5SDimitry Andric     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric     uint32_t Flags = 0;
13150b57cec5SDimitry Andric     switch (Entry.HandlerType) {
13160b57cec5SDimitry Andric     case ClrHandlerType::Catch:
13170b57cec5SDimitry Andric       // Leaving bits 0-2 clear indicates catch.
13180b57cec5SDimitry Andric       break;
13190b57cec5SDimitry Andric     case ClrHandlerType::Filter:
13200b57cec5SDimitry Andric       Flags |= 1;
13210b57cec5SDimitry Andric       break;
13220b57cec5SDimitry Andric     case ClrHandlerType::Finally:
13230b57cec5SDimitry Andric       Flags |= 2;
13240b57cec5SDimitry Andric       break;
13250b57cec5SDimitry Andric     case ClrHandlerType::Fault:
13260b57cec5SDimitry Andric       Flags |= 4;
13270b57cec5SDimitry Andric       break;
13280b57cec5SDimitry Andric     }
13290b57cec5SDimitry Andric     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
13300b57cec5SDimitry Andric       // This is a "duplicate" clause; the handler needs to be entered from a
13310b57cec5SDimitry Andric       // frame above the one holding the invoke.
13320b57cec5SDimitry Andric       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
13330b57cec5SDimitry Andric       Flags |= 8;
13340b57cec5SDimitry Andric     }
13355ffd83dbSDimitry Andric     OS.emitInt32(Flags);
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric     // Write the clause start/end
13385ffd83dbSDimitry Andric     OS.emitValue(ClauseBegin, 4);
13395ffd83dbSDimitry Andric     OS.emitValue(ClauseEnd, 4);
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric     // Write out the handler start/end
13425ffd83dbSDimitry Andric     OS.emitValue(HandlerBegin, 4);
13435ffd83dbSDimitry Andric     OS.emitValue(HandlerEnd, 4);
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     // Write out the type token or filter offset
13460b57cec5SDimitry Andric     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
13475ffd83dbSDimitry Andric     OS.emitInt32(Entry.TypeToken);
13480b57cec5SDimitry Andric   }
13490b57cec5SDimitry Andric }
1350