blob: 6387e981301d4a2a9a9d8f1231434e896570c44e [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/SmallString.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/Twine.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000022#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000024#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCExpr.h"
29#include "llvm/MC/MCSection.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSymbol.h"
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000032#include "llvm/MC/MCWin64EH.h"
David Majnemera80c1512015-09-29 20:12:33 +000033#include "llvm/Support/COFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Dwarf.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000037#include "llvm/Target/TargetFrameLowering.h"
38#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
David Majnemera80c1512015-09-29 20:12:33 +0000128 // Just switch sections to the right xdata section. This use of CurrentFnSym
129 // assumes that we only emit the LSDA when ending the parent function.
130 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
131 Asm->OutContext);
132 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000133
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000134 // Emit the tables appropriate to the personality function in use. If we
135 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000136 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000137 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000138 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000139 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000140 else if (Per == EHPersonality::MSVC_CXX)
141 emitCXXFrameHandler3Table(MF);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000142 else if (Per == EHPersonality::CoreCLR)
143 emitCLRExceptionTable(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000144 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000145 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000146
Lang Hames9ff69c82015-04-24 19:11:51 +0000147 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000148 }
David Majnemera80c1512015-09-29 20:12:33 +0000149}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000150
David Majnemer99c1d132015-10-12 16:44:22 +0000151/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000152static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
153 const MachineBasicBlock *MBB) {
154 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000155 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000156
David Majnemerbfa5b982015-10-10 00:04:29 +0000157 assert(MBB->isEHFuncletEntry());
158
159 // Give catches and cleanups a name based off of their parent function and
160 // their funclet entry block's number.
161 const MachineFunction *MF = MBB->getParent();
162 const Function *F = MF->getFunction();
163 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
164 MCContext &Ctx = MF->getContext();
165 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
166 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
167 Twine(MBB->getNumber()) + "@?0?" +
168 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000169}
170
171void WinException::beginFunclet(const MachineBasicBlock &MBB,
172 MCSymbol *Sym) {
173 CurrentFuncletEntry = &MBB;
174
175 const Function *F = Asm->MF->getFunction();
176 // If a symbol was not provided for the funclet, invent one.
177 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000178 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000179
180 // Describe our funclet symbol as a function with internal linkage.
181 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
182 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
183 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
184 << COFF::SCT_COMPLEX_TYPE_SHIFT);
185 Asm->OutStreamer->EndCOFFSymbolDef();
186
187 // We want our funclet's entry point to be aligned such that no nops will be
188 // present after the label.
189 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
190 F);
191
192 // Now that we've emitted the alignment directive, point at our funclet.
193 Asm->OutStreamer->EmitLabel(Sym);
194 }
195
196 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000197 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000198 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
199
200 if (shouldEmitPersonality) {
201 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
202 const Function *PerFn = nullptr;
203
204 // Determine which personality routine we are using for this funclet.
205 if (F->hasPersonalityFn())
206 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
207 const MCSymbol *PersHandlerSym =
208 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
209
210 // Classify the personality routine so that we may reason about it.
211 EHPersonality Per = EHPersonality::Unknown;
212 if (F->hasPersonalityFn())
213 Per = classifyEHPersonality(F->getPersonalityFn());
214
215 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
216 if (Per != EHPersonality::MSVC_CXX ||
217 !CurrentFuncletEntry->isCleanupFuncletEntry())
218 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
219 }
220}
221
222void WinException::endFunclet() {
223 // No funclet to process? Great, we have nothing to do.
224 if (!CurrentFuncletEntry)
225 return;
226
227 if (shouldEmitMoves || shouldEmitPersonality) {
228 const Function *F = Asm->MF->getFunction();
229 EHPersonality Per = EHPersonality::Unknown;
230 if (F->hasPersonalityFn())
231 Per = classifyEHPersonality(F->getPersonalityFn());
232
233 // The .seh_handlerdata directive implicitly switches section, push the
234 // current section so that we may return to it.
235 Asm->OutStreamer->PushSection();
236
237 // Emit an UNWIND_INFO struct describing the prologue.
238 Asm->OutStreamer->EmitWinEHHandlerData();
239
David Majnemera80c1512015-09-29 20:12:33 +0000240 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
241 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000242 // If this is a C++ catch funclet (or the parent function),
243 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000244 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
245 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
246 Twine("$cppxdata$", FuncLinkageName));
247 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000248 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
249 !CurrentFuncletEntry->isEHFuncletEntry()) {
250 // If this is the parent function in Win64 SEH, emit the LSDA immediately
251 // following .seh_handlerdata.
252 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000253 }
254
255 // Switch back to the previous section now that we are done writing to
256 // .xdata.
257 Asm->OutStreamer->PopSection();
258
259 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000260 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000261 }
262
263 // Let's make sure we don't try to end the same funclet twice.
264 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000265}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000266
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000267const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000268 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000269 return MCConstantExpr::create(0, Asm->OutContext);
270 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000271 ? MCSymbolRefExpr::VK_COFF_IMGREL32
272 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000273 Asm->OutContext);
274}
275
David Majnemer0ad363e2015-08-18 19:07:12 +0000276const MCExpr *WinException::create32bitRef(const Value *V) {
277 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000278 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000279 if (const auto *GV = dyn_cast<GlobalValue>(V))
280 return create32bitRef(Asm->getSymbol(GV));
281 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000282}
283
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000284const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000285 return MCBinaryExpr::createAdd(create32bitRef(Label),
286 MCConstantExpr::create(1, Asm->OutContext),
287 Asm->OutContext);
288}
289
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000290const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
291 const MCSymbol *OffsetFrom) {
292 return MCBinaryExpr::createSub(
293 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
294 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
295}
296
297const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
298 const MCSymbol *OffsetFrom) {
299 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
300 MCConstantExpr::create(1, Asm->OutContext),
301 Asm->OutContext);
302}
303
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000304int WinException::getFrameIndexOffset(int FrameIndex) {
305 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
306 unsigned UnusedReg;
307 if (Asm->MAI->usesWindowsCFI())
308 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
309 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
310}
311
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000312namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000313
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000314/// Top-level state used to represent unwind to caller
315const int NullState = -1;
316
317struct InvokeStateChange {
318 /// EH Label immediately after the last invoke in the previous state, or
319 /// nullptr if the previous state was the null state.
320 const MCSymbol *PreviousEndLabel;
321
322 /// EH label immediately before the first invoke in the new state, or nullptr
323 /// if the new state is the null state.
324 const MCSymbol *NewStartLabel;
325
326 /// State of the invoke following NewStartLabel, or NullState to indicate
327 /// the presence of calls which may unwind to caller.
328 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000329};
330
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000331/// Iterator that reports all the invoke state changes in a range of machine
332/// basic blocks. Changes to the null state are reported whenever a call that
333/// may unwind to caller is encountered. The MBB range is expected to be an
334/// entire function or funclet, and the start and end of the range are treated
335/// as being in the NullState even if there's not an unwind-to-caller call
336/// before the first invoke or after the last one (i.e., the first state change
337/// reported is the first change to something other than NullState, and a
338/// change back to NullState is always reported at the end of iteration).
339class InvokeStateChangeIterator {
340 InvokeStateChangeIterator(WinEHFuncInfo &EHInfo,
341 MachineFunction::const_iterator MFI,
342 MachineFunction::const_iterator MFE,
343 MachineBasicBlock::const_iterator MBBI)
344 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI) {
345 LastStateChange.PreviousEndLabel = nullptr;
346 LastStateChange.NewStartLabel = nullptr;
347 LastStateChange.NewState = NullState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000348 scan();
349 }
350
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000351public:
352 static iterator_range<InvokeStateChangeIterator>
353 range(WinEHFuncInfo &EHInfo, const MachineFunction &MF) {
354 // Reject empty MFs to simplify bookkeeping by ensuring that we can get the
355 // end of the last block.
356 assert(!MF.empty());
357 auto FuncBegin = MF.begin();
358 auto FuncEnd = MF.end();
359 auto BlockBegin = FuncBegin->begin();
360 auto BlockEnd = MF.back().end();
361 return make_range(
362 InvokeStateChangeIterator(EHInfo, FuncBegin, FuncEnd, BlockBegin),
363 InvokeStateChangeIterator(EHInfo, FuncEnd, FuncEnd, BlockEnd));
364 }
365 static iterator_range<InvokeStateChangeIterator>
366 range(WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
367 MachineFunction::const_iterator End) {
368 // 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();
373 return make_range(InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin),
374 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd));
375 }
376
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000377 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000378 bool operator==(const InvokeStateChangeIterator &O) const {
379 // Must be visiting same block.
380 if (MFI != O.MFI)
381 return false;
382 // Must be visiting same isntr.
383 if (MBBI != O.MBBI)
384 return false;
385 // At end of block/instr iteration, we can still have two distinct states:
386 // one to report the final EndLabel, and another indicating the end of the
387 // state change iteration. Check for CurrentEndLabel equality to
388 // distinguish these.
389 return CurrentEndLabel == O.CurrentEndLabel;
390 }
391
392 bool operator!=(const InvokeStateChangeIterator &O) const {
393 return !operator==(O);
394 }
395 InvokeStateChange &operator*() { return LastStateChange; }
396 InvokeStateChange *operator->() { return &LastStateChange; }
397 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000398
399private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000400 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000401
402 WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000403 const MCSymbol *CurrentEndLabel = nullptr;
404 MachineFunction::const_iterator MFI;
405 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000406 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000407 InvokeStateChange LastStateChange;
408 bool VisitingInvoke = false;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000409};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000410
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000411} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000412
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000413InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
414 bool IsNewBlock = false;
415 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
416 if (IsNewBlock)
417 MBBI = MFI->begin();
418 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
419 const MachineInstr &MI = *MBBI;
420 if (!VisitingInvoke && LastStateChange.NewState != NullState &&
421 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
422 // Indicate a change of state to the null state. We don't have
423 // start/end EH labels handy but the caller won't expect them for
424 // null state regions.
425 LastStateChange.PreviousEndLabel = CurrentEndLabel;
426 LastStateChange.NewStartLabel = nullptr;
427 LastStateChange.NewState = NullState;
428 CurrentEndLabel = nullptr;
429 // Don't re-visit this instr on the next scan
430 ++MBBI;
431 return *this;
432 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000433
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000434 // All other state changes are at EH labels before/after invokes.
435 if (!MI.isEHLabel())
436 continue;
437 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
438 if (Label == CurrentEndLabel) {
439 VisitingInvoke = false;
440 continue;
441 }
442 auto InvokeMapIter = EHInfo.InvokeToStateMap.find(Label);
443 // Ignore EH labels that aren't the ones inserted before an invoke
444 if (InvokeMapIter == EHInfo.InvokeToStateMap.end())
445 continue;
446 auto &StateAndEnd = InvokeMapIter->second;
447 int NewState = StateAndEnd.first;
448 // Ignore EH labels explicitly annotated with the null state (which
449 // can happen for invokes that unwind to a chain of endpads the last
450 // of which unwinds to caller). We'll see the subsequent invoke and
451 // report a transition to the null state same as we do for calls.
452 if (NewState == NullState)
453 continue;
454 // Keep track of the fact that we're between EH start/end labels so
455 // we know not to treat the inoke we'll see as unwinding to caller.
456 VisitingInvoke = true;
457 if (NewState == LastStateChange.NewState) {
458 // The state isn't actually changing here. Record the new end and
459 // keep going.
460 CurrentEndLabel = StateAndEnd.second;
461 continue;
462 }
463 // Found a state change to report
464 LastStateChange.PreviousEndLabel = CurrentEndLabel;
465 LastStateChange.NewStartLabel = Label;
466 LastStateChange.NewState = NewState;
467 // Start keeping track of the new current end
468 CurrentEndLabel = StateAndEnd.second;
469 // Don't re-visit this instr on the next scan
470 ++MBBI;
471 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000472 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000473 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000474 // Iteration hit the end of the block range.
475 if (LastStateChange.NewState != NullState) {
476 // Report the end of the last new state
477 LastStateChange.PreviousEndLabel = CurrentEndLabel;
478 LastStateChange.NewStartLabel = nullptr;
479 LastStateChange.NewState = NullState;
480 // Leave CurrentEndLabel non-null to distinguish this state from end.
481 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000482 return *this;
483 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000484 // We've reported all state changes and hit the end state.
485 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000486 return *this;
487}
488
Reid Kleckner0a57f652015-01-14 01:05:27 +0000489/// Emit the language-specific data that __C_specific_handler expects. This
490/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
491/// up after faults with __try, __except, and __finally. The typeinfo values
492/// are not really RTTI data, but pointers to filter functions that return an
493/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
494/// blocks and other cleanups, the landing pad label is zero, and the filter
495/// function is actually a cleanup handler with the same prototype. A catch-all
496/// entry is modeled with a null filter function field and a non-zero landing
497/// pad label.
498///
499/// Possible filter function return values:
500/// EXCEPTION_EXECUTE_HANDLER (1):
501/// Jump to the landing pad label after cleanups.
502/// EXCEPTION_CONTINUE_SEARCH (0):
503/// Continue searching this table or continue unwinding.
504/// EXCEPTION_CONTINUE_EXECUTION (-1):
505/// Resume execution at the trapping PC.
506///
507/// Inferred table structure:
508/// struct Table {
509/// int NumEntries;
510/// struct Entry {
511/// imagerel32 LabelStart;
512/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000513/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000514/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000515/// } Entries[NumEntries];
516/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000517void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000518 auto &OS = *Asm->OutStreamer;
519 MCContext &Ctx = Asm->OutContext;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000520
Reid Kleckner94b704c2015-09-09 21:10:03 +0000521 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
Reid Kleckner14e77352015-10-09 23:34:53 +0000522 // Use the assembler to compute the number of table entries through label
523 // difference and division.
524 MCSymbol *TableBegin =
525 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
526 MCSymbol *TableEnd =
527 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000528 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
Reid Kleckner14e77352015-10-09 23:34:53 +0000529 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
530 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
531 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000532
Reid Kleckner14e77352015-10-09 23:34:53 +0000533 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000534
Reid Kleckner14e77352015-10-09 23:34:53 +0000535 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
536 // models exceptions from invokes. LLVM also allows arbitrary reordering of
537 // the code, so our tables end up looking a bit different. Rather than
538 // trying to match MSVC's tables exactly, we emit a denormalized table. For
539 // each range of invokes in the same state, we emit table entries for all
540 // the actions that would be taken in that state. This means our tables are
541 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000542 const MCSymbol *LastStartLabel = nullptr;
543 int LastEHState = -1;
544 // Break out before we enter into a finally funclet.
545 // FIXME: We need to emit separate EH tables for cleanups.
546 MachineFunction::const_iterator End = MF->end();
547 MachineFunction::const_iterator Stop = std::next(MF->begin());
548 while (Stop != End && !Stop->isEHFuncletEntry())
549 ++Stop;
550 for (const auto &StateChange :
551 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
552 // Emit all the actions for the state we just transitioned out of
553 // if it was not the null state
554 if (LastEHState != -1)
555 emitSEHActionsForRange(FuncInfo, LastStartLabel,
556 StateChange.PreviousEndLabel, LastEHState);
557 LastStartLabel = StateChange.NewStartLabel;
558 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000559 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000560
Reid Kleckner14e77352015-10-09 23:34:53 +0000561 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000562}
David Majnemercde33032015-03-30 22:58:10 +0000563
Reid Klecknerd880dc72015-10-09 20:39:39 +0000564void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000565 const MCSymbol *BeginLabel,
566 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000567 auto &OS = *Asm->OutStreamer;
568 MCContext &Ctx = Asm->OutContext;
569
570 assert(BeginLabel && EndLabel);
571 while (State != -1) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000572 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
573 const MCExpr *FilterOrFinally;
574 const MCExpr *ExceptOrNull;
575 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
576 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000577 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000578 ExceptOrNull = MCConstantExpr::create(0, Ctx);
579 } else {
580 // For an except, the filter can be 1 (catch-all) or a function
581 // label.
582 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
583 : MCConstantExpr::create(1, Ctx);
584 ExceptOrNull = create32bitRef(Handler->getSymbol());
585 }
586
587 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
588 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
589 OS.EmitValue(FilterOrFinally, 4);
590 OS.EmitValue(ExceptOrNull, 4);
591
592 assert(UME.ToState < State && "states should decrease");
593 State = UME.ToState;
594 }
595}
596
Reid Kleckner60b640b2015-05-28 22:47:01 +0000597void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000598 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000599 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000600 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000601
Reid Kleckner813f1b62015-09-16 22:14:46 +0000602 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000603
Reid Klecknerc71d6272015-09-28 23:56:30 +0000604 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000605 MCSymbol *FuncInfoXData = nullptr;
606 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000607 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
608 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000609 FuncInfoXData =
610 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000611 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000612 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000613 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
614 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000615 }
616
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000617 int UnwindHelpOffset = 0;
618 if (Asm->MAI->usesWindowsCFI())
619 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
620
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000621 MCSymbol *UnwindMapXData = nullptr;
622 MCSymbol *TryBlockMapXData = nullptr;
623 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000624 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000625 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000626 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000627 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000628 TryBlockMapXData =
629 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000630 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000631 IPToStateXData =
632 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000633
634 // FuncInfo {
635 // uint32_t MagicNumber
636 // int32_t MaxState;
637 // UnwindMapEntry *UnwindMap;
638 // uint32_t NumTryBlocks;
639 // TryBlockMapEntry *TryBlockMap;
640 // uint32_t IPMapEntries; // always 0 for x86
641 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
642 // uint32_t UnwindHelp; // non-x86 only
643 // ESTypeList *ESTypeList;
644 // int32_t EHFlags;
645 // }
646 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
647 // EHFlags & 2 -> ???
648 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000649 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000650 OS.EmitLabel(FuncInfoXData);
651 OS.EmitIntValue(0x19930522, 4); // MagicNumber
Reid Kleckner14e77352015-10-09 23:34:53 +0000652 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4); // MaxState
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000653 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
654 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
655 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
Reid Klecknerc71d6272015-09-28 23:56:30 +0000656 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000657 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
658 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000659 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000660 OS.EmitIntValue(0, 4); // ESTypeList
661 OS.EmitIntValue(1, 4); // EHFlags
662
663 // UnwindMapEntry {
664 // int32_t ToState;
665 // void (*Action)();
666 // };
667 if (UnwindMapXData) {
668 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000669 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000670 MCSymbol *CleanupSym =
671 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
Reid Kleckner78783912015-09-10 00:25:23 +0000672 OS.EmitIntValue(UME.ToState, 4); // ToState
673 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000674 }
675 }
676
677 // TryBlockMap {
678 // int32_t TryLow;
679 // int32_t TryHigh;
680 // int32_t CatchHigh;
681 // int32_t NumCatches;
682 // HandlerType *HandlerArray;
683 // };
684 if (TryBlockMapXData) {
685 OS.EmitLabel(TryBlockMapXData);
686 SmallVector<MCSymbol *, 1> HandlerMaps;
687 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
688 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000689
Reid Kleckner813f1b62015-09-16 22:14:46 +0000690 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000691 if (!TBME.HandlerArray.empty())
692 HandlerMapXData =
693 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
694 .concat(Twine(I))
695 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000696 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000697 HandlerMaps.push_back(HandlerMapXData);
698
Reid Kleckner813f1b62015-09-16 22:14:46 +0000699 // TBMEs should form intervals.
700 assert(0 <= TBME.TryLow && "bad trymap interval");
701 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
702 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000703 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000704 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000705
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000706 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
707 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000708 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000709 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
710 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
711 }
712
Reid Kleckner28e49032015-10-16 23:43:27 +0000713 // All funclets use the same parent frame offset currently.
714 unsigned ParentFrameOffset = 0;
715 if (shouldEmitPersonality) {
716 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
717 ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
718 }
719
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000720 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
721 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
722 MCSymbol *HandlerMapXData = HandlerMaps[I];
723 if (!HandlerMapXData)
724 continue;
725 // HandlerType {
726 // int32_t Adjectives;
727 // TypeDescriptor *Type;
728 // int32_t CatchObjOffset;
729 // void (*Handler)();
730 // int32_t ParentFrameOffset; // x64 only
731 // };
732 OS.EmitLabel(HandlerMapXData);
733 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
734 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000735 // the index is INT_MAX, then there is no catch object, and we should
736 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000737 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000738 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000739 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
Reid Klecknerb005d282015-09-16 20:16:27 +0000740 // For 32-bit, the catch object offset is relative to the end of the
741 // EH registration node. For 64-bit, it's relative to SP at the end of
742 // the prologue.
743 if (!shouldEmitPersonality) {
744 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
745 Offset += FuncInfo.EHRegNodeEndOffset;
746 }
747 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000748 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000749 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000750 }
751
David Majnemerbfa5b982015-10-10 00:04:29 +0000752 MCSymbol *HandlerSym =
753 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000754
755 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
756 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
757 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
758 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner28e49032015-10-16 23:43:27 +0000759 if (shouldEmitPersonality)
Reid Kleckner813f1b62015-09-16 22:14:46 +0000760 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000761 }
762 }
763 }
764
765 // IPToStateMapEntry {
766 // void *IP;
767 // int32_t State;
768 // };
769 if (IPToStateXData) {
770 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000771 for (auto &IPStatePair : IPToStateTable) {
772 OS.EmitValue(IPStatePair.first, 4); // IP
773 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000774 }
775 }
776}
777
Reid Klecknerc71d6272015-09-28 23:56:30 +0000778void WinException::computeIP2StateTable(
779 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
780 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000781 // Indicate that all calls from the prologue to the first invoke unwind to
782 // caller. We handle this as a special case since other ranges starting at end
783 // labels need to use LtmpN+1.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000784 MCSymbol *StartLabel = Asm->getFunctionBegin();
785 assert(StartLabel && "need local function start label");
786 IPToStateTable.push_back(std::make_pair(create32bitRef(StartLabel), -1));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000787
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000788 // FIXME: Do we need to emit entries for funclet base states?
789 for (const auto &StateChange :
790 InvokeStateChangeIterator::range(FuncInfo, *MF)) {
791 // Compute the label to report as the start of this entry; use the EH start
792 // label for the invoke if we have one, otherwise (this is a call which may
793 // unwind to our caller and does not have an EH start label, so) use the
794 // previous end label.
795 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
796 if (!ChangeLabel)
797 ChangeLabel = StateChange.PreviousEndLabel;
798 // Emit an entry indicating that PCs after 'Label' have this EH state.
799 IPToStateTable.push_back(
800 std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000801 }
David Majnemercde33032015-03-30 22:58:10 +0000802}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000803
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000804void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
805 StringRef FLinkageName) {
806 // Outlined helpers called by the EH runtime need to know the offset of the EH
807 // registration in order to recover the parent frame pointer. Now that we know
808 // we've code generated the parent, we can emit the label assignment that
809 // those helpers use to get the offset of the registration node.
810 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000811 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000812 MCSymbol *ParentFrameOffset =
813 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
814 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
815 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
816 const MCExpr *RegistrationOffsetSymRef =
817 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
818 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
819}
820
Reid Klecknerf12c0302015-06-09 21:42:19 +0000821/// Emit the language-specific data that _except_handler3 and 4 expect. This is
822/// functionally equivalent to the __C_specific_handler table, except it is
823/// indexed by state number instead of IP.
824void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000825 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000826 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000827 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000828
829 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
830 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000831
832 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000833 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000834 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000835 OS.EmitLabel(LSDALabel);
836
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000837 const Function *Per =
838 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000839 StringRef PerName = Per->getName();
840 int BaseState = -1;
841 if (PerName == "_except_handler4") {
842 // The LSDA for _except_handler4 starts with this struct, followed by the
843 // scope table:
844 //
845 // struct EH4ScopeTable {
846 // int32_t GSCookieOffset;
847 // int32_t GSCookieXOROffset;
848 // int32_t EHCookieOffset;
849 // int32_t EHCookieXOROffset;
850 // ScopeTableEntry ScopeRecord[];
851 // };
852 //
853 // Only the EHCookieOffset field appears to vary, and it appears to be the
854 // offset from the final saved SP value to the retaddr.
855 OS.EmitIntValue(-2, 4);
856 OS.EmitIntValue(0, 4);
857 // FIXME: Calculate.
858 OS.EmitIntValue(9999, 4);
859 OS.EmitIntValue(0, 4);
860 BaseState = -2;
861 }
862
Reid Kleckner14e77352015-10-09 23:34:53 +0000863 assert(!FuncInfo.SEHUnwindMap.empty());
864 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
865 MCSymbol *ExceptOrFinally =
866 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
867 // -1 is usually the base state for "unwind to caller", but for
868 // _except_handler4 it's -2. Do that replacement here if necessary.
869 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
870 OS.EmitIntValue(ToState, 4); // ToState
871 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
872 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
Reid Klecknerf12c0302015-06-09 21:42:19 +0000873 }
874}
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000875
876static int getRank(WinEHFuncInfo &FuncInfo, int State) {
877 int Rank = 0;
878 while (State != -1) {
879 ++Rank;
880 State = FuncInfo.ClrEHUnwindMap[State].Parent;
881 }
882 return Rank;
883}
884
885static int getAncestor(WinEHFuncInfo &FuncInfo, int Left, int Right) {
886 int LeftRank = getRank(FuncInfo, Left);
887 int RightRank = getRank(FuncInfo, Right);
888
889 while (LeftRank < RightRank) {
890 Right = FuncInfo.ClrEHUnwindMap[Right].Parent;
891 --RightRank;
892 }
893
894 while (RightRank < LeftRank) {
895 Left = FuncInfo.ClrEHUnwindMap[Left].Parent;
896 --LeftRank;
897 }
898
899 while (Left != Right) {
900 Left = FuncInfo.ClrEHUnwindMap[Left].Parent;
901 Right = FuncInfo.ClrEHUnwindMap[Right].Parent;
902 }
903
904 return Left;
905}
906
907void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
908 // CLR EH "states" are really just IDs that identify handlers/funclets;
909 // states, handlers, and funclets all have 1:1 mappings between them, and a
910 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
911 MCStreamer &OS = *Asm->OutStreamer;
912 const Function *F = MF->getFunction();
913 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
914 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
915 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
916
917 // A ClrClause describes a protected region.
918 struct ClrClause {
919 const MCSymbol *StartLabel; // Start of protected region
920 const MCSymbol *EndLabel; // End of protected region
921 int State; // Index of handler protecting the protected region
922 int EnclosingState; // Index of funclet enclosing the protected region
923 };
924 SmallVector<ClrClause, 8> Clauses;
925
926 // Build a map from handler MBBs to their corresponding states (i.e. their
927 // indices in the ClrEHUnwindMap).
928 int NumStates = FuncInfo.ClrEHUnwindMap.size();
929 assert(NumStates > 0 && "Don't need exception table!");
930 DenseMap<const MachineBasicBlock *, int> HandlerStates;
931 for (int State = 0; State < NumStates; ++State) {
932 MachineBasicBlock *HandlerBlock =
933 FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
934 HandlerStates[HandlerBlock] = State;
935 // Use this loop through all handlers to verify our assumption (used in
936 // the MinEnclosingState computation) that ancestors have lower state
937 // numbers than their descendants.
938 assert(FuncInfo.ClrEHUnwindMap[State].Parent < State &&
939 "ill-formed state numbering");
940 }
941 // Map the main function to the NullState.
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +0000942 HandlerStates[&MF->front()] = NullState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000943
944 // Write out a sentinel indicating the end of the standard (Windows) xdata
945 // and the start of the additional (CLR) info.
946 OS.EmitIntValue(0xffffffff, 4);
947 // Write out the number of funclets
948 OS.EmitIntValue(NumStates, 4);
949
950 // Walk the machine blocks/instrs, computing and emitting a few things:
951 // 1. Emit a list of the offsets to each handler entry, in lexical order.
952 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
953 // 3. Compute the list of ClrClauses, in the required order (inner before
954 // outer, earlier before later; the order by which a forward scan with
955 // early termination will find the innermost enclosing clause covering
956 // a given address).
957 // 4. A map (MinClauseMap) from each handler index to the index of the
958 // outermost funclet/function which contains a try clause targeting the
959 // key handler. This will be used to determine IsDuplicate-ness when
960 // emitting ClrClauses. The NullState value is used to indicate that the
961 // top-level function contains a try clause targeting the key handler.
962 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
963 // try regions we entered before entering the PendingState try but which
964 // we haven't yet exited.
965 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
966 // EndSymbolMap and MinClauseMap are maps described above.
967 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
968 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
969
970 // Visit the root function and each funclet.
971
972 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
973 FuncletEnd = MF->begin(),
974 End = MF->end();
975 FuncletStart != End; FuncletStart = FuncletEnd) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +0000976 int FuncletState = HandlerStates[&*FuncletStart];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000977 // Find the end of the funclet
978 MCSymbol *EndSymbol = FuncEndSym;
979 while (++FuncletEnd != End) {
980 if (FuncletEnd->isEHFuncletEntry()) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +0000981 EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000982 break;
983 }
984 }
985 // Emit the function/funclet end and, if this is a funclet (and not the
986 // root function), record it in the EndSymbolMap.
987 OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
988 if (FuncletState != NullState) {
989 // Record the end of the handler.
990 EndSymbolMap[FuncletState] = EndSymbol;
991 }
992
993 // Walk the state changes in this function/funclet and compute its clauses.
994 // Funclets always start in the null state.
995 const MCSymbol *CurrentStartLabel = nullptr;
996 int CurrentState = NullState;
997 assert(HandlerStack.empty());
998 for (const auto &StateChange :
999 InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1000 // Close any try regions we're not still under
1001 int AncestorState =
1002 getAncestor(FuncInfo, CurrentState, StateChange.NewState);
1003 while (CurrentState != AncestorState) {
1004 assert(CurrentState != NullState && "Failed to find ancestor!");
1005 // Close the pending clause
1006 Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1007 CurrentState, FuncletState});
1008 // Now the parent handler is current
1009 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].Parent;
1010 // Pop the new start label from the handler stack if we've exited all
1011 // descendants of the corresponding handler.
1012 if (HandlerStack.back().second == CurrentState)
1013 CurrentStartLabel = HandlerStack.pop_back_val().first;
1014 }
1015
1016 if (StateChange.NewState != CurrentState) {
1017 // For each clause we're starting, update the MinClauseMap so we can
1018 // know which is the topmost funclet containing a clause targeting
1019 // it.
1020 for (int EnteredState = StateChange.NewState;
1021 EnteredState != CurrentState;
1022 EnteredState = FuncInfo.ClrEHUnwindMap[EnteredState].Parent) {
1023 int &MinEnclosingState = MinClauseMap[EnteredState];
1024 if (FuncletState < MinEnclosingState)
1025 MinEnclosingState = FuncletState;
1026 }
1027 // Save the previous current start/label on the stack and update to
1028 // the newly-current start/state.
1029 HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1030 CurrentStartLabel = StateChange.NewStartLabel;
1031 CurrentState = StateChange.NewState;
1032 }
1033 }
1034 assert(HandlerStack.empty());
1035 }
1036
1037 // Now emit the clause info, starting with the number of clauses.
1038 OS.EmitIntValue(Clauses.size(), 4);
1039 for (ClrClause &Clause : Clauses) {
1040 // Emit a CORINFO_EH_CLAUSE :
1041 /*
1042 struct CORINFO_EH_CLAUSE
1043 {
1044 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1045 DWORD TryOffset;
1046 DWORD TryLength; // actually TryEndOffset
1047 DWORD HandlerOffset;
1048 DWORD HandlerLength; // actually HandlerEndOffset
1049 union
1050 {
1051 DWORD ClassToken; // use for catch clauses
1052 DWORD FilterOffset; // use for filter clauses
1053 };
1054 };
1055
1056 enum CORINFO_EH_CLAUSE_FLAGS
1057 {
1058 CORINFO_EH_CLAUSE_NONE = 0,
1059 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1060 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1061 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1062 };
1063 typedef enum CorExceptionFlag
1064 {
1065 COR_ILEXCEPTION_CLAUSE_NONE,
1066 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1067 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1068 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1069 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1070 // clause was duplicated
1071 // to a funclet which was
1072 // pulled out of line
1073 } CorExceptionFlag;
1074 */
1075 // Add 1 to the start/end of the EH clause; the IP associated with a
1076 // call when the runtime does its scan is the IP of the next instruction
1077 // (the one to which control will return after the call), so we need
1078 // to add 1 to the end of the clause to cover that offset. We also add
1079 // 1 to the start of the clause to make sure that the ranges reported
1080 // for all clauses are disjoint. Note that we'll need some additional
1081 // logic when machine traps are supported, since in that case the IP
1082 // that the runtime uses is the offset of the faulting instruction
1083 // itself; if such an instruction immediately follows a call but the
1084 // two belong to different clauses, we'll need to insert a nop between
1085 // them so the runtime can distinguish the point to which the call will
1086 // return from the point at which the fault occurs.
1087
1088 const MCExpr *ClauseBegin =
1089 getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1090 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1091
1092 ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1093 MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1094 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1095 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1096 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1097 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1098
1099 uint32_t Flags = 0;
1100 switch (Entry.HandlerType) {
1101 case ClrHandlerType::Catch:
1102 // Leaving bits 0-2 clear indicates catch.
1103 break;
1104 case ClrHandlerType::Filter:
1105 Flags |= 1;
1106 break;
1107 case ClrHandlerType::Finally:
1108 Flags |= 2;
1109 break;
1110 case ClrHandlerType::Fault:
1111 Flags |= 4;
1112 break;
1113 }
1114 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1115 // This is a "duplicate" clause; the handler needs to be entered from a
1116 // frame above the one holding the invoke.
1117 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1118 Flags |= 8;
1119 }
1120 OS.EmitIntValue(Flags, 4);
1121
1122 // Write the clause start/end
1123 OS.EmitValue(ClauseBegin, 4);
1124 OS.EmitValue(ClauseEnd, 4);
1125
1126 // Write out the handler start/end
1127 OS.EmitValue(HandlerBegin, 4);
1128 OS.EmitValue(HandlerEnd, 4);
1129
1130 // Write out the type token or filter offset
1131 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1132 OS.EmitIntValue(Entry.TypeToken, 4);
1133 }
1134}