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