blob: e5933d8d4160c041e3a5c5966d37fdcd6255f041 [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();
Reid Kleckner9a1a9192015-07-13 20:41:46 +000075 const Function *Per = nullptr;
76 if (F->hasPersonalityFn())
77 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Charles Davis5638b9f2011-05-28 04:21:04 +000078
Keno Fischeraff703a2015-07-14 19:22:51 +000079 bool forceEmitPersonality =
80 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
81 F->needsUnwindTableEntry();
82
Reid Kleckner0e288232015-08-27 23:27:47 +000083 shouldEmitPersonality =
84 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
85 PerEncoding != dwarf::DW_EH_PE_omit && Per);
Charles Davis5638b9f2011-05-28 04:21:04 +000086
87 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
88 shouldEmitLSDA = shouldEmitPersonality &&
89 LSDAEncoding != dwarf::DW_EH_PE_omit;
90
Reid Kleckner0e288232015-08-27 23:27:47 +000091 // If we're not using CFI, we don't want the CFI or the personality, but we
92 // might want EH tables if we had EH pads.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000093 if (!Asm->MAI->usesWindowsCFI()) {
David Majnemerbfa5b982015-10-10 00:04:29 +000094 shouldEmitLSDA = hasEHFunclets;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000095 shouldEmitPersonality = false;
96 return;
97 }
David Majnemera225a192015-03-31 22:35:44 +000098
David Majnemera80c1512015-09-29 20:12:33 +000099 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000100}
101
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000102/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000103///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000104void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000105 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000106 return;
107
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000108 const Function *F = MF->getFunction();
109 EHPersonality Per = EHPersonality::Unknown;
110 if (F->hasPersonalityFn())
111 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000112
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000113 // Get rid of any dead landing pads if we're not using funclets. In funclet
114 // schemes, the landing pad is not actually reachable. It only exists so
115 // that we can emit the right table data.
116 if (!isFuncletEHPersonality(Per))
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000117 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000118
David Majnemera80c1512015-09-29 20:12:33 +0000119 endFunclet();
120
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000121 // endFunclet will emit the necessary .xdata tables for x64 SEH.
122 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
123 return;
124
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000125 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000126 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000127
Reid Kleckner97837b72016-05-02 23:22:18 +0000128 // Just switch sections to the right xdata section.
129 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
130 Asm->OutStreamer->getCurrentSectionOnly());
David Majnemera80c1512015-09-29 20:12:33 +0000131 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000132
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000133 // Emit the tables appropriate to the personality function in use. If we
134 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000135 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000136 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000137 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000138 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000139 else if (Per == EHPersonality::MSVC_CXX)
140 emitCXXFrameHandler3Table(MF);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000141 else if (Per == EHPersonality::CoreCLR)
142 emitCLRExceptionTable(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000143 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000144 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000145
Lang Hames9ff69c82015-04-24 19:11:51 +0000146 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000147 }
David Majnemera80c1512015-09-29 20:12:33 +0000148}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000149
David Majnemer99c1d132015-10-12 16:44:22 +0000150/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000151static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
152 const MachineBasicBlock *MBB) {
153 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000154 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000155
David Majnemerbfa5b982015-10-10 00:04:29 +0000156 assert(MBB->isEHFuncletEntry());
157
158 // Give catches and cleanups a name based off of their parent function and
159 // their funclet entry block's number.
160 const MachineFunction *MF = MBB->getParent();
161 const Function *F = MF->getFunction();
162 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
163 MCContext &Ctx = MF->getContext();
164 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
165 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
166 Twine(MBB->getNumber()) + "@?0?" +
167 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000168}
169
170void WinException::beginFunclet(const MachineBasicBlock &MBB,
171 MCSymbol *Sym) {
172 CurrentFuncletEntry = &MBB;
173
174 const Function *F = Asm->MF->getFunction();
175 // If a symbol was not provided for the funclet, invent one.
176 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000177 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000178
179 // Describe our funclet symbol as a function with internal linkage.
180 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
181 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
182 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
183 << COFF::SCT_COMPLEX_TYPE_SHIFT);
184 Asm->OutStreamer->EndCOFFSymbolDef();
185
186 // We want our funclet's entry point to be aligned such that no nops will be
187 // present after the label.
188 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
189 F);
190
191 // Now that we've emitted the alignment directive, point at our funclet.
192 Asm->OutStreamer->EmitLabel(Sym);
193 }
194
195 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000196 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000197 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
198
199 if (shouldEmitPersonality) {
200 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
201 const Function *PerFn = nullptr;
202
203 // Determine which personality routine we are using for this funclet.
204 if (F->hasPersonalityFn())
205 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
206 const MCSymbol *PersHandlerSym =
207 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
208
209 // Classify the personality routine so that we may reason about it.
210 EHPersonality Per = EHPersonality::Unknown;
211 if (F->hasPersonalityFn())
212 Per = classifyEHPersonality(F->getPersonalityFn());
213
214 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
215 if (Per != EHPersonality::MSVC_CXX ||
216 !CurrentFuncletEntry->isCleanupFuncletEntry())
217 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
218 }
219}
220
221void WinException::endFunclet() {
222 // No funclet to process? Great, we have nothing to do.
223 if (!CurrentFuncletEntry)
224 return;
225
226 if (shouldEmitMoves || shouldEmitPersonality) {
227 const Function *F = Asm->MF->getFunction();
228 EHPersonality Per = EHPersonality::Unknown;
229 if (F->hasPersonalityFn())
230 Per = classifyEHPersonality(F->getPersonalityFn());
231
232 // The .seh_handlerdata directive implicitly switches section, push the
233 // current section so that we may return to it.
234 Asm->OutStreamer->PushSection();
235
236 // Emit an UNWIND_INFO struct describing the prologue.
237 Asm->OutStreamer->EmitWinEHHandlerData();
238
David Majnemera80c1512015-09-29 20:12:33 +0000239 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
240 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000241 // If this is a C++ catch funclet (or the parent function),
242 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000243 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
244 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
245 Twine("$cppxdata$", FuncLinkageName));
246 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000247 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
248 !CurrentFuncletEntry->isEHFuncletEntry()) {
249 // If this is the parent function in Win64 SEH, emit the LSDA immediately
250 // following .seh_handlerdata.
251 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000252 }
253
254 // Switch back to the previous section now that we are done writing to
255 // .xdata.
256 Asm->OutStreamer->PopSection();
257
258 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000259 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000260 }
261
262 // Let's make sure we don't try to end the same funclet twice.
263 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000264}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000265
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000266const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000267 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000268 return MCConstantExpr::create(0, Asm->OutContext);
269 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000270 ? MCSymbolRefExpr::VK_COFF_IMGREL32
271 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000272 Asm->OutContext);
273}
274
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000275const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
276 if (!GV)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000277 return MCConstantExpr::create(0, Asm->OutContext);
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000278 return create32bitRef(Asm->getSymbol(GV));
David Majnemercde33032015-03-30 22:58:10 +0000279}
280
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000281const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000282 return MCBinaryExpr::createAdd(create32bitRef(Label),
283 MCConstantExpr::create(1, Asm->OutContext),
284 Asm->OutContext);
285}
286
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000287const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
288 const MCSymbol *OffsetFrom) {
289 return MCBinaryExpr::createSub(
290 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
291 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
292}
293
294const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
295 const MCSymbol *OffsetFrom) {
296 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
297 MCConstantExpr::create(1, Asm->OutContext),
298 Asm->OutContext);
299}
300
Reid Klecknerc20276d2015-11-17 21:10:25 +0000301int WinException::getFrameIndexOffset(int FrameIndex,
302 const WinEHFuncInfo &FuncInfo) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000303 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
304 unsigned UnusedReg;
Sanjoy Das0ebc9612016-06-16 18:54:06 +0000305 if (Asm->MAI->usesWindowsCFI()) {
306 int Offset =
307 TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
308 /*IgnoreSPUpdates*/ true);
309 assert(UnusedReg ==
310 Asm->MF->getSubtarget()
311 .getTargetLowering()
312 ->getStackPointerRegisterToSaveRestore());
313 return Offset;
314 }
315
Reid Kleckner6ddae312015-11-05 21:09:49 +0000316 // For 32-bit, offsets should be relative to the end of the EH registration
317 // node. For 64-bit, it's relative to SP at the end of the prologue.
318 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
319 int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
320 Offset += FuncInfo.EHRegNodeEndOffset;
321 return Offset;
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000322}
323
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000324namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000325
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000326/// Top-level state used to represent unwind to caller
327const int NullState = -1;
328
329struct InvokeStateChange {
330 /// EH Label immediately after the last invoke in the previous state, or
331 /// nullptr if the previous state was the null state.
332 const MCSymbol *PreviousEndLabel;
333
334 /// EH label immediately before the first invoke in the new state, or nullptr
335 /// if the new state is the null state.
336 const MCSymbol *NewStartLabel;
337
338 /// State of the invoke following NewStartLabel, or NullState to indicate
339 /// the presence of calls which may unwind to caller.
340 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000341};
342
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000343/// Iterator that reports all the invoke state changes in a range of machine
344/// basic blocks. Changes to the null state are reported whenever a call that
345/// may unwind to caller is encountered. The MBB range is expected to be an
346/// entire function or funclet, and the start and end of the range are treated
347/// as being in the NullState even if there's not an unwind-to-caller call
348/// before the first invoke or after the last one (i.e., the first state change
349/// reported is the first change to something other than NullState, and a
350/// change back to NullState is always reported at the end of iteration).
351class InvokeStateChangeIterator {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000352 InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000353 MachineFunction::const_iterator MFI,
354 MachineFunction::const_iterator MFE,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000355 MachineBasicBlock::const_iterator MBBI,
356 int BaseState)
357 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000358 LastStateChange.PreviousEndLabel = nullptr;
359 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000360 LastStateChange.NewState = BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000361 scan();
362 }
363
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000364public:
365 static iterator_range<InvokeStateChangeIterator>
Reid Klecknerc20276d2015-11-17 21:10:25 +0000366 range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000367 MachineFunction::const_iterator End, int BaseState = NullState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000368 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
369 // the end of the last block.
370 assert(Begin != End);
371 auto BlockBegin = Begin->begin();
372 auto BlockEnd = std::prev(End)->end();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000373 return make_range(
374 InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
375 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000376 }
377
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000378 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000379 bool operator==(const InvokeStateChangeIterator &O) const {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000380 assert(BaseState == O.BaseState);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000381 // Must be visiting same block.
382 if (MFI != O.MFI)
383 return false;
384 // Must be visiting same isntr.
385 if (MBBI != O.MBBI)
386 return false;
387 // At end of block/instr iteration, we can still have two distinct states:
388 // one to report the final EndLabel, and another indicating the end of the
389 // state change iteration. Check for CurrentEndLabel equality to
390 // distinguish these.
391 return CurrentEndLabel == O.CurrentEndLabel;
392 }
393
394 bool operator!=(const InvokeStateChangeIterator &O) const {
395 return !operator==(O);
396 }
397 InvokeStateChange &operator*() { return LastStateChange; }
398 InvokeStateChange *operator->() { return &LastStateChange; }
399 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000400
401private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000402 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000403
Reid Klecknerc20276d2015-11-17 21:10:25 +0000404 const WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000405 const MCSymbol *CurrentEndLabel = nullptr;
406 MachineFunction::const_iterator MFI;
407 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000408 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000409 InvokeStateChange LastStateChange;
410 bool VisitingInvoke = false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000411 int BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000412};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000413
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000414} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000415
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000416InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
417 bool IsNewBlock = false;
418 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
419 if (IsNewBlock)
420 MBBI = MFI->begin();
421 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
422 const MachineInstr &MI = *MBBI;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000423 if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000424 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
425 // Indicate a change of state to the null state. We don't have
426 // start/end EH labels handy but the caller won't expect them for
427 // null state regions.
428 LastStateChange.PreviousEndLabel = CurrentEndLabel;
429 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000430 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000431 CurrentEndLabel = nullptr;
432 // Don't re-visit this instr on the next scan
433 ++MBBI;
434 return *this;
435 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000436
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000437 // All other state changes are at EH labels before/after invokes.
438 if (!MI.isEHLabel())
439 continue;
440 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
441 if (Label == CurrentEndLabel) {
442 VisitingInvoke = false;
443 continue;
444 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000445 auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000446 // Ignore EH labels that aren't the ones inserted before an invoke
David Majnemer8a1c45d2015-12-12 05:38:55 +0000447 if (InvokeMapIter == EHInfo.LabelToStateMap.end())
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000448 continue;
449 auto &StateAndEnd = InvokeMapIter->second;
450 int NewState = StateAndEnd.first;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000451 // Keep track of the fact that we're between EH start/end labels so
452 // we know not to treat the inoke we'll see as unwinding to caller.
453 VisitingInvoke = true;
454 if (NewState == LastStateChange.NewState) {
455 // The state isn't actually changing here. Record the new end and
456 // keep going.
457 CurrentEndLabel = StateAndEnd.second;
458 continue;
459 }
460 // Found a state change to report
461 LastStateChange.PreviousEndLabel = CurrentEndLabel;
462 LastStateChange.NewStartLabel = Label;
463 LastStateChange.NewState = NewState;
464 // Start keeping track of the new current end
465 CurrentEndLabel = StateAndEnd.second;
466 // Don't re-visit this instr on the next scan
467 ++MBBI;
468 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000469 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000470 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000471 // Iteration hit the end of the block range.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000472 if (LastStateChange.NewState != BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000473 // Report the end of the last new state
474 LastStateChange.PreviousEndLabel = CurrentEndLabel;
475 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000476 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000477 // Leave CurrentEndLabel non-null to distinguish this state from end.
478 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000479 return *this;
480 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000481 // We've reported all state changes and hit the end state.
482 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000483 return *this;
484}
485
Reid Kleckner0a57f652015-01-14 01:05:27 +0000486/// Emit the language-specific data that __C_specific_handler expects. This
487/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
488/// up after faults with __try, __except, and __finally. The typeinfo values
489/// are not really RTTI data, but pointers to filter functions that return an
490/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
491/// blocks and other cleanups, the landing pad label is zero, and the filter
492/// function is actually a cleanup handler with the same prototype. A catch-all
493/// entry is modeled with a null filter function field and a non-zero landing
494/// pad label.
495///
496/// Possible filter function return values:
497/// EXCEPTION_EXECUTE_HANDLER (1):
498/// Jump to the landing pad label after cleanups.
499/// EXCEPTION_CONTINUE_SEARCH (0):
500/// Continue searching this table or continue unwinding.
501/// EXCEPTION_CONTINUE_EXECUTION (-1):
502/// Resume execution at the trapping PC.
503///
504/// Inferred table structure:
505/// struct Table {
506/// int NumEntries;
507/// struct Entry {
508/// imagerel32 LabelStart;
509/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000510/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000511/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000512/// } Entries[NumEntries];
513/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000514void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000515 auto &OS = *Asm->OutStreamer;
516 MCContext &Ctx = Asm->OutContext;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000517 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000518
David Majnemer081e8fe2015-12-27 06:07:12 +0000519 bool VerboseAsm = OS.isVerboseAsm();
520 auto AddComment = [&](const Twine &Comment) {
521 if (VerboseAsm)
522 OS.AddComment(Comment);
523 };
524
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000525 // Emit a label assignment with the SEH frame offset so we can use it for
526 // llvm.x86.seh.recoverfp.
527 StringRef FLinkageName =
528 GlobalValue::getRealLinkageName(MF->getFunction()->getName());
529 MCSymbol *ParentFrameOffset =
530 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
531 const MCExpr *MCOffset =
532 MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
533 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
534
Reid Kleckner14e77352015-10-09 23:34:53 +0000535 // Use the assembler to compute the number of table entries through label
536 // difference and division.
537 MCSymbol *TableBegin =
538 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
539 MCSymbol *TableEnd =
540 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000541 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
Reid Kleckner14e77352015-10-09 23:34:53 +0000542 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
543 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
David Majnemer081e8fe2015-12-27 06:07:12 +0000544 AddComment("Number of call sites");
Reid Kleckner14e77352015-10-09 23:34:53 +0000545 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000546
Reid Kleckner14e77352015-10-09 23:34:53 +0000547 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000548
Reid Kleckner14e77352015-10-09 23:34:53 +0000549 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
550 // models exceptions from invokes. LLVM also allows arbitrary reordering of
551 // the code, so our tables end up looking a bit different. Rather than
552 // trying to match MSVC's tables exactly, we emit a denormalized table. For
553 // each range of invokes in the same state, we emit table entries for all
554 // the actions that would be taken in that state. This means our tables are
555 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000556 const MCSymbol *LastStartLabel = nullptr;
557 int LastEHState = -1;
558 // Break out before we enter into a finally funclet.
559 // FIXME: We need to emit separate EH tables for cleanups.
560 MachineFunction::const_iterator End = MF->end();
561 MachineFunction::const_iterator Stop = std::next(MF->begin());
562 while (Stop != End && !Stop->isEHFuncletEntry())
563 ++Stop;
564 for (const auto &StateChange :
565 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
566 // Emit all the actions for the state we just transitioned out of
567 // if it was not the null state
568 if (LastEHState != -1)
569 emitSEHActionsForRange(FuncInfo, LastStartLabel,
570 StateChange.PreviousEndLabel, LastEHState);
571 LastStartLabel = StateChange.NewStartLabel;
572 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000573 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000574
Reid Kleckner14e77352015-10-09 23:34:53 +0000575 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000576}
David Majnemercde33032015-03-30 22:58:10 +0000577
Reid Klecknerc20276d2015-11-17 21:10:25 +0000578void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000579 const MCSymbol *BeginLabel,
580 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000581 auto &OS = *Asm->OutStreamer;
582 MCContext &Ctx = Asm->OutContext;
583
David Majnemer081e8fe2015-12-27 06:07:12 +0000584 bool VerboseAsm = OS.isVerboseAsm();
585 auto AddComment = [&](const Twine &Comment) {
586 if (VerboseAsm)
587 OS.AddComment(Comment);
588 };
589
Reid Klecknerd880dc72015-10-09 20:39:39 +0000590 assert(BeginLabel && EndLabel);
591 while (State != -1) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000592 const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
Reid Klecknerd880dc72015-10-09 20:39:39 +0000593 const MCExpr *FilterOrFinally;
594 const MCExpr *ExceptOrNull;
595 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
596 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000597 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000598 ExceptOrNull = MCConstantExpr::create(0, Ctx);
599 } else {
600 // For an except, the filter can be 1 (catch-all) or a function
601 // label.
602 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
603 : MCConstantExpr::create(1, Ctx);
604 ExceptOrNull = create32bitRef(Handler->getSymbol());
605 }
606
David Majnemer081e8fe2015-12-27 06:07:12 +0000607 AddComment("LabelStart");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000608 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000609 AddComment("LabelEnd");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000610 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000611 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
612 : "CatchAll");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000613 OS.EmitValue(FilterOrFinally, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000614 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000615 OS.EmitValue(ExceptOrNull, 4);
616
617 assert(UME.ToState < State && "states should decrease");
618 State = UME.ToState;
619 }
620}
621
Reid Kleckner60b640b2015-05-28 22:47:01 +0000622void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000623 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000624 auto &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000625 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
David Majnemercde33032015-03-30 22:58:10 +0000626
Reid Kleckner813f1b62015-09-16 22:14:46 +0000627 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000628
Reid Klecknerc71d6272015-09-28 23:56:30 +0000629 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000630 MCSymbol *FuncInfoXData = nullptr;
631 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000632 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
633 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000634 FuncInfoXData =
635 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000636 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000637 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000638 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000639 }
640
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000641 int UnwindHelpOffset = 0;
642 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner6ddae312015-11-05 21:09:49 +0000643 UnwindHelpOffset =
644 getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000645
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000646 MCSymbol *UnwindMapXData = nullptr;
647 MCSymbol *TryBlockMapXData = nullptr;
648 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000649 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000650 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000651 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000652 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000653 TryBlockMapXData =
654 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000655 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000656 IPToStateXData =
657 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000658
David Majnemer081e8fe2015-12-27 06:07:12 +0000659 bool VerboseAsm = OS.isVerboseAsm();
660 auto AddComment = [&](const Twine &Comment) {
661 if (VerboseAsm)
662 OS.AddComment(Comment);
663 };
664
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000665 // FuncInfo {
666 // uint32_t MagicNumber
667 // int32_t MaxState;
668 // UnwindMapEntry *UnwindMap;
669 // uint32_t NumTryBlocks;
670 // TryBlockMapEntry *TryBlockMap;
671 // uint32_t IPMapEntries; // always 0 for x86
672 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
673 // uint32_t UnwindHelp; // non-x86 only
674 // ESTypeList *ESTypeList;
675 // int32_t EHFlags;
676 // }
677 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
678 // EHFlags & 2 -> ???
679 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000680 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000681 OS.EmitLabel(FuncInfoXData);
David Majnemer081e8fe2015-12-27 06:07:12 +0000682
683 AddComment("MagicNumber");
684 OS.EmitIntValue(0x19930522, 4);
685
686 AddComment("MaxState");
687 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
688
689 AddComment("UnwindMap");
690 OS.EmitValue(create32bitRef(UnwindMapXData), 4);
691
692 AddComment("NumTryBlocks");
693 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
694
695 AddComment("TryBlockMap");
696 OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
697
698 AddComment("IPMapEntries");
699 OS.EmitIntValue(IPToStateTable.size(), 4);
700
701 AddComment("IPToStateXData");
702 OS.EmitValue(create32bitRef(IPToStateXData), 4);
703
704 if (Asm->MAI->usesWindowsCFI()) {
705 AddComment("UnwindHelp");
706 OS.EmitIntValue(UnwindHelpOffset, 4);
707 }
708
709 AddComment("ESTypeList");
710 OS.EmitIntValue(0, 4);
711
712 AddComment("EHFlags");
713 OS.EmitIntValue(1, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000714
715 // UnwindMapEntry {
716 // int32_t ToState;
717 // void (*Action)();
718 // };
719 if (UnwindMapXData) {
720 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000721 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000722 MCSymbol *CleanupSym =
723 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
David Majnemer081e8fe2015-12-27 06:07:12 +0000724 AddComment("ToState");
725 OS.EmitIntValue(UME.ToState, 4);
726
727 AddComment("Action");
728 OS.EmitValue(create32bitRef(CleanupSym), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000729 }
730 }
731
732 // TryBlockMap {
733 // int32_t TryLow;
734 // int32_t TryHigh;
735 // int32_t CatchHigh;
736 // int32_t NumCatches;
737 // HandlerType *HandlerArray;
738 // };
739 if (TryBlockMapXData) {
740 OS.EmitLabel(TryBlockMapXData);
741 SmallVector<MCSymbol *, 1> HandlerMaps;
742 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000743 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000744
Reid Kleckner813f1b62015-09-16 22:14:46 +0000745 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000746 if (!TBME.HandlerArray.empty())
747 HandlerMapXData =
748 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
749 .concat(Twine(I))
750 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000751 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000752 HandlerMaps.push_back(HandlerMapXData);
753
Reid Kleckner813f1b62015-09-16 22:14:46 +0000754 // TBMEs should form intervals.
755 assert(0 <= TBME.TryLow && "bad trymap interval");
756 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
757 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000758 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000759 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000760
David Majnemer081e8fe2015-12-27 06:07:12 +0000761 AddComment("TryLow");
762 OS.EmitIntValue(TBME.TryLow, 4);
763
764 AddComment("TryHigh");
765 OS.EmitIntValue(TBME.TryHigh, 4);
766
767 AddComment("CatchHigh");
768 OS.EmitIntValue(TBME.CatchHigh, 4);
769
770 AddComment("NumCatches");
771 OS.EmitIntValue(TBME.HandlerArray.size(), 4);
772
773 AddComment("HandlerArray");
774 OS.EmitValue(create32bitRef(HandlerMapXData), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000775 }
776
Reid Kleckner28e49032015-10-16 23:43:27 +0000777 // All funclets use the same parent frame offset currently.
778 unsigned ParentFrameOffset = 0;
779 if (shouldEmitPersonality) {
780 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
781 ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
782 }
783
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000784 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000785 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000786 MCSymbol *HandlerMapXData = HandlerMaps[I];
787 if (!HandlerMapXData)
788 continue;
789 // HandlerType {
790 // int32_t Adjectives;
791 // TypeDescriptor *Type;
792 // int32_t CatchObjOffset;
793 // void (*Handler)();
794 // int32_t ParentFrameOffset; // x64 only
795 // };
796 OS.EmitLabel(HandlerMapXData);
797 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
798 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000799 // the index is INT_MAX, then there is no catch object, and we should
800 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000801 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000802 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner6ddae312015-11-05 21:09:49 +0000803 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
David Majnemercb305de2016-03-01 04:30:16 +0000804 assert(Offset != 0 && "Illegal offset for catch object!");
Reid Klecknerb005d282015-09-16 20:16:27 +0000805 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000806 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000807 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000808 }
809
David Majnemerbfa5b982015-10-10 00:04:29 +0000810 MCSymbol *HandlerSym =
811 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000812
David Majnemer081e8fe2015-12-27 06:07:12 +0000813 AddComment("Adjectives");
814 OS.EmitIntValue(HT.Adjectives, 4);
815
816 AddComment("Type");
817 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
818
819 AddComment("CatchObjOffset");
820 OS.EmitValue(FrameAllocOffsetRef, 4);
821
822 AddComment("Handler");
823 OS.EmitValue(create32bitRef(HandlerSym), 4);
824
825 if (shouldEmitPersonality) {
826 AddComment("ParentFrameOffset");
827 OS.EmitIntValue(ParentFrameOffset, 4);
828 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000829 }
830 }
831 }
832
833 // IPToStateMapEntry {
834 // void *IP;
835 // int32_t State;
836 // };
837 if (IPToStateXData) {
838 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000839 for (auto &IPStatePair : IPToStateTable) {
David Majnemer081e8fe2015-12-27 06:07:12 +0000840 AddComment("IP");
841 OS.EmitValue(IPStatePair.first, 4);
842 AddComment("ToState");
843 OS.EmitIntValue(IPStatePair.second, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000844 }
845 }
846}
847
Reid Klecknerc71d6272015-09-28 23:56:30 +0000848void WinException::computeIP2StateTable(
Reid Klecknerc20276d2015-11-17 21:10:25 +0000849 const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
Reid Klecknerc71d6272015-09-28 23:56:30 +0000850 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000851
David Majnemer8a1c45d2015-12-12 05:38:55 +0000852 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
853 FuncletEnd = MF->begin(),
854 End = MF->end();
855 FuncletStart != End; FuncletStart = FuncletEnd) {
856 // Find the end of the funclet
857 while (++FuncletEnd != End) {
858 if (FuncletEnd->isEHFuncletEntry()) {
859 break;
860 }
861 }
862
863 // Don't emit ip2state entries for cleanup funclets. Any interesting
864 // exceptional actions in cleanups must be handled in a separate IR
865 // function.
866 if (FuncletStart->isCleanupFuncletEntry())
867 continue;
868
869 MCSymbol *StartLabel;
870 int BaseState;
871 if (FuncletStart == MF->begin()) {
872 BaseState = NullState;
873 StartLabel = Asm->getFunctionBegin();
874 } else {
875 auto *FuncletPad =
876 cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
877 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
878 BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
879 StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
880 }
881 assert(StartLabel && "need local function start label");
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000882 IPToStateTable.push_back(
David Majnemer8a1c45d2015-12-12 05:38:55 +0000883 std::make_pair(create32bitRef(StartLabel), BaseState));
884
885 for (const auto &StateChange : InvokeStateChangeIterator::range(
886 FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
887 // Compute the label to report as the start of this entry; use the EH
888 // start label for the invoke if we have one, otherwise (this is a call
889 // which may unwind to our caller and does not have an EH start label, so)
890 // use the previous end label.
891 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
892 if (!ChangeLabel)
893 ChangeLabel = StateChange.PreviousEndLabel;
894 // Emit an entry indicating that PCs after 'Label' have this EH state.
895 IPToStateTable.push_back(
896 std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
897 // FIXME: assert that NewState is between CatchLow and CatchHigh.
898 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000899 }
David Majnemercde33032015-03-30 22:58:10 +0000900}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000901
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000902void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
903 StringRef FLinkageName) {
904 // Outlined helpers called by the EH runtime need to know the offset of the EH
905 // registration in order to recover the parent frame pointer. Now that we know
906 // we've code generated the parent, we can emit the label assignment that
907 // those helpers use to get the offset of the registration node.
Reid Klecknerc20276d2015-11-17 21:10:25 +0000908 MCContext &Ctx = Asm->OutContext;
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000909 MCSymbol *ParentFrameOffset =
Reid Klecknerc20276d2015-11-17 21:10:25 +0000910 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
911 unsigned UnusedReg;
912 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
913 int64_t Offset = TFI->getFrameIndexReference(
914 *Asm->MF, FuncInfo.EHRegNodeFrameIndex, UnusedReg);
915 const MCExpr *MCOffset = MCConstantExpr::create(Offset, Ctx);
916 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000917}
918
Reid Klecknerf12c0302015-06-09 21:42:19 +0000919/// Emit the language-specific data that _except_handler3 and 4 expect. This is
920/// functionally equivalent to the __C_specific_handler table, except it is
921/// indexed by state number instead of IP.
922void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000923 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000924 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000925 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000926
David Majnemer081e8fe2015-12-27 06:07:12 +0000927 bool VerboseAsm = OS.isVerboseAsm();
928 auto AddComment = [&](const Twine &Comment) {
929 if (VerboseAsm)
930 OS.AddComment(Comment);
931 };
932
Reid Klecknerc20276d2015-11-17 21:10:25 +0000933 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000934 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000935
936 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000937 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000938 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000939 OS.EmitLabel(LSDALabel);
940
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000941 const Function *Per =
942 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000943 StringRef PerName = Per->getName();
944 int BaseState = -1;
945 if (PerName == "_except_handler4") {
946 // The LSDA for _except_handler4 starts with this struct, followed by the
947 // scope table:
948 //
949 // struct EH4ScopeTable {
950 // int32_t GSCookieOffset;
951 // int32_t GSCookieXOROffset;
952 // int32_t EHCookieOffset;
953 // int32_t EHCookieXOROffset;
954 // ScopeTableEntry ScopeRecord[];
955 // };
956 //
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000957 // Offsets are %ebp relative.
958 //
959 // The GS cookie is present only if the function needs stack protection.
960 // GSCookieOffset = -2 means that GS cookie is not used.
961 //
962 // The EH cookie is always present.
963 //
964 // Check is done the following way:
965 // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
966
967 // Retrieve the Guard Stack slot.
968 int GSCookieOffset = -2;
969 const MachineFrameInfo *MFI = MF->getFrameInfo();
970 if (MFI->hasStackProtectorIndex()) {
971 unsigned UnusedReg;
972 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
973 int SSPIdx = MFI->getStackProtectorIndex();
974 GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
975 }
976
977 // Retrieve the EH Guard slot.
978 // TODO(etienneb): Get rid of this value and change it for and assertion.
979 int EHCookieOffset = 9999;
980 if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
981 unsigned UnusedReg;
982 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
983 int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
984 EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
985 }
986
David Majnemer081e8fe2015-12-27 06:07:12 +0000987 AddComment("GSCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000988 OS.EmitIntValue(GSCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000989 AddComment("GSCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +0000990 OS.EmitIntValue(0, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000991 AddComment("EHCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000992 OS.EmitIntValue(EHCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000993 AddComment("EHCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +0000994 OS.EmitIntValue(0, 4);
995 BaseState = -2;
996 }
997
Reid Kleckner14e77352015-10-09 23:34:53 +0000998 assert(!FuncInfo.SEHUnwindMap.empty());
Reid Klecknerc20276d2015-11-17 21:10:25 +0000999 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
David Majnemer081e8fe2015-12-27 06:07:12 +00001000 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1001 const MCSymbol *ExceptOrFinally =
1002 UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
Reid Kleckner14e77352015-10-09 23:34:53 +00001003 // -1 is usually the base state for "unwind to caller", but for
1004 // _except_handler4 it's -2. Do that replacement here if necessary.
1005 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
David Majnemer081e8fe2015-12-27 06:07:12 +00001006 AddComment("ToState");
1007 OS.EmitIntValue(ToState, 4);
1008 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1009 OS.EmitValue(create32bitRef(UME.Filter), 4);
1010 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1011 OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001012 }
1013}
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001014
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001015static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001016 int Rank = 0;
1017 while (State != -1) {
1018 ++Rank;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001019 State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001020 }
1021 return Rank;
1022}
1023
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001024static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1025 int LeftRank = getTryRank(FuncInfo, Left);
1026 int RightRank = getTryRank(FuncInfo, Right);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001027
1028 while (LeftRank < RightRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001029 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001030 --RightRank;
1031 }
1032
1033 while (RightRank < LeftRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001034 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001035 --LeftRank;
1036 }
1037
1038 while (Left != Right) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001039 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1040 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001041 }
1042
1043 return Left;
1044}
1045
1046void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1047 // CLR EH "states" are really just IDs that identify handlers/funclets;
1048 // states, handlers, and funclets all have 1:1 mappings between them, and a
1049 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1050 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +00001051 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001052 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1053 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1054
1055 // A ClrClause describes a protected region.
1056 struct ClrClause {
1057 const MCSymbol *StartLabel; // Start of protected region
1058 const MCSymbol *EndLabel; // End of protected region
1059 int State; // Index of handler protecting the protected region
1060 int EnclosingState; // Index of funclet enclosing the protected region
1061 };
1062 SmallVector<ClrClause, 8> Clauses;
1063
1064 // Build a map from handler MBBs to their corresponding states (i.e. their
1065 // indices in the ClrEHUnwindMap).
1066 int NumStates = FuncInfo.ClrEHUnwindMap.size();
1067 assert(NumStates > 0 && "Don't need exception table!");
1068 DenseMap<const MachineBasicBlock *, int> HandlerStates;
1069 for (int State = 0; State < NumStates; ++State) {
1070 MachineBasicBlock *HandlerBlock =
1071 FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1072 HandlerStates[HandlerBlock] = State;
1073 // Use this loop through all handlers to verify our assumption (used in
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001074 // the MinEnclosingState computation) that enclosing funclets have lower
1075 // state numbers than their enclosed funclets.
1076 assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001077 "ill-formed state numbering");
1078 }
1079 // Map the main function to the NullState.
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001080 HandlerStates[&MF->front()] = NullState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001081
1082 // Write out a sentinel indicating the end of the standard (Windows) xdata
1083 // and the start of the additional (CLR) info.
1084 OS.EmitIntValue(0xffffffff, 4);
1085 // Write out the number of funclets
1086 OS.EmitIntValue(NumStates, 4);
1087
1088 // Walk the machine blocks/instrs, computing and emitting a few things:
1089 // 1. Emit a list of the offsets to each handler entry, in lexical order.
1090 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1091 // 3. Compute the list of ClrClauses, in the required order (inner before
1092 // outer, earlier before later; the order by which a forward scan with
1093 // early termination will find the innermost enclosing clause covering
1094 // a given address).
1095 // 4. A map (MinClauseMap) from each handler index to the index of the
1096 // outermost funclet/function which contains a try clause targeting the
1097 // key handler. This will be used to determine IsDuplicate-ness when
1098 // emitting ClrClauses. The NullState value is used to indicate that the
1099 // top-level function contains a try clause targeting the key handler.
1100 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1101 // try regions we entered before entering the PendingState try but which
1102 // we haven't yet exited.
1103 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1104 // EndSymbolMap and MinClauseMap are maps described above.
1105 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1106 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1107
1108 // Visit the root function and each funclet.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001109 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1110 FuncletEnd = MF->begin(),
1111 End = MF->end();
1112 FuncletStart != End; FuncletStart = FuncletEnd) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001113 int FuncletState = HandlerStates[&*FuncletStart];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001114 // Find the end of the funclet
1115 MCSymbol *EndSymbol = FuncEndSym;
1116 while (++FuncletEnd != End) {
1117 if (FuncletEnd->isEHFuncletEntry()) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001118 EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001119 break;
1120 }
1121 }
1122 // Emit the function/funclet end and, if this is a funclet (and not the
1123 // root function), record it in the EndSymbolMap.
1124 OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1125 if (FuncletState != NullState) {
1126 // Record the end of the handler.
1127 EndSymbolMap[FuncletState] = EndSymbol;
1128 }
1129
1130 // Walk the state changes in this function/funclet and compute its clauses.
1131 // Funclets always start in the null state.
1132 const MCSymbol *CurrentStartLabel = nullptr;
1133 int CurrentState = NullState;
1134 assert(HandlerStack.empty());
1135 for (const auto &StateChange :
1136 InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1137 // Close any try regions we're not still under
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001138 int StillPendingState =
1139 getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1140 while (CurrentState != StillPendingState) {
1141 assert(CurrentState != NullState &&
1142 "Failed to find still-pending state!");
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001143 // Close the pending clause
1144 Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1145 CurrentState, FuncletState});
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001146 // Now the next-outer try region is current
1147 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001148 // Pop the new start label from the handler stack if we've exited all
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001149 // inner try regions of the corresponding try region.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001150 if (HandlerStack.back().second == CurrentState)
1151 CurrentStartLabel = HandlerStack.pop_back_val().first;
1152 }
1153
1154 if (StateChange.NewState != CurrentState) {
1155 // For each clause we're starting, update the MinClauseMap so we can
1156 // know which is the topmost funclet containing a clause targeting
1157 // it.
1158 for (int EnteredState = StateChange.NewState;
1159 EnteredState != CurrentState;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001160 EnteredState =
1161 FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001162 int &MinEnclosingState = MinClauseMap[EnteredState];
1163 if (FuncletState < MinEnclosingState)
1164 MinEnclosingState = FuncletState;
1165 }
1166 // Save the previous current start/label on the stack and update to
1167 // the newly-current start/state.
1168 HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1169 CurrentStartLabel = StateChange.NewStartLabel;
1170 CurrentState = StateChange.NewState;
1171 }
1172 }
1173 assert(HandlerStack.empty());
1174 }
1175
1176 // Now emit the clause info, starting with the number of clauses.
1177 OS.EmitIntValue(Clauses.size(), 4);
1178 for (ClrClause &Clause : Clauses) {
1179 // Emit a CORINFO_EH_CLAUSE :
1180 /*
1181 struct CORINFO_EH_CLAUSE
1182 {
1183 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1184 DWORD TryOffset;
1185 DWORD TryLength; // actually TryEndOffset
1186 DWORD HandlerOffset;
1187 DWORD HandlerLength; // actually HandlerEndOffset
1188 union
1189 {
1190 DWORD ClassToken; // use for catch clauses
1191 DWORD FilterOffset; // use for filter clauses
1192 };
1193 };
1194
1195 enum CORINFO_EH_CLAUSE_FLAGS
1196 {
1197 CORINFO_EH_CLAUSE_NONE = 0,
1198 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1199 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1200 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1201 };
1202 typedef enum CorExceptionFlag
1203 {
1204 COR_ILEXCEPTION_CLAUSE_NONE,
1205 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1206 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1207 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1208 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1209 // clause was duplicated
1210 // to a funclet which was
1211 // pulled out of line
1212 } CorExceptionFlag;
1213 */
1214 // Add 1 to the start/end of the EH clause; the IP associated with a
1215 // call when the runtime does its scan is the IP of the next instruction
1216 // (the one to which control will return after the call), so we need
1217 // to add 1 to the end of the clause to cover that offset. We also add
1218 // 1 to the start of the clause to make sure that the ranges reported
1219 // for all clauses are disjoint. Note that we'll need some additional
1220 // logic when machine traps are supported, since in that case the IP
1221 // that the runtime uses is the offset of the faulting instruction
1222 // itself; if such an instruction immediately follows a call but the
1223 // two belong to different clauses, we'll need to insert a nop between
1224 // them so the runtime can distinguish the point to which the call will
1225 // return from the point at which the fault occurs.
1226
1227 const MCExpr *ClauseBegin =
1228 getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1229 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1230
Reid Klecknerc20276d2015-11-17 21:10:25 +00001231 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001232 MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1233 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1234 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1235 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1236 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1237
1238 uint32_t Flags = 0;
1239 switch (Entry.HandlerType) {
1240 case ClrHandlerType::Catch:
1241 // Leaving bits 0-2 clear indicates catch.
1242 break;
1243 case ClrHandlerType::Filter:
1244 Flags |= 1;
1245 break;
1246 case ClrHandlerType::Finally:
1247 Flags |= 2;
1248 break;
1249 case ClrHandlerType::Fault:
1250 Flags |= 4;
1251 break;
1252 }
1253 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1254 // This is a "duplicate" clause; the handler needs to be entered from a
1255 // frame above the one holding the invoke.
1256 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1257 Flags |= 8;
1258 }
1259 OS.EmitIntValue(Flags, 4);
1260
1261 // Write the clause start/end
1262 OS.EmitValue(ClauseBegin, 4);
1263 OS.EmitValue(ClauseEnd, 4);
1264
1265 // Write out the handler start/end
1266 OS.EmitValue(HandlerBegin, 4);
1267 OS.EmitValue(HandlerEnd, 4);
1268
1269 // Write out the type token or filter offset
1270 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1271 OS.EmitIntValue(Entry.TypeToken, 4);
1272 }
1273}