blob: d9a55af08a69621122ef5178a6ea695b5a25ed17 [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.
66 bool hasLandingPads = !MMI->getLandingPads().empty();
Reid Kleckner0e288232015-08-27 23:27:47 +000067 bool hasEHFunclets = MMI->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.
129 if (!isFuncletEHPersonality(Per))
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000130 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000131
David Majnemera80c1512015-09-29 20:12:33 +0000132 endFunclet();
133
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000134 // endFunclet will emit the necessary .xdata tables for x64 SEH.
135 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
136 return;
137
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000138 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000139 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000140
Reid Kleckner97837b72016-05-02 23:22:18 +0000141 // Just switch sections to the right xdata section.
142 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
143 Asm->OutStreamer->getCurrentSectionOnly());
David Majnemera80c1512015-09-29 20:12:33 +0000144 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000145
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000146 // Emit the tables appropriate to the personality function in use. If we
147 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000148 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000149 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000150 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000151 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000152 else if (Per == EHPersonality::MSVC_CXX)
153 emitCXXFrameHandler3Table(MF);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000154 else if (Per == EHPersonality::CoreCLR)
155 emitCLRExceptionTable(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000156 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000157 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000158
Lang Hames9ff69c82015-04-24 19:11:51 +0000159 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000160 }
David Majnemera80c1512015-09-29 20:12:33 +0000161}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000162
David Majnemer99c1d132015-10-12 16:44:22 +0000163/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000164static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
165 const MachineBasicBlock *MBB) {
166 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000167 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000168
David Majnemerbfa5b982015-10-10 00:04:29 +0000169 assert(MBB->isEHFuncletEntry());
170
171 // Give catches and cleanups a name based off of their parent function and
172 // their funclet entry block's number.
173 const MachineFunction *MF = MBB->getParent();
174 const Function *F = MF->getFunction();
175 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
176 MCContext &Ctx = MF->getContext();
177 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
178 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
179 Twine(MBB->getNumber()) + "@?0?" +
180 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000181}
182
183void WinException::beginFunclet(const MachineBasicBlock &MBB,
184 MCSymbol *Sym) {
185 CurrentFuncletEntry = &MBB;
186
187 const Function *F = Asm->MF->getFunction();
188 // If a symbol was not provided for the funclet, invent one.
189 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000190 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000191
192 // Describe our funclet symbol as a function with internal linkage.
193 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
194 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
195 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
196 << COFF::SCT_COMPLEX_TYPE_SHIFT);
197 Asm->OutStreamer->EndCOFFSymbolDef();
198
199 // We want our funclet's entry point to be aligned such that no nops will be
200 // present after the label.
201 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
202 F);
203
204 // Now that we've emitted the alignment directive, point at our funclet.
205 Asm->OutStreamer->EmitLabel(Sym);
206 }
207
208 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000209 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000210 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
211
212 if (shouldEmitPersonality) {
213 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
214 const Function *PerFn = nullptr;
215
216 // Determine which personality routine we are using for this funclet.
217 if (F->hasPersonalityFn())
218 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
219 const MCSymbol *PersHandlerSym =
Eric Christopher4367c7f2016-09-16 07:33:15 +0000220 TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
David Majnemera80c1512015-09-29 20:12:33 +0000221
222 // Classify the personality routine so that we may reason about it.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000223 EHPersonality Per = classifyEHPersonality(PerFn);
David Majnemera80c1512015-09-29 20:12:33 +0000224
225 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
226 if (Per != EHPersonality::MSVC_CXX ||
227 !CurrentFuncletEntry->isCleanupFuncletEntry())
228 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
229 }
230}
231
232void WinException::endFunclet() {
233 // No funclet to process? Great, we have nothing to do.
234 if (!CurrentFuncletEntry)
235 return;
236
237 if (shouldEmitMoves || shouldEmitPersonality) {
238 const Function *F = Asm->MF->getFunction();
239 EHPersonality Per = EHPersonality::Unknown;
240 if (F->hasPersonalityFn())
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000241 Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
David Majnemera80c1512015-09-29 20:12:33 +0000242
243 // The .seh_handlerdata directive implicitly switches section, push the
244 // current section so that we may return to it.
245 Asm->OutStreamer->PushSection();
246
247 // Emit an UNWIND_INFO struct describing the prologue.
248 Asm->OutStreamer->EmitWinEHHandlerData();
249
David Majnemera80c1512015-09-29 20:12:33 +0000250 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
251 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000252 // If this is a C++ catch funclet (or the parent function),
253 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000254 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
255 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
256 Twine("$cppxdata$", FuncLinkageName));
257 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000258 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
259 !CurrentFuncletEntry->isEHFuncletEntry()) {
260 // If this is the parent function in Win64 SEH, emit the LSDA immediately
261 // following .seh_handlerdata.
262 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000263 }
264
265 // Switch back to the previous section now that we are done writing to
266 // .xdata.
267 Asm->OutStreamer->PopSection();
268
269 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000270 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000271 }
272
273 // Let's make sure we don't try to end the same funclet twice.
274 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000275}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000276
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000277const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000278 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000279 return MCConstantExpr::create(0, Asm->OutContext);
280 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000281 ? MCSymbolRefExpr::VK_COFF_IMGREL32
282 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000283 Asm->OutContext);
284}
285
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000286const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
287 if (!GV)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000288 return MCConstantExpr::create(0, Asm->OutContext);
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000289 return create32bitRef(Asm->getSymbol(GV));
David Majnemercde33032015-03-30 22:58:10 +0000290}
291
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000292const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000293 return MCBinaryExpr::createAdd(create32bitRef(Label),
294 MCConstantExpr::create(1, Asm->OutContext),
295 Asm->OutContext);
296}
297
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000298const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
299 const MCSymbol *OffsetFrom) {
300 return MCBinaryExpr::createSub(
301 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
302 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
303}
304
305const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
306 const MCSymbol *OffsetFrom) {
307 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
308 MCConstantExpr::create(1, Asm->OutContext),
309 Asm->OutContext);
310}
311
Reid Klecknerc20276d2015-11-17 21:10:25 +0000312int WinException::getFrameIndexOffset(int FrameIndex,
313 const WinEHFuncInfo &FuncInfo) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000314 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
315 unsigned UnusedReg;
Sanjoy Das0ebc9612016-06-16 18:54:06 +0000316 if (Asm->MAI->usesWindowsCFI()) {
317 int Offset =
318 TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
319 /*IgnoreSPUpdates*/ true);
320 assert(UnusedReg ==
321 Asm->MF->getSubtarget()
322 .getTargetLowering()
323 ->getStackPointerRegisterToSaveRestore());
324 return Offset;
325 }
326
Reid Kleckner6ddae312015-11-05 21:09:49 +0000327 // For 32-bit, offsets should be relative to the end of the EH registration
328 // node. For 64-bit, it's relative to SP at the end of the prologue.
329 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
330 int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
331 Offset += FuncInfo.EHRegNodeEndOffset;
332 return Offset;
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000333}
334
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000335namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000336
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000337/// Top-level state used to represent unwind to caller
338const int NullState = -1;
339
340struct InvokeStateChange {
341 /// EH Label immediately after the last invoke in the previous state, or
342 /// nullptr if the previous state was the null state.
343 const MCSymbol *PreviousEndLabel;
344
345 /// EH label immediately before the first invoke in the new state, or nullptr
346 /// if the new state is the null state.
347 const MCSymbol *NewStartLabel;
348
349 /// State of the invoke following NewStartLabel, or NullState to indicate
350 /// the presence of calls which may unwind to caller.
351 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000352};
353
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000354/// Iterator that reports all the invoke state changes in a range of machine
355/// basic blocks. Changes to the null state are reported whenever a call that
356/// may unwind to caller is encountered. The MBB range is expected to be an
357/// entire function or funclet, and the start and end of the range are treated
358/// as being in the NullState even if there's not an unwind-to-caller call
359/// before the first invoke or after the last one (i.e., the first state change
360/// reported is the first change to something other than NullState, and a
361/// change back to NullState is always reported at the end of iteration).
362class InvokeStateChangeIterator {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000363 InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000364 MachineFunction::const_iterator MFI,
365 MachineFunction::const_iterator MFE,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000366 MachineBasicBlock::const_iterator MBBI,
367 int BaseState)
368 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000369 LastStateChange.PreviousEndLabel = nullptr;
370 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000371 LastStateChange.NewState = BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000372 scan();
373 }
374
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000375public:
376 static iterator_range<InvokeStateChangeIterator>
Reid Klecknerc20276d2015-11-17 21:10:25 +0000377 range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000378 MachineFunction::const_iterator End, int BaseState = NullState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000379 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
380 // the end of the last block.
381 assert(Begin != End);
382 auto BlockBegin = Begin->begin();
383 auto BlockEnd = std::prev(End)->end();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000384 return make_range(
385 InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
386 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000387 }
388
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000389 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000390 bool operator==(const InvokeStateChangeIterator &O) const {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000391 assert(BaseState == O.BaseState);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000392 // Must be visiting same block.
393 if (MFI != O.MFI)
394 return false;
395 // Must be visiting same isntr.
396 if (MBBI != O.MBBI)
397 return false;
398 // At end of block/instr iteration, we can still have two distinct states:
399 // one to report the final EndLabel, and another indicating the end of the
400 // state change iteration. Check for CurrentEndLabel equality to
401 // distinguish these.
402 return CurrentEndLabel == O.CurrentEndLabel;
403 }
404
405 bool operator!=(const InvokeStateChangeIterator &O) const {
406 return !operator==(O);
407 }
408 InvokeStateChange &operator*() { return LastStateChange; }
409 InvokeStateChange *operator->() { return &LastStateChange; }
410 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000411
412private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000413 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000414
Reid Klecknerc20276d2015-11-17 21:10:25 +0000415 const WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000416 const MCSymbol *CurrentEndLabel = nullptr;
417 MachineFunction::const_iterator MFI;
418 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000419 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000420 InvokeStateChange LastStateChange;
421 bool VisitingInvoke = false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000422 int BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000423};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000424
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000425} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000426
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000427InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
428 bool IsNewBlock = false;
429 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
430 if (IsNewBlock)
431 MBBI = MFI->begin();
432 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
433 const MachineInstr &MI = *MBBI;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000434 if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000435 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
436 // Indicate a change of state to the null state. We don't have
437 // start/end EH labels handy but the caller won't expect them for
438 // null state regions.
439 LastStateChange.PreviousEndLabel = CurrentEndLabel;
440 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000441 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000442 CurrentEndLabel = nullptr;
443 // Don't re-visit this instr on the next scan
444 ++MBBI;
445 return *this;
446 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000447
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000448 // All other state changes are at EH labels before/after invokes.
449 if (!MI.isEHLabel())
450 continue;
451 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
452 if (Label == CurrentEndLabel) {
453 VisitingInvoke = false;
454 continue;
455 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000456 auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000457 // Ignore EH labels that aren't the ones inserted before an invoke
David Majnemer8a1c45d2015-12-12 05:38:55 +0000458 if (InvokeMapIter == EHInfo.LabelToStateMap.end())
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000459 continue;
460 auto &StateAndEnd = InvokeMapIter->second;
461 int NewState = StateAndEnd.first;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000462 // Keep track of the fact that we're between EH start/end labels so
463 // we know not to treat the inoke we'll see as unwinding to caller.
464 VisitingInvoke = true;
465 if (NewState == LastStateChange.NewState) {
466 // The state isn't actually changing here. Record the new end and
467 // keep going.
468 CurrentEndLabel = StateAndEnd.second;
469 continue;
470 }
471 // Found a state change to report
472 LastStateChange.PreviousEndLabel = CurrentEndLabel;
473 LastStateChange.NewStartLabel = Label;
474 LastStateChange.NewState = NewState;
475 // Start keeping track of the new current end
476 CurrentEndLabel = StateAndEnd.second;
477 // Don't re-visit this instr on the next scan
478 ++MBBI;
479 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000480 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000481 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000482 // Iteration hit the end of the block range.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000483 if (LastStateChange.NewState != BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000484 // Report the end of the last new state
485 LastStateChange.PreviousEndLabel = CurrentEndLabel;
486 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000487 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000488 // Leave CurrentEndLabel non-null to distinguish this state from end.
489 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000490 return *this;
491 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000492 // We've reported all state changes and hit the end state.
493 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000494 return *this;
495}
496
Reid Kleckner0a57f652015-01-14 01:05:27 +0000497/// Emit the language-specific data that __C_specific_handler expects. This
498/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
499/// up after faults with __try, __except, and __finally. The typeinfo values
500/// are not really RTTI data, but pointers to filter functions that return an
501/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
502/// blocks and other cleanups, the landing pad label is zero, and the filter
503/// function is actually a cleanup handler with the same prototype. A catch-all
504/// entry is modeled with a null filter function field and a non-zero landing
505/// pad label.
506///
507/// Possible filter function return values:
508/// EXCEPTION_EXECUTE_HANDLER (1):
509/// Jump to the landing pad label after cleanups.
510/// EXCEPTION_CONTINUE_SEARCH (0):
511/// Continue searching this table or continue unwinding.
512/// EXCEPTION_CONTINUE_EXECUTION (-1):
513/// Resume execution at the trapping PC.
514///
515/// Inferred table structure:
516/// struct Table {
517/// int NumEntries;
518/// struct Entry {
519/// imagerel32 LabelStart;
520/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000521/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000522/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000523/// } Entries[NumEntries];
524/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000525void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000526 auto &OS = *Asm->OutStreamer;
527 MCContext &Ctx = Asm->OutContext;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000528 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000529
David Majnemer081e8fe2015-12-27 06:07:12 +0000530 bool VerboseAsm = OS.isVerboseAsm();
531 auto AddComment = [&](const Twine &Comment) {
532 if (VerboseAsm)
533 OS.AddComment(Comment);
534 };
535
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000536 // Emit a label assignment with the SEH frame offset so we can use it for
537 // llvm.x86.seh.recoverfp.
538 StringRef FLinkageName =
539 GlobalValue::getRealLinkageName(MF->getFunction()->getName());
540 MCSymbol *ParentFrameOffset =
541 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
542 const MCExpr *MCOffset =
543 MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
544 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
545
Reid Kleckner14e77352015-10-09 23:34:53 +0000546 // Use the assembler to compute the number of table entries through label
547 // difference and division.
548 MCSymbol *TableBegin =
549 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
550 MCSymbol *TableEnd =
551 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000552 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
Reid Kleckner14e77352015-10-09 23:34:53 +0000553 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
554 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
David Majnemer081e8fe2015-12-27 06:07:12 +0000555 AddComment("Number of call sites");
Reid Kleckner14e77352015-10-09 23:34:53 +0000556 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000557
Reid Kleckner14e77352015-10-09 23:34:53 +0000558 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000559
Reid Kleckner14e77352015-10-09 23:34:53 +0000560 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
561 // models exceptions from invokes. LLVM also allows arbitrary reordering of
562 // the code, so our tables end up looking a bit different. Rather than
563 // trying to match MSVC's tables exactly, we emit a denormalized table. For
564 // each range of invokes in the same state, we emit table entries for all
565 // the actions that would be taken in that state. This means our tables are
566 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000567 const MCSymbol *LastStartLabel = nullptr;
568 int LastEHState = -1;
569 // Break out before we enter into a finally funclet.
570 // FIXME: We need to emit separate EH tables for cleanups.
571 MachineFunction::const_iterator End = MF->end();
572 MachineFunction::const_iterator Stop = std::next(MF->begin());
573 while (Stop != End && !Stop->isEHFuncletEntry())
574 ++Stop;
575 for (const auto &StateChange :
576 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
577 // Emit all the actions for the state we just transitioned out of
578 // if it was not the null state
579 if (LastEHState != -1)
580 emitSEHActionsForRange(FuncInfo, LastStartLabel,
581 StateChange.PreviousEndLabel, LastEHState);
582 LastStartLabel = StateChange.NewStartLabel;
583 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000584 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000585
Reid Kleckner14e77352015-10-09 23:34:53 +0000586 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000587}
David Majnemercde33032015-03-30 22:58:10 +0000588
Reid Klecknerc20276d2015-11-17 21:10:25 +0000589void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000590 const MCSymbol *BeginLabel,
591 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000592 auto &OS = *Asm->OutStreamer;
593 MCContext &Ctx = Asm->OutContext;
594
David Majnemer081e8fe2015-12-27 06:07:12 +0000595 bool VerboseAsm = OS.isVerboseAsm();
596 auto AddComment = [&](const Twine &Comment) {
597 if (VerboseAsm)
598 OS.AddComment(Comment);
599 };
600
Reid Klecknerd880dc72015-10-09 20:39:39 +0000601 assert(BeginLabel && EndLabel);
602 while (State != -1) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000603 const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
Reid Klecknerd880dc72015-10-09 20:39:39 +0000604 const MCExpr *FilterOrFinally;
605 const MCExpr *ExceptOrNull;
606 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
607 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000608 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000609 ExceptOrNull = MCConstantExpr::create(0, Ctx);
610 } else {
611 // For an except, the filter can be 1 (catch-all) or a function
612 // label.
613 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
614 : MCConstantExpr::create(1, Ctx);
615 ExceptOrNull = create32bitRef(Handler->getSymbol());
616 }
617
David Majnemer081e8fe2015-12-27 06:07:12 +0000618 AddComment("LabelStart");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000619 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000620 AddComment("LabelEnd");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000621 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000622 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
623 : "CatchAll");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000624 OS.EmitValue(FilterOrFinally, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000625 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000626 OS.EmitValue(ExceptOrNull, 4);
627
628 assert(UME.ToState < State && "states should decrease");
629 State = UME.ToState;
630 }
631}
632
Reid Kleckner60b640b2015-05-28 22:47:01 +0000633void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000634 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000635 auto &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000636 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
David Majnemercde33032015-03-30 22:58:10 +0000637
Reid Kleckner813f1b62015-09-16 22:14:46 +0000638 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000639
Reid Klecknerc71d6272015-09-28 23:56:30 +0000640 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000641 MCSymbol *FuncInfoXData = nullptr;
642 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000643 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
644 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000645 FuncInfoXData =
646 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000647 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000648 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000649 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000650 }
651
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000652 int UnwindHelpOffset = 0;
653 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner6ddae312015-11-05 21:09:49 +0000654 UnwindHelpOffset =
655 getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000656
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000657 MCSymbol *UnwindMapXData = nullptr;
658 MCSymbol *TryBlockMapXData = nullptr;
659 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000660 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000661 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000662 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000663 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000664 TryBlockMapXData =
665 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000666 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000667 IPToStateXData =
668 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000669
David Majnemer081e8fe2015-12-27 06:07:12 +0000670 bool VerboseAsm = OS.isVerboseAsm();
671 auto AddComment = [&](const Twine &Comment) {
672 if (VerboseAsm)
673 OS.AddComment(Comment);
674 };
675
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000676 // FuncInfo {
677 // uint32_t MagicNumber
678 // int32_t MaxState;
679 // UnwindMapEntry *UnwindMap;
680 // uint32_t NumTryBlocks;
681 // TryBlockMapEntry *TryBlockMap;
682 // uint32_t IPMapEntries; // always 0 for x86
683 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
684 // uint32_t UnwindHelp; // non-x86 only
685 // ESTypeList *ESTypeList;
686 // int32_t EHFlags;
687 // }
688 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
689 // EHFlags & 2 -> ???
690 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000691 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000692 OS.EmitLabel(FuncInfoXData);
David Majnemer081e8fe2015-12-27 06:07:12 +0000693
694 AddComment("MagicNumber");
695 OS.EmitIntValue(0x19930522, 4);
696
697 AddComment("MaxState");
698 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
699
700 AddComment("UnwindMap");
701 OS.EmitValue(create32bitRef(UnwindMapXData), 4);
702
703 AddComment("NumTryBlocks");
704 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
705
706 AddComment("TryBlockMap");
707 OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
708
709 AddComment("IPMapEntries");
710 OS.EmitIntValue(IPToStateTable.size(), 4);
711
712 AddComment("IPToStateXData");
713 OS.EmitValue(create32bitRef(IPToStateXData), 4);
714
715 if (Asm->MAI->usesWindowsCFI()) {
716 AddComment("UnwindHelp");
717 OS.EmitIntValue(UnwindHelpOffset, 4);
718 }
719
720 AddComment("ESTypeList");
721 OS.EmitIntValue(0, 4);
722
723 AddComment("EHFlags");
724 OS.EmitIntValue(1, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000725
726 // UnwindMapEntry {
727 // int32_t ToState;
728 // void (*Action)();
729 // };
730 if (UnwindMapXData) {
731 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000732 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000733 MCSymbol *CleanupSym =
734 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
David Majnemer081e8fe2015-12-27 06:07:12 +0000735 AddComment("ToState");
736 OS.EmitIntValue(UME.ToState, 4);
737
738 AddComment("Action");
739 OS.EmitValue(create32bitRef(CleanupSym), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000740 }
741 }
742
743 // TryBlockMap {
744 // int32_t TryLow;
745 // int32_t TryHigh;
746 // int32_t CatchHigh;
747 // int32_t NumCatches;
748 // HandlerType *HandlerArray;
749 // };
750 if (TryBlockMapXData) {
751 OS.EmitLabel(TryBlockMapXData);
752 SmallVector<MCSymbol *, 1> HandlerMaps;
753 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000754 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000755
Reid Kleckner813f1b62015-09-16 22:14:46 +0000756 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000757 if (!TBME.HandlerArray.empty())
758 HandlerMapXData =
759 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
760 .concat(Twine(I))
761 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000762 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000763 HandlerMaps.push_back(HandlerMapXData);
764
Reid Kleckner813f1b62015-09-16 22:14:46 +0000765 // TBMEs should form intervals.
766 assert(0 <= TBME.TryLow && "bad trymap interval");
767 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
768 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000769 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000770 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000771
David Majnemer081e8fe2015-12-27 06:07:12 +0000772 AddComment("TryLow");
773 OS.EmitIntValue(TBME.TryLow, 4);
774
775 AddComment("TryHigh");
776 OS.EmitIntValue(TBME.TryHigh, 4);
777
778 AddComment("CatchHigh");
779 OS.EmitIntValue(TBME.CatchHigh, 4);
780
781 AddComment("NumCatches");
782 OS.EmitIntValue(TBME.HandlerArray.size(), 4);
783
784 AddComment("HandlerArray");
785 OS.EmitValue(create32bitRef(HandlerMapXData), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000786 }
787
Reid Kleckner28e49032015-10-16 23:43:27 +0000788 // All funclets use the same parent frame offset currently.
789 unsigned ParentFrameOffset = 0;
790 if (shouldEmitPersonality) {
791 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
792 ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
793 }
794
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000795 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000796 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000797 MCSymbol *HandlerMapXData = HandlerMaps[I];
798 if (!HandlerMapXData)
799 continue;
800 // HandlerType {
801 // int32_t Adjectives;
802 // TypeDescriptor *Type;
803 // int32_t CatchObjOffset;
804 // void (*Handler)();
805 // int32_t ParentFrameOffset; // x64 only
806 // };
807 OS.EmitLabel(HandlerMapXData);
808 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
809 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000810 // the index is INT_MAX, then there is no catch object, and we should
811 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000812 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000813 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner6ddae312015-11-05 21:09:49 +0000814 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
David Majnemercb305de2016-03-01 04:30:16 +0000815 assert(Offset != 0 && "Illegal offset for catch object!");
Reid Klecknerb005d282015-09-16 20:16:27 +0000816 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000817 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000818 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000819 }
820
David Majnemerbfa5b982015-10-10 00:04:29 +0000821 MCSymbol *HandlerSym =
822 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000823
David Majnemer081e8fe2015-12-27 06:07:12 +0000824 AddComment("Adjectives");
825 OS.EmitIntValue(HT.Adjectives, 4);
826
827 AddComment("Type");
828 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
829
830 AddComment("CatchObjOffset");
831 OS.EmitValue(FrameAllocOffsetRef, 4);
832
833 AddComment("Handler");
834 OS.EmitValue(create32bitRef(HandlerSym), 4);
835
836 if (shouldEmitPersonality) {
837 AddComment("ParentFrameOffset");
838 OS.EmitIntValue(ParentFrameOffset, 4);
839 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000840 }
841 }
842 }
843
844 // IPToStateMapEntry {
845 // void *IP;
846 // int32_t State;
847 // };
848 if (IPToStateXData) {
849 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000850 for (auto &IPStatePair : IPToStateTable) {
David Majnemer081e8fe2015-12-27 06:07:12 +0000851 AddComment("IP");
852 OS.EmitValue(IPStatePair.first, 4);
853 AddComment("ToState");
854 OS.EmitIntValue(IPStatePair.second, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000855 }
856 }
857}
858
Reid Klecknerc71d6272015-09-28 23:56:30 +0000859void WinException::computeIP2StateTable(
Reid Klecknerc20276d2015-11-17 21:10:25 +0000860 const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
Reid Klecknerc71d6272015-09-28 23:56:30 +0000861 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000862
David Majnemer8a1c45d2015-12-12 05:38:55 +0000863 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
864 FuncletEnd = MF->begin(),
865 End = MF->end();
866 FuncletStart != End; FuncletStart = FuncletEnd) {
867 // Find the end of the funclet
868 while (++FuncletEnd != End) {
869 if (FuncletEnd->isEHFuncletEntry()) {
870 break;
871 }
872 }
873
874 // Don't emit ip2state entries for cleanup funclets. Any interesting
875 // exceptional actions in cleanups must be handled in a separate IR
876 // function.
877 if (FuncletStart->isCleanupFuncletEntry())
878 continue;
879
880 MCSymbol *StartLabel;
881 int BaseState;
882 if (FuncletStart == MF->begin()) {
883 BaseState = NullState;
884 StartLabel = Asm->getFunctionBegin();
885 } else {
886 auto *FuncletPad =
887 cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
888 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
889 BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
890 StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
891 }
892 assert(StartLabel && "need local function start label");
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000893 IPToStateTable.push_back(
David Majnemer8a1c45d2015-12-12 05:38:55 +0000894 std::make_pair(create32bitRef(StartLabel), BaseState));
895
896 for (const auto &StateChange : InvokeStateChangeIterator::range(
897 FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
898 // Compute the label to report as the start of this entry; use the EH
899 // start label for the invoke if we have one, otherwise (this is a call
900 // which may unwind to our caller and does not have an EH start label, so)
901 // use the previous end label.
902 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
903 if (!ChangeLabel)
904 ChangeLabel = StateChange.PreviousEndLabel;
905 // Emit an entry indicating that PCs after 'Label' have this EH state.
906 IPToStateTable.push_back(
907 std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
908 // FIXME: assert that NewState is between CatchLow and CatchHigh.
909 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000910 }
David Majnemercde33032015-03-30 22:58:10 +0000911}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000912
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000913void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
914 StringRef FLinkageName) {
915 // Outlined helpers called by the EH runtime need to know the offset of the EH
916 // registration in order to recover the parent frame pointer. Now that we know
917 // we've code generated the parent, we can emit the label assignment that
918 // those helpers use to get the offset of the registration node.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000919
920 // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
921 // after optimization all the invokes were eliminated. We still need to emit
922 // the parent frame offset label, but it should be garbage and should never be
923 // used.
924 int64_t Offset = 0;
925 int FI = FuncInfo.EHRegNodeFrameIndex;
926 if (FI != INT_MAX) {
927 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
928 unsigned UnusedReg;
929 Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
930 }
931
Reid Klecknerc20276d2015-11-17 21:10:25 +0000932 MCContext &Ctx = Asm->OutContext;
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000933 MCSymbol *ParentFrameOffset =
Reid Klecknerc20276d2015-11-17 21:10:25 +0000934 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000935 Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
936 MCConstantExpr::create(Offset, Ctx));
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000937}
938
Reid Klecknerf12c0302015-06-09 21:42:19 +0000939/// Emit the language-specific data that _except_handler3 and 4 expect. This is
940/// functionally equivalent to the __C_specific_handler table, except it is
941/// indexed by state number instead of IP.
942void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000943 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000944 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000945 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000946
David Majnemer081e8fe2015-12-27 06:07:12 +0000947 bool VerboseAsm = OS.isVerboseAsm();
948 auto AddComment = [&](const Twine &Comment) {
949 if (VerboseAsm)
950 OS.AddComment(Comment);
951 };
952
Reid Klecknerc20276d2015-11-17 21:10:25 +0000953 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000954 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000955
956 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000957 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000958 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000959 OS.EmitLabel(LSDALabel);
960
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000961 const Function *Per =
962 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000963 StringRef PerName = Per->getName();
964 int BaseState = -1;
965 if (PerName == "_except_handler4") {
966 // The LSDA for _except_handler4 starts with this struct, followed by the
967 // scope table:
968 //
969 // struct EH4ScopeTable {
970 // int32_t GSCookieOffset;
971 // int32_t GSCookieXOROffset;
972 // int32_t EHCookieOffset;
973 // int32_t EHCookieXOROffset;
974 // ScopeTableEntry ScopeRecord[];
975 // };
976 //
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000977 // Offsets are %ebp relative.
978 //
979 // The GS cookie is present only if the function needs stack protection.
980 // GSCookieOffset = -2 means that GS cookie is not used.
981 //
982 // The EH cookie is always present.
983 //
984 // Check is done the following way:
985 // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
986
987 // Retrieve the Guard Stack slot.
988 int GSCookieOffset = -2;
Matthias Braun941a7052016-07-28 18:40:00 +0000989 const MachineFrameInfo &MFI = MF->getFrameInfo();
990 if (MFI.hasStackProtectorIndex()) {
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000991 unsigned UnusedReg;
992 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +0000993 int SSPIdx = MFI.getStackProtectorIndex();
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000994 GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
995 }
996
997 // Retrieve the EH Guard slot.
998 // TODO(etienneb): Get rid of this value and change it for and assertion.
999 int EHCookieOffset = 9999;
1000 if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1001 unsigned UnusedReg;
1002 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1003 int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1004 EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
1005 }
1006
David Majnemer081e8fe2015-12-27 06:07:12 +00001007 AddComment("GSCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001008 OS.EmitIntValue(GSCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001009 AddComment("GSCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001010 OS.EmitIntValue(0, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001011 AddComment("EHCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001012 OS.EmitIntValue(EHCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001013 AddComment("EHCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001014 OS.EmitIntValue(0, 4);
1015 BaseState = -2;
1016 }
1017
Reid Kleckner14e77352015-10-09 23:34:53 +00001018 assert(!FuncInfo.SEHUnwindMap.empty());
Reid Klecknerc20276d2015-11-17 21:10:25 +00001019 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
David Majnemer081e8fe2015-12-27 06:07:12 +00001020 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1021 const MCSymbol *ExceptOrFinally =
1022 UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
Reid Kleckner14e77352015-10-09 23:34:53 +00001023 // -1 is usually the base state for "unwind to caller", but for
1024 // _except_handler4 it's -2. Do that replacement here if necessary.
1025 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
David Majnemer081e8fe2015-12-27 06:07:12 +00001026 AddComment("ToState");
1027 OS.EmitIntValue(ToState, 4);
1028 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1029 OS.EmitValue(create32bitRef(UME.Filter), 4);
1030 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1031 OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001032 }
1033}
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001034
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001035static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001036 int Rank = 0;
1037 while (State != -1) {
1038 ++Rank;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001039 State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001040 }
1041 return Rank;
1042}
1043
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001044static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1045 int LeftRank = getTryRank(FuncInfo, Left);
1046 int RightRank = getTryRank(FuncInfo, Right);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001047
1048 while (LeftRank < RightRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001049 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001050 --RightRank;
1051 }
1052
1053 while (RightRank < LeftRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001054 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001055 --LeftRank;
1056 }
1057
1058 while (Left != Right) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001059 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1060 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001061 }
1062
1063 return Left;
1064}
1065
1066void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1067 // CLR EH "states" are really just IDs that identify handlers/funclets;
1068 // states, handlers, and funclets all have 1:1 mappings between them, and a
1069 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1070 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +00001071 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001072 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1073 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1074
1075 // A ClrClause describes a protected region.
1076 struct ClrClause {
1077 const MCSymbol *StartLabel; // Start of protected region
1078 const MCSymbol *EndLabel; // End of protected region
1079 int State; // Index of handler protecting the protected region
1080 int EnclosingState; // Index of funclet enclosing the protected region
1081 };
1082 SmallVector<ClrClause, 8> Clauses;
1083
1084 // Build a map from handler MBBs to their corresponding states (i.e. their
1085 // indices in the ClrEHUnwindMap).
1086 int NumStates = FuncInfo.ClrEHUnwindMap.size();
1087 assert(NumStates > 0 && "Don't need exception table!");
1088 DenseMap<const MachineBasicBlock *, int> HandlerStates;
1089 for (int State = 0; State < NumStates; ++State) {
1090 MachineBasicBlock *HandlerBlock =
1091 FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1092 HandlerStates[HandlerBlock] = State;
1093 // Use this loop through all handlers to verify our assumption (used in
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001094 // the MinEnclosingState computation) that enclosing funclets have lower
1095 // state numbers than their enclosed funclets.
1096 assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001097 "ill-formed state numbering");
1098 }
1099 // Map the main function to the NullState.
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001100 HandlerStates[&MF->front()] = NullState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001101
1102 // Write out a sentinel indicating the end of the standard (Windows) xdata
1103 // and the start of the additional (CLR) info.
1104 OS.EmitIntValue(0xffffffff, 4);
1105 // Write out the number of funclets
1106 OS.EmitIntValue(NumStates, 4);
1107
1108 // Walk the machine blocks/instrs, computing and emitting a few things:
1109 // 1. Emit a list of the offsets to each handler entry, in lexical order.
1110 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1111 // 3. Compute the list of ClrClauses, in the required order (inner before
1112 // outer, earlier before later; the order by which a forward scan with
1113 // early termination will find the innermost enclosing clause covering
1114 // a given address).
1115 // 4. A map (MinClauseMap) from each handler index to the index of the
1116 // outermost funclet/function which contains a try clause targeting the
1117 // key handler. This will be used to determine IsDuplicate-ness when
1118 // emitting ClrClauses. The NullState value is used to indicate that the
1119 // top-level function contains a try clause targeting the key handler.
1120 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1121 // try regions we entered before entering the PendingState try but which
1122 // we haven't yet exited.
1123 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1124 // EndSymbolMap and MinClauseMap are maps described above.
1125 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1126 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1127
1128 // Visit the root function and each funclet.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001129 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1130 FuncletEnd = MF->begin(),
1131 End = MF->end();
1132 FuncletStart != End; FuncletStart = FuncletEnd) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001133 int FuncletState = HandlerStates[&*FuncletStart];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001134 // Find the end of the funclet
1135 MCSymbol *EndSymbol = FuncEndSym;
1136 while (++FuncletEnd != End) {
1137 if (FuncletEnd->isEHFuncletEntry()) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001138 EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001139 break;
1140 }
1141 }
1142 // Emit the function/funclet end and, if this is a funclet (and not the
1143 // root function), record it in the EndSymbolMap.
1144 OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1145 if (FuncletState != NullState) {
1146 // Record the end of the handler.
1147 EndSymbolMap[FuncletState] = EndSymbol;
1148 }
1149
1150 // Walk the state changes in this function/funclet and compute its clauses.
1151 // Funclets always start in the null state.
1152 const MCSymbol *CurrentStartLabel = nullptr;
1153 int CurrentState = NullState;
1154 assert(HandlerStack.empty());
1155 for (const auto &StateChange :
1156 InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1157 // Close any try regions we're not still under
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001158 int StillPendingState =
1159 getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1160 while (CurrentState != StillPendingState) {
1161 assert(CurrentState != NullState &&
1162 "Failed to find still-pending state!");
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001163 // Close the pending clause
1164 Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1165 CurrentState, FuncletState});
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001166 // Now the next-outer try region is current
1167 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001168 // Pop the new start label from the handler stack if we've exited all
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001169 // inner try regions of the corresponding try region.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001170 if (HandlerStack.back().second == CurrentState)
1171 CurrentStartLabel = HandlerStack.pop_back_val().first;
1172 }
1173
1174 if (StateChange.NewState != CurrentState) {
1175 // For each clause we're starting, update the MinClauseMap so we can
1176 // know which is the topmost funclet containing a clause targeting
1177 // it.
1178 for (int EnteredState = StateChange.NewState;
1179 EnteredState != CurrentState;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001180 EnteredState =
1181 FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001182 int &MinEnclosingState = MinClauseMap[EnteredState];
1183 if (FuncletState < MinEnclosingState)
1184 MinEnclosingState = FuncletState;
1185 }
1186 // Save the previous current start/label on the stack and update to
1187 // the newly-current start/state.
1188 HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1189 CurrentStartLabel = StateChange.NewStartLabel;
1190 CurrentState = StateChange.NewState;
1191 }
1192 }
1193 assert(HandlerStack.empty());
1194 }
1195
1196 // Now emit the clause info, starting with the number of clauses.
1197 OS.EmitIntValue(Clauses.size(), 4);
1198 for (ClrClause &Clause : Clauses) {
1199 // Emit a CORINFO_EH_CLAUSE :
1200 /*
1201 struct CORINFO_EH_CLAUSE
1202 {
1203 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1204 DWORD TryOffset;
1205 DWORD TryLength; // actually TryEndOffset
1206 DWORD HandlerOffset;
1207 DWORD HandlerLength; // actually HandlerEndOffset
1208 union
1209 {
1210 DWORD ClassToken; // use for catch clauses
1211 DWORD FilterOffset; // use for filter clauses
1212 };
1213 };
1214
1215 enum CORINFO_EH_CLAUSE_FLAGS
1216 {
1217 CORINFO_EH_CLAUSE_NONE = 0,
1218 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1219 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1220 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1221 };
1222 typedef enum CorExceptionFlag
1223 {
1224 COR_ILEXCEPTION_CLAUSE_NONE,
1225 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1226 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1227 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1228 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1229 // clause was duplicated
1230 // to a funclet which was
1231 // pulled out of line
1232 } CorExceptionFlag;
1233 */
1234 // Add 1 to the start/end of the EH clause; the IP associated with a
1235 // call when the runtime does its scan is the IP of the next instruction
1236 // (the one to which control will return after the call), so we need
1237 // to add 1 to the end of the clause to cover that offset. We also add
1238 // 1 to the start of the clause to make sure that the ranges reported
1239 // for all clauses are disjoint. Note that we'll need some additional
1240 // logic when machine traps are supported, since in that case the IP
1241 // that the runtime uses is the offset of the faulting instruction
1242 // itself; if such an instruction immediately follows a call but the
1243 // two belong to different clauses, we'll need to insert a nop between
1244 // them so the runtime can distinguish the point to which the call will
1245 // return from the point at which the fault occurs.
1246
1247 const MCExpr *ClauseBegin =
1248 getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1249 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1250
Reid Klecknerc20276d2015-11-17 21:10:25 +00001251 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001252 MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1253 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1254 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1255 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1256 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1257
1258 uint32_t Flags = 0;
1259 switch (Entry.HandlerType) {
1260 case ClrHandlerType::Catch:
1261 // Leaving bits 0-2 clear indicates catch.
1262 break;
1263 case ClrHandlerType::Filter:
1264 Flags |= 1;
1265 break;
1266 case ClrHandlerType::Finally:
1267 Flags |= 2;
1268 break;
1269 case ClrHandlerType::Fault:
1270 Flags |= 4;
1271 break;
1272 }
1273 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1274 // This is a "duplicate" clause; the handler needs to be entered from a
1275 // frame above the one holding the invoke.
1276 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1277 Flags |= 8;
1278 }
1279 OS.EmitIntValue(Flags, 4);
1280
1281 // Write the clause start/end
1282 OS.EmitValue(ClauseBegin, 4);
1283 OS.EmitValue(ClauseEnd, 4);
1284
1285 // Write out the handler start/end
1286 OS.EmitValue(HandlerBegin, 4);
1287 OS.EmitValue(HandlerEnd, 4);
1288
1289 // Write out the type token or filter offset
1290 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1291 OS.EmitIntValue(Entry.TypeToken, 4);
1292 }
1293}