blob: bd348f681c548521e811978400c9bd22a07fa433 [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);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000142 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000143 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000144
Lang Hames9ff69c82015-04-24 19:11:51 +0000145 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000146 }
David Majnemera80c1512015-09-29 20:12:33 +0000147}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000148
David Majnemer99c1d132015-10-12 16:44:22 +0000149/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000150static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
151 const MachineBasicBlock *MBB) {
152 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000153 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000154
David Majnemerbfa5b982015-10-10 00:04:29 +0000155 assert(MBB->isEHFuncletEntry());
156
157 // Give catches and cleanups a name based off of their parent function and
158 // their funclet entry block's number.
159 const MachineFunction *MF = MBB->getParent();
160 const Function *F = MF->getFunction();
161 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
162 MCContext &Ctx = MF->getContext();
163 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
164 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
165 Twine(MBB->getNumber()) + "@?0?" +
166 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000167}
168
169void WinException::beginFunclet(const MachineBasicBlock &MBB,
170 MCSymbol *Sym) {
171 CurrentFuncletEntry = &MBB;
172
173 const Function *F = Asm->MF->getFunction();
174 // If a symbol was not provided for the funclet, invent one.
175 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000176 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000177
178 // Describe our funclet symbol as a function with internal linkage.
179 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
180 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
181 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
182 << COFF::SCT_COMPLEX_TYPE_SHIFT);
183 Asm->OutStreamer->EndCOFFSymbolDef();
184
185 // We want our funclet's entry point to be aligned such that no nops will be
186 // present after the label.
187 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
188 F);
189
190 // Now that we've emitted the alignment directive, point at our funclet.
191 Asm->OutStreamer->EmitLabel(Sym);
192 }
193
194 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000195 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000196 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
197
198 if (shouldEmitPersonality) {
199 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
200 const Function *PerFn = nullptr;
201
202 // Determine which personality routine we are using for this funclet.
203 if (F->hasPersonalityFn())
204 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
205 const MCSymbol *PersHandlerSym =
206 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
207
208 // Classify the personality routine so that we may reason about it.
209 EHPersonality Per = EHPersonality::Unknown;
210 if (F->hasPersonalityFn())
211 Per = classifyEHPersonality(F->getPersonalityFn());
212
213 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
214 if (Per != EHPersonality::MSVC_CXX ||
215 !CurrentFuncletEntry->isCleanupFuncletEntry())
216 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
217 }
218}
219
220void WinException::endFunclet() {
221 // No funclet to process? Great, we have nothing to do.
222 if (!CurrentFuncletEntry)
223 return;
224
225 if (shouldEmitMoves || shouldEmitPersonality) {
226 const Function *F = Asm->MF->getFunction();
227 EHPersonality Per = EHPersonality::Unknown;
228 if (F->hasPersonalityFn())
229 Per = classifyEHPersonality(F->getPersonalityFn());
230
231 // The .seh_handlerdata directive implicitly switches section, push the
232 // current section so that we may return to it.
233 Asm->OutStreamer->PushSection();
234
235 // Emit an UNWIND_INFO struct describing the prologue.
236 Asm->OutStreamer->EmitWinEHHandlerData();
237
David Majnemera80c1512015-09-29 20:12:33 +0000238 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
239 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000240 // If this is a C++ catch funclet (or the parent function),
241 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000242 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
243 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
244 Twine("$cppxdata$", FuncLinkageName));
245 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000246 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
247 !CurrentFuncletEntry->isEHFuncletEntry()) {
248 // If this is the parent function in Win64 SEH, emit the LSDA immediately
249 // following .seh_handlerdata.
250 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000251 }
252
253 // Switch back to the previous section now that we are done writing to
254 // .xdata.
255 Asm->OutStreamer->PopSection();
256
257 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000258 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000259 }
260
261 // Let's make sure we don't try to end the same funclet twice.
262 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000263}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000264
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000265const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000266 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000267 return MCConstantExpr::create(0, Asm->OutContext);
268 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000269 ? MCSymbolRefExpr::VK_COFF_IMGREL32
270 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000271 Asm->OutContext);
272}
273
David Majnemer0ad363e2015-08-18 19:07:12 +0000274const MCExpr *WinException::create32bitRef(const Value *V) {
275 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000276 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000277 if (const auto *GV = dyn_cast<GlobalValue>(V))
278 return create32bitRef(Asm->getSymbol(GV));
279 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000280}
281
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000282const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000283 return MCBinaryExpr::createAdd(create32bitRef(Label),
284 MCConstantExpr::create(1, Asm->OutContext),
285 Asm->OutContext);
286}
287
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000288int WinException::getFrameIndexOffset(int FrameIndex) {
289 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
290 unsigned UnusedReg;
291 if (Asm->MAI->usesWindowsCFI())
292 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
293 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
294}
295
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000296namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000297
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000298/// Top-level state used to represent unwind to caller
299const int NullState = -1;
300
301struct InvokeStateChange {
302 /// EH Label immediately after the last invoke in the previous state, or
303 /// nullptr if the previous state was the null state.
304 const MCSymbol *PreviousEndLabel;
305
306 /// EH label immediately before the first invoke in the new state, or nullptr
307 /// if the new state is the null state.
308 const MCSymbol *NewStartLabel;
309
310 /// State of the invoke following NewStartLabel, or NullState to indicate
311 /// the presence of calls which may unwind to caller.
312 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000313};
314
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000315/// Iterator that reports all the invoke state changes in a range of machine
316/// basic blocks. Changes to the null state are reported whenever a call that
317/// may unwind to caller is encountered. The MBB range is expected to be an
318/// entire function or funclet, and the start and end of the range are treated
319/// as being in the NullState even if there's not an unwind-to-caller call
320/// before the first invoke or after the last one (i.e., the first state change
321/// reported is the first change to something other than NullState, and a
322/// change back to NullState is always reported at the end of iteration).
323class InvokeStateChangeIterator {
324 InvokeStateChangeIterator(WinEHFuncInfo &EHInfo,
325 MachineFunction::const_iterator MFI,
326 MachineFunction::const_iterator MFE,
327 MachineBasicBlock::const_iterator MBBI)
328 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI) {
329 LastStateChange.PreviousEndLabel = nullptr;
330 LastStateChange.NewStartLabel = nullptr;
331 LastStateChange.NewState = NullState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000332 scan();
333 }
334
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000335public:
336 static iterator_range<InvokeStateChangeIterator>
337 range(WinEHFuncInfo &EHInfo, const MachineFunction &MF) {
338 // Reject empty MFs to simplify bookkeeping by ensuring that we can get the
339 // end of the last block.
340 assert(!MF.empty());
341 auto FuncBegin = MF.begin();
342 auto FuncEnd = MF.end();
343 auto BlockBegin = FuncBegin->begin();
344 auto BlockEnd = MF.back().end();
345 return make_range(
346 InvokeStateChangeIterator(EHInfo, FuncBegin, FuncEnd, BlockBegin),
347 InvokeStateChangeIterator(EHInfo, FuncEnd, FuncEnd, BlockEnd));
348 }
349 static iterator_range<InvokeStateChangeIterator>
350 range(WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
351 MachineFunction::const_iterator End) {
352 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
353 // the end of the last block.
354 assert(Begin != End);
355 auto BlockBegin = Begin->begin();
356 auto BlockEnd = std::prev(End)->end();
357 return make_range(InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin),
358 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd));
359 }
360
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000361 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000362 bool operator==(const InvokeStateChangeIterator &O) const {
363 // Must be visiting same block.
364 if (MFI != O.MFI)
365 return false;
366 // Must be visiting same isntr.
367 if (MBBI != O.MBBI)
368 return false;
369 // At end of block/instr iteration, we can still have two distinct states:
370 // one to report the final EndLabel, and another indicating the end of the
371 // state change iteration. Check for CurrentEndLabel equality to
372 // distinguish these.
373 return CurrentEndLabel == O.CurrentEndLabel;
374 }
375
376 bool operator!=(const InvokeStateChangeIterator &O) const {
377 return !operator==(O);
378 }
379 InvokeStateChange &operator*() { return LastStateChange; }
380 InvokeStateChange *operator->() { return &LastStateChange; }
381 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000382
383private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000384 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000385
386 WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000387 const MCSymbol *CurrentEndLabel = nullptr;
388 MachineFunction::const_iterator MFI;
389 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000390 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000391 InvokeStateChange LastStateChange;
392 bool VisitingInvoke = false;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000393};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000394
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000395} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000396
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000397InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
398 bool IsNewBlock = false;
399 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
400 if (IsNewBlock)
401 MBBI = MFI->begin();
402 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
403 const MachineInstr &MI = *MBBI;
404 if (!VisitingInvoke && LastStateChange.NewState != NullState &&
405 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
406 // Indicate a change of state to the null state. We don't have
407 // start/end EH labels handy but the caller won't expect them for
408 // null state regions.
409 LastStateChange.PreviousEndLabel = CurrentEndLabel;
410 LastStateChange.NewStartLabel = nullptr;
411 LastStateChange.NewState = NullState;
412 CurrentEndLabel = nullptr;
413 // Don't re-visit this instr on the next scan
414 ++MBBI;
415 return *this;
416 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000417
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000418 // All other state changes are at EH labels before/after invokes.
419 if (!MI.isEHLabel())
420 continue;
421 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
422 if (Label == CurrentEndLabel) {
423 VisitingInvoke = false;
424 continue;
425 }
426 auto InvokeMapIter = EHInfo.InvokeToStateMap.find(Label);
427 // Ignore EH labels that aren't the ones inserted before an invoke
428 if (InvokeMapIter == EHInfo.InvokeToStateMap.end())
429 continue;
430 auto &StateAndEnd = InvokeMapIter->second;
431 int NewState = StateAndEnd.first;
432 // Ignore EH labels explicitly annotated with the null state (which
433 // can happen for invokes that unwind to a chain of endpads the last
434 // of which unwinds to caller). We'll see the subsequent invoke and
435 // report a transition to the null state same as we do for calls.
436 if (NewState == NullState)
437 continue;
438 // Keep track of the fact that we're between EH start/end labels so
439 // we know not to treat the inoke we'll see as unwinding to caller.
440 VisitingInvoke = true;
441 if (NewState == LastStateChange.NewState) {
442 // The state isn't actually changing here. Record the new end and
443 // keep going.
444 CurrentEndLabel = StateAndEnd.second;
445 continue;
446 }
447 // Found a state change to report
448 LastStateChange.PreviousEndLabel = CurrentEndLabel;
449 LastStateChange.NewStartLabel = Label;
450 LastStateChange.NewState = NewState;
451 // Start keeping track of the new current end
452 CurrentEndLabel = StateAndEnd.second;
453 // Don't re-visit this instr on the next scan
454 ++MBBI;
455 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000456 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000457 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000458 // Iteration hit the end of the block range.
459 if (LastStateChange.NewState != NullState) {
460 // Report the end of the last new state
461 LastStateChange.PreviousEndLabel = CurrentEndLabel;
462 LastStateChange.NewStartLabel = nullptr;
463 LastStateChange.NewState = NullState;
464 // Leave CurrentEndLabel non-null to distinguish this state from end.
465 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000466 return *this;
467 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000468 // We've reported all state changes and hit the end state.
469 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000470 return *this;
471}
472
Reid Kleckner0a57f652015-01-14 01:05:27 +0000473/// Emit the language-specific data that __C_specific_handler expects. This
474/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
475/// up after faults with __try, __except, and __finally. The typeinfo values
476/// are not really RTTI data, but pointers to filter functions that return an
477/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
478/// blocks and other cleanups, the landing pad label is zero, and the filter
479/// function is actually a cleanup handler with the same prototype. A catch-all
480/// entry is modeled with a null filter function field and a non-zero landing
481/// pad label.
482///
483/// Possible filter function return values:
484/// EXCEPTION_EXECUTE_HANDLER (1):
485/// Jump to the landing pad label after cleanups.
486/// EXCEPTION_CONTINUE_SEARCH (0):
487/// Continue searching this table or continue unwinding.
488/// EXCEPTION_CONTINUE_EXECUTION (-1):
489/// Resume execution at the trapping PC.
490///
491/// Inferred table structure:
492/// struct Table {
493/// int NumEntries;
494/// struct Entry {
495/// imagerel32 LabelStart;
496/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000497/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000498/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000499/// } Entries[NumEntries];
500/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000501void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000502 auto &OS = *Asm->OutStreamer;
503 MCContext &Ctx = Asm->OutContext;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000504
Reid Kleckner94b704c2015-09-09 21:10:03 +0000505 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
Reid Kleckner14e77352015-10-09 23:34:53 +0000506 // Use the assembler to compute the number of table entries through label
507 // difference and division.
508 MCSymbol *TableBegin =
509 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
510 MCSymbol *TableEnd =
511 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
512 const MCExpr *LabelDiff =
513 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
514 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
515 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
516 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
517 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000518
Reid Kleckner14e77352015-10-09 23:34:53 +0000519 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000520
Reid Kleckner14e77352015-10-09 23:34:53 +0000521 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
522 // models exceptions from invokes. LLVM also allows arbitrary reordering of
523 // the code, so our tables end up looking a bit different. Rather than
524 // trying to match MSVC's tables exactly, we emit a denormalized table. For
525 // each range of invokes in the same state, we emit table entries for all
526 // the actions that would be taken in that state. This means our tables are
527 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000528 const MCSymbol *LastStartLabel = nullptr;
529 int LastEHState = -1;
530 // Break out before we enter into a finally funclet.
531 // FIXME: We need to emit separate EH tables for cleanups.
532 MachineFunction::const_iterator End = MF->end();
533 MachineFunction::const_iterator Stop = std::next(MF->begin());
534 while (Stop != End && !Stop->isEHFuncletEntry())
535 ++Stop;
536 for (const auto &StateChange :
537 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
538 // Emit all the actions for the state we just transitioned out of
539 // if it was not the null state
540 if (LastEHState != -1)
541 emitSEHActionsForRange(FuncInfo, LastStartLabel,
542 StateChange.PreviousEndLabel, LastEHState);
543 LastStartLabel = StateChange.NewStartLabel;
544 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000545 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000546
Reid Kleckner14e77352015-10-09 23:34:53 +0000547 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000548}
David Majnemercde33032015-03-30 22:58:10 +0000549
Reid Klecknerd880dc72015-10-09 20:39:39 +0000550void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000551 const MCSymbol *BeginLabel,
552 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000553 auto &OS = *Asm->OutStreamer;
554 MCContext &Ctx = Asm->OutContext;
555
556 assert(BeginLabel && EndLabel);
557 while (State != -1) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000558 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
559 const MCExpr *FilterOrFinally;
560 const MCExpr *ExceptOrNull;
561 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
562 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000563 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000564 ExceptOrNull = MCConstantExpr::create(0, Ctx);
565 } else {
566 // For an except, the filter can be 1 (catch-all) or a function
567 // label.
568 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
569 : MCConstantExpr::create(1, Ctx);
570 ExceptOrNull = create32bitRef(Handler->getSymbol());
571 }
572
573 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
574 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
575 OS.EmitValue(FilterOrFinally, 4);
576 OS.EmitValue(ExceptOrNull, 4);
577
578 assert(UME.ToState < State && "states should decrease");
579 State = UME.ToState;
580 }
581}
582
Reid Kleckner60b640b2015-05-28 22:47:01 +0000583void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000584 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000585 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000586 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000587
Reid Kleckner813f1b62015-09-16 22:14:46 +0000588 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000589
Reid Klecknerc71d6272015-09-28 23:56:30 +0000590 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000591 MCSymbol *FuncInfoXData = nullptr;
592 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000593 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
594 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000595 FuncInfoXData =
596 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000597 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000598 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000599 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
600 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000601 }
602
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000603 int UnwindHelpOffset = 0;
604 if (Asm->MAI->usesWindowsCFI())
605 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
606
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000607 MCSymbol *UnwindMapXData = nullptr;
608 MCSymbol *TryBlockMapXData = nullptr;
609 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000610 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000611 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000612 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000613 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000614 TryBlockMapXData =
615 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000616 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000617 IPToStateXData =
618 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000619
620 // FuncInfo {
621 // uint32_t MagicNumber
622 // int32_t MaxState;
623 // UnwindMapEntry *UnwindMap;
624 // uint32_t NumTryBlocks;
625 // TryBlockMapEntry *TryBlockMap;
626 // uint32_t IPMapEntries; // always 0 for x86
627 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
628 // uint32_t UnwindHelp; // non-x86 only
629 // ESTypeList *ESTypeList;
630 // int32_t EHFlags;
631 // }
632 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
633 // EHFlags & 2 -> ???
634 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000635 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000636 OS.EmitLabel(FuncInfoXData);
637 OS.EmitIntValue(0x19930522, 4); // MagicNumber
Reid Kleckner14e77352015-10-09 23:34:53 +0000638 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4); // MaxState
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000639 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
640 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
641 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
Reid Klecknerc71d6272015-09-28 23:56:30 +0000642 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000643 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
644 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000645 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000646 OS.EmitIntValue(0, 4); // ESTypeList
647 OS.EmitIntValue(1, 4); // EHFlags
648
649 // UnwindMapEntry {
650 // int32_t ToState;
651 // void (*Action)();
652 // };
653 if (UnwindMapXData) {
654 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000655 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000656 MCSymbol *CleanupSym =
657 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
Reid Kleckner78783912015-09-10 00:25:23 +0000658 OS.EmitIntValue(UME.ToState, 4); // ToState
659 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000660 }
661 }
662
663 // TryBlockMap {
664 // int32_t TryLow;
665 // int32_t TryHigh;
666 // int32_t CatchHigh;
667 // int32_t NumCatches;
668 // HandlerType *HandlerArray;
669 // };
670 if (TryBlockMapXData) {
671 OS.EmitLabel(TryBlockMapXData);
672 SmallVector<MCSymbol *, 1> HandlerMaps;
673 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
674 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000675
Reid Kleckner813f1b62015-09-16 22:14:46 +0000676 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000677 if (!TBME.HandlerArray.empty())
678 HandlerMapXData =
679 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
680 .concat(Twine(I))
681 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000682 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000683 HandlerMaps.push_back(HandlerMapXData);
684
Reid Kleckner813f1b62015-09-16 22:14:46 +0000685 // TBMEs should form intervals.
686 assert(0 <= TBME.TryLow && "bad trymap interval");
687 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
688 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000689 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000690 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000691
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000692 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
693 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000694 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000695 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
696 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
697 }
698
699 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
700 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
701 MCSymbol *HandlerMapXData = HandlerMaps[I];
702 if (!HandlerMapXData)
703 continue;
704 // HandlerType {
705 // int32_t Adjectives;
706 // TypeDescriptor *Type;
707 // int32_t CatchObjOffset;
708 // void (*Handler)();
709 // int32_t ParentFrameOffset; // x64 only
710 // };
711 OS.EmitLabel(HandlerMapXData);
712 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
713 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000714 // the index is INT_MAX, then there is no catch object, and we should
715 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000716 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000717 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000718 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
Reid Klecknerb005d282015-09-16 20:16:27 +0000719 // For 32-bit, the catch object offset is relative to the end of the
720 // EH registration node. For 64-bit, it's relative to SP at the end of
721 // the prologue.
722 if (!shouldEmitPersonality) {
723 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
724 Offset += FuncInfo.EHRegNodeEndOffset;
725 }
726 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000727 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000728 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000729 }
730
David Majnemerbfa5b982015-10-10 00:04:29 +0000731 MCSymbol *HandlerSym =
732 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000733
734 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
735 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
736 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
737 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000738
739 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000740 // Keep this in sync with X86FrameLowering::emitPrologue.
741 int ParentFrameOffset =
742 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
743 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000744 }
745 }
746 }
747 }
748
749 // IPToStateMapEntry {
750 // void *IP;
751 // int32_t State;
752 // };
753 if (IPToStateXData) {
754 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000755 for (auto &IPStatePair : IPToStateTable) {
756 OS.EmitValue(IPStatePair.first, 4); // IP
757 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000758 }
759 }
760}
761
Reid Klecknerc71d6272015-09-28 23:56:30 +0000762void WinException::computeIP2StateTable(
763 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
764 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000765 // Indicate that all calls from the prologue to the first invoke unwind to
766 // caller. We handle this as a special case since other ranges starting at end
767 // labels need to use LtmpN+1.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000768 MCSymbol *StartLabel = Asm->getFunctionBegin();
769 assert(StartLabel && "need local function start label");
770 IPToStateTable.push_back(std::make_pair(create32bitRef(StartLabel), -1));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000771
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000772 // FIXME: Do we need to emit entries for funclet base states?
773 for (const auto &StateChange :
774 InvokeStateChangeIterator::range(FuncInfo, *MF)) {
775 // Compute the label to report as the start of this entry; use the EH start
776 // label for the invoke if we have one, otherwise (this is a call which may
777 // unwind to our caller and does not have an EH start label, so) use the
778 // previous end label.
779 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
780 if (!ChangeLabel)
781 ChangeLabel = StateChange.PreviousEndLabel;
782 // Emit an entry indicating that PCs after 'Label' have this EH state.
783 IPToStateTable.push_back(
784 std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000785 }
David Majnemercde33032015-03-30 22:58:10 +0000786}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000787
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000788void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
789 StringRef FLinkageName) {
790 // Outlined helpers called by the EH runtime need to know the offset of the EH
791 // registration in order to recover the parent frame pointer. Now that we know
792 // we've code generated the parent, we can emit the label assignment that
793 // those helpers use to get the offset of the registration node.
794 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000795 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000796 MCSymbol *ParentFrameOffset =
797 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
798 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
799 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
800 const MCExpr *RegistrationOffsetSymRef =
801 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
802 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
803}
804
Reid Klecknerf12c0302015-06-09 21:42:19 +0000805/// Emit the language-specific data that _except_handler3 and 4 expect. This is
806/// functionally equivalent to the __C_specific_handler table, except it is
807/// indexed by state number instead of IP.
808void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000809 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000810 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000811 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000812
813 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
814 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000815
816 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000817 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000818 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000819 OS.EmitLabel(LSDALabel);
820
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000821 const Function *Per =
822 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000823 StringRef PerName = Per->getName();
824 int BaseState = -1;
825 if (PerName == "_except_handler4") {
826 // The LSDA for _except_handler4 starts with this struct, followed by the
827 // scope table:
828 //
829 // struct EH4ScopeTable {
830 // int32_t GSCookieOffset;
831 // int32_t GSCookieXOROffset;
832 // int32_t EHCookieOffset;
833 // int32_t EHCookieXOROffset;
834 // ScopeTableEntry ScopeRecord[];
835 // };
836 //
837 // Only the EHCookieOffset field appears to vary, and it appears to be the
838 // offset from the final saved SP value to the retaddr.
839 OS.EmitIntValue(-2, 4);
840 OS.EmitIntValue(0, 4);
841 // FIXME: Calculate.
842 OS.EmitIntValue(9999, 4);
843 OS.EmitIntValue(0, 4);
844 BaseState = -2;
845 }
846
Reid Kleckner14e77352015-10-09 23:34:53 +0000847 assert(!FuncInfo.SEHUnwindMap.empty());
848 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
849 MCSymbol *ExceptOrFinally =
850 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
851 // -1 is usually the base state for "unwind to caller", but for
852 // _except_handler4 it's -2. Do that replacement here if necessary.
853 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
854 OS.EmitIntValue(ToState, 4); // ToState
855 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
856 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
Reid Klecknerf12c0302015-06-09 21:42:19 +0000857 }
858}