blob: 75cb43d85553be045bab4a80b1d1ee6e43dd787d [file] [log] [blame]
Reid Kleckner60b640b2015-05-28 22:47:01 +00001//===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
Charles Davis91ed7992011-05-27 23:47:32 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing Win64 exception info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner60b640b2015-05-28 22:47:01 +000014#include "WinException.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/StringExtras.h"
16#include "llvm/ADT/Twine.h"
Charles Davis91ed7992011-05-27 23:47:32 +000017#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/CodeGen/MachineModuleInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000021#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000023#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000025#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCExpr.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSymbol.h"
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000031#include "llvm/MC/MCWin64EH.h"
David Majnemera80c1512015-09-29 20:12:33 +000032#include "llvm/Support/COFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/Dwarf.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000036#include "llvm/Target/TargetFrameLowering.h"
Sanjoy Das0ebc9612016-06-16 18:54:06 +000037#include "llvm/Target/TargetLowering.h"
Charles Davis91ed7992011-05-27 23:47:32 +000038#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000039#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Reid Kleckner70bf6bb2015-10-07 21:13:15 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000042using namespace llvm;
43
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000044WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
45 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
46 // platforms use an imagerel32 relocation to refer to symbols.
47 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
48}
Charles Davis91ed7992011-05-27 23:47:32 +000049
Reid Kleckner60b640b2015-05-28 22:47:01 +000050WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000051
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000052/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000053/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000054void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000055 auto &OS = *Asm->OutStreamer;
56 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000057 for (const Function &F : *M)
58 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000059 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000060}
61
Reid Kleckner60b640b2015-05-28 22:47:01 +000062void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000063 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
64
65 // If any landing pads survive, we need an EH table.
Matthias Braund0ee66c2016-12-01 19:32:15 +000066 bool hasLandingPads = !MF->getLandingPads().empty();
67 bool hasEHFunclets = MF->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000068
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000069 const Function *F = MF->getFunction();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000070
Charles Davis5638b9f2011-05-28 04:21:04 +000071 shouldEmitMoves = Asm->needsSEHMoves();
72
73 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Charles Davis5638b9f2011-05-28 04:21:04 +000075
Reid Kleckner9cb915b2016-09-30 22:10:12 +000076 EHPersonality Per = EHPersonality::Unknown;
77 const Function *PerFn = nullptr;
78 if (F->hasPersonalityFn()) {
79 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
80 Per = classifyEHPersonality(PerFn);
81 }
82
83 bool forceEmitPersonality = F->hasPersonalityFn() &&
84 !isNoOpWithoutInvoke(Per) &&
85 F->needsUnwindTableEntry();
Keno Fischeraff703a2015-07-14 19:22:51 +000086
Reid Kleckner0e288232015-08-27 23:27:47 +000087 shouldEmitPersonality =
88 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
Reid Kleckner9cb915b2016-09-30 22:10:12 +000089 PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
Charles Davis5638b9f2011-05-28 04:21:04 +000090
91 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
92 shouldEmitLSDA = shouldEmitPersonality &&
93 LSDAEncoding != dwarf::DW_EH_PE_omit;
94
Reid Kleckner0e288232015-08-27 23:27:47 +000095 // If we're not using CFI, we don't want the CFI or the personality, but we
96 // might want EH tables if we had EH pads.
Reid Kleckner9cb915b2016-09-30 22:10:12 +000097 if (!Asm->MAI->usesWindowsCFI() || (!MF->hasWinCFI() && !PerFn)) {
98 if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
99 // If this is 32-bit SEH and we don't have any funclets (really invokes),
100 // make sure we emit the parent offset label. Some unreferenced filter
101 // functions may still refer to it.
102 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
103 StringRef FLinkageName =
104 GlobalValue::getRealLinkageName(MF->getFunction()->getName());
105 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
106 }
David Majnemerbfa5b982015-10-10 00:04:29 +0000107 shouldEmitLSDA = hasEHFunclets;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000108 shouldEmitPersonality = false;
109 return;
110 }
David Majnemera225a192015-03-31 22:35:44 +0000111
David Majnemera80c1512015-09-29 20:12:33 +0000112 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000113}
114
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000115/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000116///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000117void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000118 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000119 return;
120
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000121 const Function *F = MF->getFunction();
122 EHPersonality Per = EHPersonality::Unknown;
123 if (F->hasPersonalityFn())
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000124 Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000125
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000126 // Get rid of any dead landing pads if we're not using funclets. In funclet
127 // schemes, the landing pad is not actually reachable. It only exists so
128 // that we can emit the right table data.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000129 if (!isFuncletEHPersonality(Per)) {
130 MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
131 NonConstMF->tidyLandingPads();
132 }
Charles Davisa5752262011-05-30 00:13:34 +0000133
David Majnemera80c1512015-09-29 20:12:33 +0000134 endFunclet();
135
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000136 // endFunclet will emit the necessary .xdata tables for x64 SEH.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000137 if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000138 return;
139
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000140 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000141 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000142
Reid Kleckner97837b72016-05-02 23:22:18 +0000143 // Just switch sections to the right xdata section.
144 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
145 Asm->OutStreamer->getCurrentSectionOnly());
David Majnemera80c1512015-09-29 20:12:33 +0000146 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000147
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000148 // Emit the tables appropriate to the personality function in use. If we
149 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000150 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000151 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000152 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000153 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000154 else if (Per == EHPersonality::MSVC_CXX)
155 emitCXXFrameHandler3Table(MF);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000156 else if (Per == EHPersonality::CoreCLR)
157 emitCLRExceptionTable(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000158 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000159 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000160
Lang Hames9ff69c82015-04-24 19:11:51 +0000161 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000162 }
David Majnemera80c1512015-09-29 20:12:33 +0000163}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000164
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000165/// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000166static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
167 const MachineBasicBlock *MBB) {
168 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000169 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000170
David Majnemerbfa5b982015-10-10 00:04:29 +0000171 assert(MBB->isEHFuncletEntry());
172
173 // Give catches and cleanups a name based off of their parent function and
174 // their funclet entry block's number.
175 const MachineFunction *MF = MBB->getParent();
176 const Function *F = MF->getFunction();
177 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
178 MCContext &Ctx = MF->getContext();
179 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
180 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
181 Twine(MBB->getNumber()) + "@?0?" +
182 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000183}
184
185void WinException::beginFunclet(const MachineBasicBlock &MBB,
186 MCSymbol *Sym) {
187 CurrentFuncletEntry = &MBB;
188
189 const Function *F = Asm->MF->getFunction();
190 // If a symbol was not provided for the funclet, invent one.
191 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000192 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000193
194 // Describe our funclet symbol as a function with internal linkage.
195 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
196 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
197 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
198 << COFF::SCT_COMPLEX_TYPE_SHIFT);
199 Asm->OutStreamer->EndCOFFSymbolDef();
200
201 // We want our funclet's entry point to be aligned such that no nops will be
202 // present after the label.
203 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
204 F);
205
206 // Now that we've emitted the alignment directive, point at our funclet.
207 Asm->OutStreamer->EmitLabel(Sym);
208 }
209
210 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000211 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000212 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
213
214 if (shouldEmitPersonality) {
215 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
216 const Function *PerFn = nullptr;
217
218 // Determine which personality routine we are using for this funclet.
219 if (F->hasPersonalityFn())
220 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
221 const MCSymbol *PersHandlerSym =
Eric Christopher4367c7f2016-09-16 07:33:15 +0000222 TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
David Majnemera80c1512015-09-29 20:12:33 +0000223
224 // Classify the personality routine so that we may reason about it.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000225 EHPersonality Per = classifyEHPersonality(PerFn);
David Majnemera80c1512015-09-29 20:12:33 +0000226
227 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
228 if (Per != EHPersonality::MSVC_CXX ||
229 !CurrentFuncletEntry->isCleanupFuncletEntry())
230 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
231 }
232}
233
234void WinException::endFunclet() {
235 // No funclet to process? Great, we have nothing to do.
236 if (!CurrentFuncletEntry)
237 return;
238
Matthias Braund0ee66c2016-12-01 19:32:15 +0000239 const MachineFunction *MF = Asm->MF;
David Majnemera80c1512015-09-29 20:12:33 +0000240 if (shouldEmitMoves || shouldEmitPersonality) {
Matthias Braund0ee66c2016-12-01 19:32:15 +0000241 const Function *F = MF->getFunction();
David Majnemera80c1512015-09-29 20:12:33 +0000242 EHPersonality Per = EHPersonality::Unknown;
243 if (F->hasPersonalityFn())
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000244 Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
David Majnemera80c1512015-09-29 20:12:33 +0000245
246 // The .seh_handlerdata directive implicitly switches section, push the
247 // current section so that we may return to it.
248 Asm->OutStreamer->PushSection();
249
250 // Emit an UNWIND_INFO struct describing the prologue.
251 Asm->OutStreamer->EmitWinEHHandlerData();
252
David Majnemera80c1512015-09-29 20:12:33 +0000253 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
254 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000255 // If this is a C++ catch funclet (or the parent function),
256 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000257 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
258 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
259 Twine("$cppxdata$", FuncLinkageName));
260 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Matthias Braund0ee66c2016-12-01 19:32:15 +0000261 } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000262 !CurrentFuncletEntry->isEHFuncletEntry()) {
263 // If this is the parent function in Win64 SEH, emit the LSDA immediately
264 // following .seh_handlerdata.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000265 emitCSpecificHandlerTable(MF);
David Majnemera80c1512015-09-29 20:12:33 +0000266 }
267
268 // Switch back to the previous section now that we are done writing to
269 // .xdata.
270 Asm->OutStreamer->PopSection();
271
272 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000273 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000274 }
275
276 // Let's make sure we don't try to end the same funclet twice.
277 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000278}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000279
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000280const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000281 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000282 return MCConstantExpr::create(0, Asm->OutContext);
283 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000284 ? MCSymbolRefExpr::VK_COFF_IMGREL32
285 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000286 Asm->OutContext);
287}
288
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000289const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
290 if (!GV)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000291 return MCConstantExpr::create(0, Asm->OutContext);
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000292 return create32bitRef(Asm->getSymbol(GV));
David Majnemercde33032015-03-30 22:58:10 +0000293}
294
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000295const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000296 return MCBinaryExpr::createAdd(create32bitRef(Label),
297 MCConstantExpr::create(1, Asm->OutContext),
298 Asm->OutContext);
299}
300
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000301const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
302 const MCSymbol *OffsetFrom) {
303 return MCBinaryExpr::createSub(
304 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
305 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
306}
307
308const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
309 const MCSymbol *OffsetFrom) {
310 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
311 MCConstantExpr::create(1, Asm->OutContext),
312 Asm->OutContext);
313}
314
Reid Klecknerc20276d2015-11-17 21:10:25 +0000315int WinException::getFrameIndexOffset(int FrameIndex,
316 const WinEHFuncInfo &FuncInfo) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000317 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
318 unsigned UnusedReg;
Sanjoy Das0ebc9612016-06-16 18:54:06 +0000319 if (Asm->MAI->usesWindowsCFI()) {
320 int Offset =
321 TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
322 /*IgnoreSPUpdates*/ true);
323 assert(UnusedReg ==
324 Asm->MF->getSubtarget()
325 .getTargetLowering()
326 ->getStackPointerRegisterToSaveRestore());
327 return Offset;
328 }
329
Reid Kleckner6ddae312015-11-05 21:09:49 +0000330 // For 32-bit, offsets should be relative to the end of the EH registration
331 // node. For 64-bit, it's relative to SP at the end of the prologue.
332 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
333 int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
334 Offset += FuncInfo.EHRegNodeEndOffset;
335 return Offset;
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000336}
337
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000338namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000339
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000340/// Top-level state used to represent unwind to caller
341const int NullState = -1;
342
343struct InvokeStateChange {
344 /// EH Label immediately after the last invoke in the previous state, or
345 /// nullptr if the previous state was the null state.
346 const MCSymbol *PreviousEndLabel;
347
348 /// EH label immediately before the first invoke in the new state, or nullptr
349 /// if the new state is the null state.
350 const MCSymbol *NewStartLabel;
351
352 /// State of the invoke following NewStartLabel, or NullState to indicate
353 /// the presence of calls which may unwind to caller.
354 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000355};
356
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000357/// Iterator that reports all the invoke state changes in a range of machine
358/// basic blocks. Changes to the null state are reported whenever a call that
359/// may unwind to caller is encountered. The MBB range is expected to be an
360/// entire function or funclet, and the start and end of the range are treated
361/// as being in the NullState even if there's not an unwind-to-caller call
362/// before the first invoke or after the last one (i.e., the first state change
363/// reported is the first change to something other than NullState, and a
364/// change back to NullState is always reported at the end of iteration).
365class InvokeStateChangeIterator {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000366 InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000367 MachineFunction::const_iterator MFI,
368 MachineFunction::const_iterator MFE,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000369 MachineBasicBlock::const_iterator MBBI,
370 int BaseState)
371 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000372 LastStateChange.PreviousEndLabel = nullptr;
373 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000374 LastStateChange.NewState = BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000375 scan();
376 }
377
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000378public:
379 static iterator_range<InvokeStateChangeIterator>
Reid Klecknerc20276d2015-11-17 21:10:25 +0000380 range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000381 MachineFunction::const_iterator End, int BaseState = NullState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000382 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
383 // the end of the last block.
384 assert(Begin != End);
385 auto BlockBegin = Begin->begin();
386 auto BlockEnd = std::prev(End)->end();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000387 return make_range(
388 InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
389 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000390 }
391
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000392 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000393 bool operator==(const InvokeStateChangeIterator &O) const {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000394 assert(BaseState == O.BaseState);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000395 // Must be visiting same block.
396 if (MFI != O.MFI)
397 return false;
398 // Must be visiting same isntr.
399 if (MBBI != O.MBBI)
400 return false;
401 // At end of block/instr iteration, we can still have two distinct states:
402 // one to report the final EndLabel, and another indicating the end of the
403 // state change iteration. Check for CurrentEndLabel equality to
404 // distinguish these.
405 return CurrentEndLabel == O.CurrentEndLabel;
406 }
407
408 bool operator!=(const InvokeStateChangeIterator &O) const {
409 return !operator==(O);
410 }
411 InvokeStateChange &operator*() { return LastStateChange; }
412 InvokeStateChange *operator->() { return &LastStateChange; }
413 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000414
415private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000416 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000417
Reid Klecknerc20276d2015-11-17 21:10:25 +0000418 const WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000419 const MCSymbol *CurrentEndLabel = nullptr;
420 MachineFunction::const_iterator MFI;
421 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000422 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000423 InvokeStateChange LastStateChange;
424 bool VisitingInvoke = false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000425 int BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000426};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000427
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000428} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000429
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000430InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
431 bool IsNewBlock = false;
432 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
433 if (IsNewBlock)
434 MBBI = MFI->begin();
435 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
436 const MachineInstr &MI = *MBBI;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000437 if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000438 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
439 // Indicate a change of state to the null state. We don't have
440 // start/end EH labels handy but the caller won't expect them for
441 // null state regions.
442 LastStateChange.PreviousEndLabel = CurrentEndLabel;
443 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000444 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000445 CurrentEndLabel = nullptr;
446 // Don't re-visit this instr on the next scan
447 ++MBBI;
448 return *this;
449 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000450
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000451 // All other state changes are at EH labels before/after invokes.
452 if (!MI.isEHLabel())
453 continue;
454 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
455 if (Label == CurrentEndLabel) {
456 VisitingInvoke = false;
457 continue;
458 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000459 auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000460 // Ignore EH labels that aren't the ones inserted before an invoke
David Majnemer8a1c45d2015-12-12 05:38:55 +0000461 if (InvokeMapIter == EHInfo.LabelToStateMap.end())
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000462 continue;
463 auto &StateAndEnd = InvokeMapIter->second;
464 int NewState = StateAndEnd.first;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000465 // Keep track of the fact that we're between EH start/end labels so
466 // we know not to treat the inoke we'll see as unwinding to caller.
467 VisitingInvoke = true;
468 if (NewState == LastStateChange.NewState) {
469 // The state isn't actually changing here. Record the new end and
470 // keep going.
471 CurrentEndLabel = StateAndEnd.second;
472 continue;
473 }
474 // Found a state change to report
475 LastStateChange.PreviousEndLabel = CurrentEndLabel;
476 LastStateChange.NewStartLabel = Label;
477 LastStateChange.NewState = NewState;
478 // Start keeping track of the new current end
479 CurrentEndLabel = StateAndEnd.second;
480 // Don't re-visit this instr on the next scan
481 ++MBBI;
482 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000483 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000484 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000485 // Iteration hit the end of the block range.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000486 if (LastStateChange.NewState != BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000487 // Report the end of the last new state
488 LastStateChange.PreviousEndLabel = CurrentEndLabel;
489 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000490 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000491 // Leave CurrentEndLabel non-null to distinguish this state from end.
492 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000493 return *this;
494 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000495 // We've reported all state changes and hit the end state.
496 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000497 return *this;
498}
499
Reid Kleckner0a57f652015-01-14 01:05:27 +0000500/// Emit the language-specific data that __C_specific_handler expects. This
501/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
502/// up after faults with __try, __except, and __finally. The typeinfo values
503/// are not really RTTI data, but pointers to filter functions that return an
504/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
505/// blocks and other cleanups, the landing pad label is zero, and the filter
506/// function is actually a cleanup handler with the same prototype. A catch-all
507/// entry is modeled with a null filter function field and a non-zero landing
508/// pad label.
509///
510/// Possible filter function return values:
511/// EXCEPTION_EXECUTE_HANDLER (1):
512/// Jump to the landing pad label after cleanups.
513/// EXCEPTION_CONTINUE_SEARCH (0):
514/// Continue searching this table or continue unwinding.
515/// EXCEPTION_CONTINUE_EXECUTION (-1):
516/// Resume execution at the trapping PC.
517///
518/// Inferred table structure:
519/// struct Table {
520/// int NumEntries;
521/// struct Entry {
522/// imagerel32 LabelStart;
523/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000524/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000525/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000526/// } Entries[NumEntries];
527/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000528void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000529 auto &OS = *Asm->OutStreamer;
530 MCContext &Ctx = Asm->OutContext;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000531 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000532
David Majnemer081e8fe2015-12-27 06:07:12 +0000533 bool VerboseAsm = OS.isVerboseAsm();
534 auto AddComment = [&](const Twine &Comment) {
535 if (VerboseAsm)
536 OS.AddComment(Comment);
537 };
538
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000539 // Emit a label assignment with the SEH frame offset so we can use it for
540 // llvm.x86.seh.recoverfp.
541 StringRef FLinkageName =
542 GlobalValue::getRealLinkageName(MF->getFunction()->getName());
543 MCSymbol *ParentFrameOffset =
544 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
545 const MCExpr *MCOffset =
546 MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
547 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
548
Reid Kleckner14e77352015-10-09 23:34:53 +0000549 // Use the assembler to compute the number of table entries through label
550 // difference and division.
551 MCSymbol *TableBegin =
552 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
553 MCSymbol *TableEnd =
554 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000555 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
Reid Kleckner14e77352015-10-09 23:34:53 +0000556 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
557 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
David Majnemer081e8fe2015-12-27 06:07:12 +0000558 AddComment("Number of call sites");
Reid Kleckner14e77352015-10-09 23:34:53 +0000559 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000560
Reid Kleckner14e77352015-10-09 23:34:53 +0000561 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000562
Reid Kleckner14e77352015-10-09 23:34:53 +0000563 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
564 // models exceptions from invokes. LLVM also allows arbitrary reordering of
565 // the code, so our tables end up looking a bit different. Rather than
566 // trying to match MSVC's tables exactly, we emit a denormalized table. For
567 // each range of invokes in the same state, we emit table entries for all
568 // the actions that would be taken in that state. This means our tables are
569 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000570 const MCSymbol *LastStartLabel = nullptr;
571 int LastEHState = -1;
572 // Break out before we enter into a finally funclet.
573 // FIXME: We need to emit separate EH tables for cleanups.
574 MachineFunction::const_iterator End = MF->end();
575 MachineFunction::const_iterator Stop = std::next(MF->begin());
576 while (Stop != End && !Stop->isEHFuncletEntry())
577 ++Stop;
578 for (const auto &StateChange :
579 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
580 // Emit all the actions for the state we just transitioned out of
581 // if it was not the null state
582 if (LastEHState != -1)
583 emitSEHActionsForRange(FuncInfo, LastStartLabel,
584 StateChange.PreviousEndLabel, LastEHState);
585 LastStartLabel = StateChange.NewStartLabel;
586 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000587 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000588
Reid Kleckner14e77352015-10-09 23:34:53 +0000589 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000590}
David Majnemercde33032015-03-30 22:58:10 +0000591
Reid Klecknerc20276d2015-11-17 21:10:25 +0000592void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000593 const MCSymbol *BeginLabel,
594 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000595 auto &OS = *Asm->OutStreamer;
596 MCContext &Ctx = Asm->OutContext;
597
David Majnemer081e8fe2015-12-27 06:07:12 +0000598 bool VerboseAsm = OS.isVerboseAsm();
599 auto AddComment = [&](const Twine &Comment) {
600 if (VerboseAsm)
601 OS.AddComment(Comment);
602 };
603
Reid Klecknerd880dc72015-10-09 20:39:39 +0000604 assert(BeginLabel && EndLabel);
605 while (State != -1) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000606 const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
Reid Klecknerd880dc72015-10-09 20:39:39 +0000607 const MCExpr *FilterOrFinally;
608 const MCExpr *ExceptOrNull;
609 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
610 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000611 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000612 ExceptOrNull = MCConstantExpr::create(0, Ctx);
613 } else {
614 // For an except, the filter can be 1 (catch-all) or a function
615 // label.
616 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
617 : MCConstantExpr::create(1, Ctx);
618 ExceptOrNull = create32bitRef(Handler->getSymbol());
619 }
620
David Majnemer081e8fe2015-12-27 06:07:12 +0000621 AddComment("LabelStart");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000622 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000623 AddComment("LabelEnd");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000624 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000625 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
626 : "CatchAll");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000627 OS.EmitValue(FilterOrFinally, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000628 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000629 OS.EmitValue(ExceptOrNull, 4);
630
631 assert(UME.ToState < State && "states should decrease");
632 State = UME.ToState;
633 }
634}
635
Reid Kleckner60b640b2015-05-28 22:47:01 +0000636void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000637 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000638 auto &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000639 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
David Majnemercde33032015-03-30 22:58:10 +0000640
Reid Kleckner813f1b62015-09-16 22:14:46 +0000641 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000642
Reid Klecknerc71d6272015-09-28 23:56:30 +0000643 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000644 MCSymbol *FuncInfoXData = nullptr;
645 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000646 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
647 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000648 FuncInfoXData =
649 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000650 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000651 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000652 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000653 }
654
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000655 int UnwindHelpOffset = 0;
656 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner6ddae312015-11-05 21:09:49 +0000657 UnwindHelpOffset =
658 getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000659
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000660 MCSymbol *UnwindMapXData = nullptr;
661 MCSymbol *TryBlockMapXData = nullptr;
662 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000663 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000664 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000665 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000666 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000667 TryBlockMapXData =
668 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000669 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000670 IPToStateXData =
671 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000672
David Majnemer081e8fe2015-12-27 06:07:12 +0000673 bool VerboseAsm = OS.isVerboseAsm();
674 auto AddComment = [&](const Twine &Comment) {
675 if (VerboseAsm)
676 OS.AddComment(Comment);
677 };
678
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000679 // FuncInfo {
680 // uint32_t MagicNumber
681 // int32_t MaxState;
682 // UnwindMapEntry *UnwindMap;
683 // uint32_t NumTryBlocks;
684 // TryBlockMapEntry *TryBlockMap;
685 // uint32_t IPMapEntries; // always 0 for x86
686 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
687 // uint32_t UnwindHelp; // non-x86 only
688 // ESTypeList *ESTypeList;
689 // int32_t EHFlags;
690 // }
691 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
692 // EHFlags & 2 -> ???
693 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000694 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000695 OS.EmitLabel(FuncInfoXData);
David Majnemer081e8fe2015-12-27 06:07:12 +0000696
697 AddComment("MagicNumber");
698 OS.EmitIntValue(0x19930522, 4);
699
700 AddComment("MaxState");
701 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
702
703 AddComment("UnwindMap");
704 OS.EmitValue(create32bitRef(UnwindMapXData), 4);
705
706 AddComment("NumTryBlocks");
707 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
708
709 AddComment("TryBlockMap");
710 OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
711
712 AddComment("IPMapEntries");
713 OS.EmitIntValue(IPToStateTable.size(), 4);
714
715 AddComment("IPToStateXData");
716 OS.EmitValue(create32bitRef(IPToStateXData), 4);
717
718 if (Asm->MAI->usesWindowsCFI()) {
719 AddComment("UnwindHelp");
720 OS.EmitIntValue(UnwindHelpOffset, 4);
721 }
722
723 AddComment("ESTypeList");
724 OS.EmitIntValue(0, 4);
725
726 AddComment("EHFlags");
727 OS.EmitIntValue(1, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000728
729 // UnwindMapEntry {
730 // int32_t ToState;
731 // void (*Action)();
732 // };
733 if (UnwindMapXData) {
734 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000735 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000736 MCSymbol *CleanupSym =
737 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
David Majnemer081e8fe2015-12-27 06:07:12 +0000738 AddComment("ToState");
739 OS.EmitIntValue(UME.ToState, 4);
740
741 AddComment("Action");
742 OS.EmitValue(create32bitRef(CleanupSym), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000743 }
744 }
745
746 // TryBlockMap {
747 // int32_t TryLow;
748 // int32_t TryHigh;
749 // int32_t CatchHigh;
750 // int32_t NumCatches;
751 // HandlerType *HandlerArray;
752 // };
753 if (TryBlockMapXData) {
754 OS.EmitLabel(TryBlockMapXData);
755 SmallVector<MCSymbol *, 1> HandlerMaps;
756 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000757 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000758
Reid Kleckner813f1b62015-09-16 22:14:46 +0000759 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000760 if (!TBME.HandlerArray.empty())
761 HandlerMapXData =
762 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
763 .concat(Twine(I))
764 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000765 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000766 HandlerMaps.push_back(HandlerMapXData);
767
Reid Kleckner813f1b62015-09-16 22:14:46 +0000768 // TBMEs should form intervals.
769 assert(0 <= TBME.TryLow && "bad trymap interval");
770 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
771 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000772 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000773 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000774
David Majnemer081e8fe2015-12-27 06:07:12 +0000775 AddComment("TryLow");
776 OS.EmitIntValue(TBME.TryLow, 4);
777
778 AddComment("TryHigh");
779 OS.EmitIntValue(TBME.TryHigh, 4);
780
781 AddComment("CatchHigh");
782 OS.EmitIntValue(TBME.CatchHigh, 4);
783
784 AddComment("NumCatches");
785 OS.EmitIntValue(TBME.HandlerArray.size(), 4);
786
787 AddComment("HandlerArray");
788 OS.EmitValue(create32bitRef(HandlerMapXData), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000789 }
790
Reid Kleckner28e49032015-10-16 23:43:27 +0000791 // All funclets use the same parent frame offset currently.
792 unsigned ParentFrameOffset = 0;
793 if (shouldEmitPersonality) {
794 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
795 ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
796 }
797
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000798 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000799 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000800 MCSymbol *HandlerMapXData = HandlerMaps[I];
801 if (!HandlerMapXData)
802 continue;
803 // HandlerType {
804 // int32_t Adjectives;
805 // TypeDescriptor *Type;
806 // int32_t CatchObjOffset;
807 // void (*Handler)();
808 // int32_t ParentFrameOffset; // x64 only
809 // };
810 OS.EmitLabel(HandlerMapXData);
811 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
812 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000813 // the index is INT_MAX, then there is no catch object, and we should
814 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000815 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000816 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner6ddae312015-11-05 21:09:49 +0000817 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
David Majnemercb305de2016-03-01 04:30:16 +0000818 assert(Offset != 0 && "Illegal offset for catch object!");
Reid Klecknerb005d282015-09-16 20:16:27 +0000819 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000820 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000821 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000822 }
823
David Majnemerbfa5b982015-10-10 00:04:29 +0000824 MCSymbol *HandlerSym =
825 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000826
David Majnemer081e8fe2015-12-27 06:07:12 +0000827 AddComment("Adjectives");
828 OS.EmitIntValue(HT.Adjectives, 4);
829
830 AddComment("Type");
831 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
832
833 AddComment("CatchObjOffset");
834 OS.EmitValue(FrameAllocOffsetRef, 4);
835
836 AddComment("Handler");
837 OS.EmitValue(create32bitRef(HandlerSym), 4);
838
839 if (shouldEmitPersonality) {
840 AddComment("ParentFrameOffset");
841 OS.EmitIntValue(ParentFrameOffset, 4);
842 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000843 }
844 }
845 }
846
847 // IPToStateMapEntry {
848 // void *IP;
849 // int32_t State;
850 // };
851 if (IPToStateXData) {
852 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000853 for (auto &IPStatePair : IPToStateTable) {
David Majnemer081e8fe2015-12-27 06:07:12 +0000854 AddComment("IP");
855 OS.EmitValue(IPStatePair.first, 4);
856 AddComment("ToState");
857 OS.EmitIntValue(IPStatePair.second, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000858 }
859 }
860}
861
Reid Klecknerc71d6272015-09-28 23:56:30 +0000862void WinException::computeIP2StateTable(
Reid Klecknerc20276d2015-11-17 21:10:25 +0000863 const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
Reid Klecknerc71d6272015-09-28 23:56:30 +0000864 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000865
David Majnemer8a1c45d2015-12-12 05:38:55 +0000866 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
867 FuncletEnd = MF->begin(),
868 End = MF->end();
869 FuncletStart != End; FuncletStart = FuncletEnd) {
870 // Find the end of the funclet
871 while (++FuncletEnd != End) {
872 if (FuncletEnd->isEHFuncletEntry()) {
873 break;
874 }
875 }
876
877 // Don't emit ip2state entries for cleanup funclets. Any interesting
878 // exceptional actions in cleanups must be handled in a separate IR
879 // function.
880 if (FuncletStart->isCleanupFuncletEntry())
881 continue;
882
883 MCSymbol *StartLabel;
884 int BaseState;
885 if (FuncletStart == MF->begin()) {
886 BaseState = NullState;
887 StartLabel = Asm->getFunctionBegin();
888 } else {
889 auto *FuncletPad =
890 cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
891 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
892 BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
893 StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
894 }
895 assert(StartLabel && "need local function start label");
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000896 IPToStateTable.push_back(
David Majnemer8a1c45d2015-12-12 05:38:55 +0000897 std::make_pair(create32bitRef(StartLabel), BaseState));
898
899 for (const auto &StateChange : InvokeStateChangeIterator::range(
900 FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
901 // Compute the label to report as the start of this entry; use the EH
902 // start label for the invoke if we have one, otherwise (this is a call
903 // which may unwind to our caller and does not have an EH start label, so)
904 // use the previous end label.
905 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
906 if (!ChangeLabel)
907 ChangeLabel = StateChange.PreviousEndLabel;
908 // Emit an entry indicating that PCs after 'Label' have this EH state.
909 IPToStateTable.push_back(
910 std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
911 // FIXME: assert that NewState is between CatchLow and CatchHigh.
912 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000913 }
David Majnemercde33032015-03-30 22:58:10 +0000914}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000915
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000916void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
917 StringRef FLinkageName) {
918 // Outlined helpers called by the EH runtime need to know the offset of the EH
919 // registration in order to recover the parent frame pointer. Now that we know
920 // we've code generated the parent, we can emit the label assignment that
921 // those helpers use to get the offset of the registration node.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000922
923 // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
924 // after optimization all the invokes were eliminated. We still need to emit
925 // the parent frame offset label, but it should be garbage and should never be
926 // used.
927 int64_t Offset = 0;
928 int FI = FuncInfo.EHRegNodeFrameIndex;
929 if (FI != INT_MAX) {
930 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
931 unsigned UnusedReg;
932 Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
933 }
934
Reid Klecknerc20276d2015-11-17 21:10:25 +0000935 MCContext &Ctx = Asm->OutContext;
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000936 MCSymbol *ParentFrameOffset =
Reid Klecknerc20276d2015-11-17 21:10:25 +0000937 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000938 Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
939 MCConstantExpr::create(Offset, Ctx));
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000940}
941
Reid Klecknerf12c0302015-06-09 21:42:19 +0000942/// Emit the language-specific data that _except_handler3 and 4 expect. This is
943/// functionally equivalent to the __C_specific_handler table, except it is
944/// indexed by state number instead of IP.
945void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000946 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000947 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000948 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000949
David Majnemer081e8fe2015-12-27 06:07:12 +0000950 bool VerboseAsm = OS.isVerboseAsm();
951 auto AddComment = [&](const Twine &Comment) {
952 if (VerboseAsm)
953 OS.AddComment(Comment);
954 };
955
Reid Klecknerc20276d2015-11-17 21:10:25 +0000956 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000957 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000958
959 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000960 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000961 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000962 OS.EmitLabel(LSDALabel);
963
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000964 const Function *Per =
965 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000966 StringRef PerName = Per->getName();
967 int BaseState = -1;
968 if (PerName == "_except_handler4") {
969 // The LSDA for _except_handler4 starts with this struct, followed by the
970 // scope table:
971 //
972 // struct EH4ScopeTable {
973 // int32_t GSCookieOffset;
974 // int32_t GSCookieXOROffset;
975 // int32_t EHCookieOffset;
976 // int32_t EHCookieXOROffset;
977 // ScopeTableEntry ScopeRecord[];
978 // };
979 //
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000980 // Offsets are %ebp relative.
981 //
982 // The GS cookie is present only if the function needs stack protection.
983 // GSCookieOffset = -2 means that GS cookie is not used.
984 //
985 // The EH cookie is always present.
986 //
987 // Check is done the following way:
988 // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
989
990 // Retrieve the Guard Stack slot.
991 int GSCookieOffset = -2;
Matthias Braun941a7052016-07-28 18:40:00 +0000992 const MachineFrameInfo &MFI = MF->getFrameInfo();
993 if (MFI.hasStackProtectorIndex()) {
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000994 unsigned UnusedReg;
995 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +0000996 int SSPIdx = MFI.getStackProtectorIndex();
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000997 GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
998 }
999
1000 // Retrieve the EH Guard slot.
1001 // TODO(etienneb): Get rid of this value and change it for and assertion.
1002 int EHCookieOffset = 9999;
1003 if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1004 unsigned UnusedReg;
1005 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1006 int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1007 EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
1008 }
1009
David Majnemer081e8fe2015-12-27 06:07:12 +00001010 AddComment("GSCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001011 OS.EmitIntValue(GSCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001012 AddComment("GSCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001013 OS.EmitIntValue(0, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001014 AddComment("EHCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001015 OS.EmitIntValue(EHCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001016 AddComment("EHCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001017 OS.EmitIntValue(0, 4);
1018 BaseState = -2;
1019 }
1020
Reid Kleckner14e77352015-10-09 23:34:53 +00001021 assert(!FuncInfo.SEHUnwindMap.empty());
Reid Klecknerc20276d2015-11-17 21:10:25 +00001022 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
David Majnemer081e8fe2015-12-27 06:07:12 +00001023 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1024 const MCSymbol *ExceptOrFinally =
1025 UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
Reid Kleckner14e77352015-10-09 23:34:53 +00001026 // -1 is usually the base state for "unwind to caller", but for
1027 // _except_handler4 it's -2. Do that replacement here if necessary.
1028 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
David Majnemer081e8fe2015-12-27 06:07:12 +00001029 AddComment("ToState");
1030 OS.EmitIntValue(ToState, 4);
1031 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1032 OS.EmitValue(create32bitRef(UME.Filter), 4);
1033 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1034 OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001035 }
1036}
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001037
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001038static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001039 int Rank = 0;
1040 while (State != -1) {
1041 ++Rank;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001042 State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001043 }
1044 return Rank;
1045}
1046
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001047static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1048 int LeftRank = getTryRank(FuncInfo, Left);
1049 int RightRank = getTryRank(FuncInfo, Right);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001050
1051 while (LeftRank < RightRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001052 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001053 --RightRank;
1054 }
1055
1056 while (RightRank < LeftRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001057 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001058 --LeftRank;
1059 }
1060
1061 while (Left != Right) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001062 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1063 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001064 }
1065
1066 return Left;
1067}
1068
1069void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1070 // CLR EH "states" are really just IDs that identify handlers/funclets;
1071 // states, handlers, and funclets all have 1:1 mappings between them, and a
1072 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1073 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +00001074 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001075 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1076 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1077
1078 // A ClrClause describes a protected region.
1079 struct ClrClause {
1080 const MCSymbol *StartLabel; // Start of protected region
1081 const MCSymbol *EndLabel; // End of protected region
1082 int State; // Index of handler protecting the protected region
1083 int EnclosingState; // Index of funclet enclosing the protected region
1084 };
1085 SmallVector<ClrClause, 8> Clauses;
1086
1087 // Build a map from handler MBBs to their corresponding states (i.e. their
1088 // indices in the ClrEHUnwindMap).
1089 int NumStates = FuncInfo.ClrEHUnwindMap.size();
1090 assert(NumStates > 0 && "Don't need exception table!");
1091 DenseMap<const MachineBasicBlock *, int> HandlerStates;
1092 for (int State = 0; State < NumStates; ++State) {
1093 MachineBasicBlock *HandlerBlock =
1094 FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1095 HandlerStates[HandlerBlock] = State;
1096 // Use this loop through all handlers to verify our assumption (used in
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001097 // the MinEnclosingState computation) that enclosing funclets have lower
1098 // state numbers than their enclosed funclets.
1099 assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001100 "ill-formed state numbering");
1101 }
1102 // Map the main function to the NullState.
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001103 HandlerStates[&MF->front()] = NullState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001104
1105 // Write out a sentinel indicating the end of the standard (Windows) xdata
1106 // and the start of the additional (CLR) info.
1107 OS.EmitIntValue(0xffffffff, 4);
1108 // Write out the number of funclets
1109 OS.EmitIntValue(NumStates, 4);
1110
1111 // Walk the machine blocks/instrs, computing and emitting a few things:
1112 // 1. Emit a list of the offsets to each handler entry, in lexical order.
1113 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1114 // 3. Compute the list of ClrClauses, in the required order (inner before
1115 // outer, earlier before later; the order by which a forward scan with
1116 // early termination will find the innermost enclosing clause covering
1117 // a given address).
1118 // 4. A map (MinClauseMap) from each handler index to the index of the
1119 // outermost funclet/function which contains a try clause targeting the
1120 // key handler. This will be used to determine IsDuplicate-ness when
1121 // emitting ClrClauses. The NullState value is used to indicate that the
1122 // top-level function contains a try clause targeting the key handler.
1123 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1124 // try regions we entered before entering the PendingState try but which
1125 // we haven't yet exited.
1126 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1127 // EndSymbolMap and MinClauseMap are maps described above.
1128 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1129 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1130
1131 // Visit the root function and each funclet.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001132 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1133 FuncletEnd = MF->begin(),
1134 End = MF->end();
1135 FuncletStart != End; FuncletStart = FuncletEnd) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001136 int FuncletState = HandlerStates[&*FuncletStart];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001137 // Find the end of the funclet
1138 MCSymbol *EndSymbol = FuncEndSym;
1139 while (++FuncletEnd != End) {
1140 if (FuncletEnd->isEHFuncletEntry()) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001141 EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001142 break;
1143 }
1144 }
1145 // Emit the function/funclet end and, if this is a funclet (and not the
1146 // root function), record it in the EndSymbolMap.
1147 OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1148 if (FuncletState != NullState) {
1149 // Record the end of the handler.
1150 EndSymbolMap[FuncletState] = EndSymbol;
1151 }
1152
1153 // Walk the state changes in this function/funclet and compute its clauses.
1154 // Funclets always start in the null state.
1155 const MCSymbol *CurrentStartLabel = nullptr;
1156 int CurrentState = NullState;
1157 assert(HandlerStack.empty());
1158 for (const auto &StateChange :
1159 InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1160 // Close any try regions we're not still under
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001161 int StillPendingState =
1162 getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1163 while (CurrentState != StillPendingState) {
1164 assert(CurrentState != NullState &&
1165 "Failed to find still-pending state!");
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001166 // Close the pending clause
1167 Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1168 CurrentState, FuncletState});
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001169 // Now the next-outer try region is current
1170 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001171 // Pop the new start label from the handler stack if we've exited all
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001172 // inner try regions of the corresponding try region.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001173 if (HandlerStack.back().second == CurrentState)
1174 CurrentStartLabel = HandlerStack.pop_back_val().first;
1175 }
1176
1177 if (StateChange.NewState != CurrentState) {
1178 // For each clause we're starting, update the MinClauseMap so we can
1179 // know which is the topmost funclet containing a clause targeting
1180 // it.
1181 for (int EnteredState = StateChange.NewState;
1182 EnteredState != CurrentState;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001183 EnteredState =
1184 FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001185 int &MinEnclosingState = MinClauseMap[EnteredState];
1186 if (FuncletState < MinEnclosingState)
1187 MinEnclosingState = FuncletState;
1188 }
1189 // Save the previous current start/label on the stack and update to
1190 // the newly-current start/state.
1191 HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1192 CurrentStartLabel = StateChange.NewStartLabel;
1193 CurrentState = StateChange.NewState;
1194 }
1195 }
1196 assert(HandlerStack.empty());
1197 }
1198
1199 // Now emit the clause info, starting with the number of clauses.
1200 OS.EmitIntValue(Clauses.size(), 4);
1201 for (ClrClause &Clause : Clauses) {
1202 // Emit a CORINFO_EH_CLAUSE :
1203 /*
1204 struct CORINFO_EH_CLAUSE
1205 {
1206 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1207 DWORD TryOffset;
1208 DWORD TryLength; // actually TryEndOffset
1209 DWORD HandlerOffset;
1210 DWORD HandlerLength; // actually HandlerEndOffset
1211 union
1212 {
1213 DWORD ClassToken; // use for catch clauses
1214 DWORD FilterOffset; // use for filter clauses
1215 };
1216 };
1217
1218 enum CORINFO_EH_CLAUSE_FLAGS
1219 {
1220 CORINFO_EH_CLAUSE_NONE = 0,
1221 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1222 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1223 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1224 };
1225 typedef enum CorExceptionFlag
1226 {
1227 COR_ILEXCEPTION_CLAUSE_NONE,
1228 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1229 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1230 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1231 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1232 // clause was duplicated
1233 // to a funclet which was
1234 // pulled out of line
1235 } CorExceptionFlag;
1236 */
1237 // Add 1 to the start/end of the EH clause; the IP associated with a
1238 // call when the runtime does its scan is the IP of the next instruction
1239 // (the one to which control will return after the call), so we need
1240 // to add 1 to the end of the clause to cover that offset. We also add
1241 // 1 to the start of the clause to make sure that the ranges reported
1242 // for all clauses are disjoint. Note that we'll need some additional
1243 // logic when machine traps are supported, since in that case the IP
1244 // that the runtime uses is the offset of the faulting instruction
1245 // itself; if such an instruction immediately follows a call but the
1246 // two belong to different clauses, we'll need to insert a nop between
1247 // them so the runtime can distinguish the point to which the call will
1248 // return from the point at which the fault occurs.
1249
1250 const MCExpr *ClauseBegin =
1251 getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1252 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1253
Reid Klecknerc20276d2015-11-17 21:10:25 +00001254 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001255 MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1256 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1257 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1258 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1259 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1260
1261 uint32_t Flags = 0;
1262 switch (Entry.HandlerType) {
1263 case ClrHandlerType::Catch:
1264 // Leaving bits 0-2 clear indicates catch.
1265 break;
1266 case ClrHandlerType::Filter:
1267 Flags |= 1;
1268 break;
1269 case ClrHandlerType::Finally:
1270 Flags |= 2;
1271 break;
1272 case ClrHandlerType::Fault:
1273 Flags |= 4;
1274 break;
1275 }
1276 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1277 // This is a "duplicate" clause; the handler needs to be entered from a
1278 // frame above the one holding the invoke.
1279 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1280 Flags |= 8;
1281 }
1282 OS.EmitIntValue(Flags, 4);
1283
1284 // Write the clause start/end
1285 OS.EmitValue(ClauseBegin, 4);
1286 OS.EmitValue(ClauseEnd, 4);
1287
1288 // Write out the handler start/end
1289 OS.EmitValue(HandlerBegin, 4);
1290 OS.EmitValue(HandlerEnd, 4);
1291
1292 // Write out the type token or filter offset
1293 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1294 OS.EmitIntValue(Entry.TypeToken, 4);
1295 }
1296}