blob: f4a279e5fe8651b5e7c08159f3bc76a5e0ccff76 [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"
Charles Davis91ed7992011-05-27 23:47:32 +000041using namespace llvm;
42
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000043WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
44 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
45 // platforms use an imagerel32 relocation to refer to symbols.
46 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
47}
Charles Davis91ed7992011-05-27 23:47:32 +000048
Reid Kleckner60b640b2015-05-28 22:47:01 +000049WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000050
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000051/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000052/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000053void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000054 auto &OS = *Asm->OutStreamer;
55 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000056 for (const Function &F : *M)
57 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000058 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000059}
60
Reid Kleckner60b640b2015-05-28 22:47:01 +000061void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000062 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
63
64 // If any landing pads survive, we need an EH table.
65 bool hasLandingPads = !MMI->getLandingPads().empty();
Reid Kleckner0e288232015-08-27 23:27:47 +000066 bool hasEHFunclets = MMI->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000067
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000068 const Function *F = MF->getFunction();
69 const Function *ParentF = MMI->getWinEHParent(F);
70
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.
93 // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
94 // this once WinEHPrepare stops doing that.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000095 if (!Asm->MAI->usesWindowsCFI()) {
Reid Kleckner0e288232015-08-27 23:27:47 +000096 shouldEmitLSDA =
97 hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000098 shouldEmitPersonality = false;
99 return;
100 }
David Majnemera225a192015-03-31 22:35:44 +0000101
David Majnemera80c1512015-09-29 20:12:33 +0000102 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000103}
104
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000105/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000106///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000107void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000108 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000109 return;
110
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000111 const Function *F = MF->getFunction();
112 EHPersonality Per = EHPersonality::Unknown;
113 if (F->hasPersonalityFn())
114 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000115
116 // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
117 // Windows EH schemes, the landing pad is not actually reachable. It only
118 // exists so that we can emit the right table data.
119 if (!isMSVCEHPersonality(Per))
120 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000121
David Majnemera80c1512015-09-29 20:12:33 +0000122 endFunclet();
123
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000124 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000125 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000126
David Majnemera80c1512015-09-29 20:12:33 +0000127 // Just switch sections to the right xdata section. This use of CurrentFnSym
128 // assumes that we only emit the LSDA when ending the parent function.
129 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
130 Asm->OutContext);
131 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000132
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000133 // Emit the tables appropriate to the personality function in use. If we
134 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000135 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000136 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000137 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000138 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000139 else if (Per == EHPersonality::MSVC_CXX)
140 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000141 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000142 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000143
Lang Hames9ff69c82015-04-24 19:11:51 +0000144 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000145 }
David Majnemera80c1512015-09-29 20:12:33 +0000146}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000147
David Majnemera80c1512015-09-29 20:12:33 +0000148/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
149/// are used in the old WinEH scheme, and they will be removed eventually.
150static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
151 if (!Handler)
152 return nullptr;
153 if (Handler.is<const MachineBasicBlock *>()) {
154 auto *MBB = Handler.get<const MachineBasicBlock *>();
155 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");
167 }
168 return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
169}
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) {
178 Sym = getMCSymbolForMBBOrGV(Asm, &MBB);
179
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
240 // If this is a C++ catch funclet (or the parent function),
241 // emit a reference to the LSDA for the parent function.
242 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
243 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
244 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
245 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
246 Twine("$cppxdata$", FuncLinkageName));
247 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
248 }
249
250 // Switch back to the previous section now that we are done writing to
251 // .xdata.
252 Asm->OutStreamer->PopSection();
253
254 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000255 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000256 }
257
258 // Let's make sure we don't try to end the same funclet twice.
259 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000260}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000261
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000262const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000263 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000264 return MCConstantExpr::create(0, Asm->OutContext);
265 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000266 ? MCSymbolRefExpr::VK_COFF_IMGREL32
267 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000268 Asm->OutContext);
269}
270
David Majnemer0ad363e2015-08-18 19:07:12 +0000271const MCExpr *WinException::create32bitRef(const Value *V) {
272 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000273 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000274 // FIXME: Delete the GlobalValue case once the new IR is fully functional.
275 if (const auto *GV = dyn_cast<GlobalValue>(V))
276 return create32bitRef(Asm->getSymbol(GV));
277 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000278}
279
Reid Klecknerc71d6272015-09-28 23:56:30 +0000280const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
281 return MCBinaryExpr::createAdd(create32bitRef(Label),
282 MCConstantExpr::create(1, Asm->OutContext),
283 Asm->OutContext);
284}
285
Reid Kleckner0a57f652015-01-14 01:05:27 +0000286/// Emit the language-specific data that __C_specific_handler expects. This
287/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
288/// up after faults with __try, __except, and __finally. The typeinfo values
289/// are not really RTTI data, but pointers to filter functions that return an
290/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
291/// blocks and other cleanups, the landing pad label is zero, and the filter
292/// function is actually a cleanup handler with the same prototype. A catch-all
293/// entry is modeled with a null filter function field and a non-zero landing
294/// pad label.
295///
296/// Possible filter function return values:
297/// EXCEPTION_EXECUTE_HANDLER (1):
298/// Jump to the landing pad label after cleanups.
299/// EXCEPTION_CONTINUE_SEARCH (0):
300/// Continue searching this table or continue unwinding.
301/// EXCEPTION_CONTINUE_EXECUTION (-1):
302/// Resume execution at the trapping PC.
303///
304/// Inferred table structure:
305/// struct Table {
306/// int NumEntries;
307/// struct Entry {
308/// imagerel32 LabelStart;
309/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000310/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000311/// imagerel32 LabelLPad; // Zero means __finally.
312/// } Entries[NumEntries];
313/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000314void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Kleckner0a57f652015-01-14 01:05:27 +0000315 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
316
Reid Kleckner94b704c2015-09-09 21:10:03 +0000317 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
318 if (!FuncInfo.SEHUnwindMap.empty())
319 report_fatal_error("x64 SEH tables not yet implemented");
320
Reid Kleckner0a57f652015-01-14 01:05:27 +0000321 // Simplifying assumptions for first implementation:
322 // - Cleanups are not implemented.
323 // - Filters are not implemented.
324
325 // The Itanium LSDA table sorts similar landing pads together to simplify the
326 // actions table, but we don't need that.
327 SmallVector<const LandingPadInfo *, 64> LandingPads;
328 LandingPads.reserve(PadInfos.size());
329 for (const auto &LP : PadInfos)
330 LandingPads.push_back(&LP);
331
332 // Compute label ranges for call sites as we would for the Itanium LSDA, but
333 // use an all zero action table because we aren't using these actions.
334 SmallVector<unsigned, 64> FirstActions;
335 FirstActions.resize(LandingPads.size());
336 SmallVector<CallSiteEntry, 64> CallSites;
337 computeCallSiteTable(CallSites, LandingPads, FirstActions);
338
Rafael Espindola629cdba2015-02-27 18:18:39 +0000339 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
340 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000341
342 // Emit the number of table entries.
343 unsigned NumEntries = 0;
344 for (const CallSiteEntry &CSE : CallSites) {
345 if (!CSE.LPad)
346 continue; // Ignore gaps.
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000347 NumEntries += CSE.LPad->SEHHandlers.size();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000348 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000349 Asm->OutStreamer->EmitIntValue(NumEntries, 4);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000350
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000351 // If there are no actions, we don't need to iterate again.
352 if (NumEntries == 0)
353 return;
354
Reid Kleckner0a57f652015-01-14 01:05:27 +0000355 // Emit the four-label records for each call site entry. The table has to be
356 // sorted in layout order, and the call sites should already be sorted.
357 for (const CallSiteEntry &CSE : CallSites) {
358 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
359 // an EH table entry will propagate the exception rather than terminating
360 // the program.
361 if (!CSE.LPad)
362 continue;
363 const LandingPadInfo *LPad = CSE.LPad;
364
365 // Compute the label range. We may reuse the function begin and end labels
366 // rather than forming new ones.
367 const MCExpr *Begin =
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000368 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000369 const MCExpr *End;
370 if (CSE.EndLabel) {
371 // The interval is half-open, so we have to add one to include the return
372 // address of the last invoke in the range.
Reid Klecknerc71d6272015-09-28 23:56:30 +0000373 End = getLabelPlusOne(CSE.EndLabel);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000374 } else {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000375 End = create32bitRef(EHFuncEndSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000376 }
377
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000378 // Emit an entry for each action.
379 for (SEHHandler Handler : LPad->SEHHandlers) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000380 Asm->OutStreamer->EmitValue(Begin, 4);
381 Asm->OutStreamer->EmitValue(End, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000382
383 // Emit the filter or finally function pointer, if present. Otherwise,
384 // emit '1' to indicate a catch-all.
385 const Function *F = Handler.FilterOrFinally;
386 if (F)
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000387 Asm->OutStreamer->EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000388 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000389 Asm->OutStreamer->EmitIntValue(1, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000390
391 // Emit the recovery address, if present. Otherwise, this must be a
392 // finally.
393 const BlockAddress *BA = Handler.RecoverBA;
394 if (BA)
Lang Hames9ff69c82015-04-24 19:11:51 +0000395 Asm->OutStreamer->EmitValue(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000396 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000397 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000398 Asm->OutStreamer->EmitIntValue(0, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000399 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000400 }
401}
David Majnemercde33032015-03-30 22:58:10 +0000402
Reid Kleckner60b640b2015-05-28 22:47:01 +0000403void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000404 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000405 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000406 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000407
Reid Kleckner813f1b62015-09-16 22:14:46 +0000408 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000409
Reid Klecknerc71d6272015-09-28 23:56:30 +0000410 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000411 MCSymbol *FuncInfoXData = nullptr;
412 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000413 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
414 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000415 FuncInfoXData =
416 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000417 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000418 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000419 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
420 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000421 }
422
423 MCSymbol *UnwindMapXData = nullptr;
424 MCSymbol *TryBlockMapXData = nullptr;
425 MCSymbol *IPToStateXData = nullptr;
426 if (!FuncInfo.UnwindMap.empty())
427 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000428 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000429 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000430 TryBlockMapXData =
431 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000432 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000433 IPToStateXData =
434 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000435
436 // FuncInfo {
437 // uint32_t MagicNumber
438 // int32_t MaxState;
439 // UnwindMapEntry *UnwindMap;
440 // uint32_t NumTryBlocks;
441 // TryBlockMapEntry *TryBlockMap;
442 // uint32_t IPMapEntries; // always 0 for x86
443 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
444 // uint32_t UnwindHelp; // non-x86 only
445 // ESTypeList *ESTypeList;
446 // int32_t EHFlags;
447 // }
448 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
449 // EHFlags & 2 -> ???
450 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000451 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000452 OS.EmitLabel(FuncInfoXData);
453 OS.EmitIntValue(0x19930522, 4); // MagicNumber
454 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
455 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
456 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
457 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
Reid Klecknerc71d6272015-09-28 23:56:30 +0000458 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000459 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
460 if (Asm->MAI->usesWindowsCFI())
461 OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
462 OS.EmitIntValue(0, 4); // ESTypeList
463 OS.EmitIntValue(1, 4); // EHFlags
464
465 // UnwindMapEntry {
466 // int32_t ToState;
467 // void (*Action)();
468 // };
469 if (UnwindMapXData) {
470 OS.EmitLabel(UnwindMapXData);
471 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
Reid Kleckner78783912015-09-10 00:25:23 +0000472 MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
473 OS.EmitIntValue(UME.ToState, 4); // ToState
474 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000475 }
476 }
477
478 // TryBlockMap {
479 // int32_t TryLow;
480 // int32_t TryHigh;
481 // int32_t CatchHigh;
482 // int32_t NumCatches;
483 // HandlerType *HandlerArray;
484 // };
485 if (TryBlockMapXData) {
486 OS.EmitLabel(TryBlockMapXData);
487 SmallVector<MCSymbol *, 1> HandlerMaps;
488 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
489 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000490
Reid Kleckner813f1b62015-09-16 22:14:46 +0000491 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000492 if (!TBME.HandlerArray.empty())
493 HandlerMapXData =
494 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
495 .concat(Twine(I))
496 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000497 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000498 HandlerMaps.push_back(HandlerMapXData);
499
Reid Kleckner813f1b62015-09-16 22:14:46 +0000500 // TBMEs should form intervals.
501 assert(0 <= TBME.TryLow && "bad trymap interval");
502 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
503 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
504 assert(TBME.CatchHigh < int(FuncInfo.UnwindMap.size()) &&
505 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000506
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000507 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
508 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000509 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000510 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
511 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
512 }
513
514 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
515 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
516 MCSymbol *HandlerMapXData = HandlerMaps[I];
517 if (!HandlerMapXData)
518 continue;
519 // HandlerType {
520 // int32_t Adjectives;
521 // TypeDescriptor *Type;
522 // int32_t CatchObjOffset;
523 // void (*Handler)();
524 // int32_t ParentFrameOffset; // x64 only
525 // };
526 OS.EmitLabel(HandlerMapXData);
527 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
528 // Get the frame escape label with the offset of the catch object. If
529 // the index is -1, then there is no catch object, and we should emit an
530 // offset of zero, indicating that no copy will occur.
531 const MCExpr *FrameAllocOffsetRef = nullptr;
532 if (HT.CatchObjRecoverIdx >= 0) {
533 MCSymbol *FrameAllocOffset =
534 Asm->OutContext.getOrCreateFrameAllocSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000535 FuncLinkageName, HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000536 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000537 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
Reid Klecknerb005d282015-09-16 20:16:27 +0000538 } else if (HT.CatchObj.FrameOffset != INT_MAX) {
539 int Offset = HT.CatchObj.FrameOffset;
540 // For 32-bit, the catch object offset is relative to the end of the
541 // EH registration node. For 64-bit, it's relative to SP at the end of
542 // the prologue.
543 if (!shouldEmitPersonality) {
544 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
545 Offset += FuncInfo.EHRegNodeEndOffset;
546 }
547 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000548 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000549 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000550 }
551
Reid Kleckner94b704c2015-09-09 21:10:03 +0000552 MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
553
554 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
555 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
556 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
557 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000558
559 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000560 // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
561 // Keep this in sync with X86FrameLowering::emitPrologue.
562 int ParentFrameOffset =
563 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
564 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000565 }
566 }
567 }
568 }
569
570 // IPToStateMapEntry {
571 // void *IP;
572 // int32_t State;
573 // };
574 if (IPToStateXData) {
575 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000576 for (auto &IPStatePair : IPToStateTable) {
577 OS.EmitValue(IPStatePair.first, 4); // IP
578 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000579 }
580 }
581}
582
Reid Klecknerc71d6272015-09-28 23:56:30 +0000583void WinException::computeIP2StateTable(
584 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
585 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
David Majnemercde33032015-03-30 22:58:10 +0000586 // Whether there is a potentially throwing instruction (currently this means
587 // an ordinary call) between the end of the previous try-range and now.
Reid Klecknerc71d6272015-09-28 23:56:30 +0000588 bool SawPotentiallyThrowing = true;
David Majnemercde33032015-03-30 22:58:10 +0000589
Reid Klecknerc71d6272015-09-28 23:56:30 +0000590 // Remember what state we were in the last time we found a begin try label.
591 // This allows us to coalesce many nearby invokes with the same state into one
592 // entry.
593 int LastEHState = -1;
594 MCSymbol *LastEndLabel = Asm->getFunctionBegin();
595 assert(LastEndLabel && "need local function start label");
David Majnemercde33032015-03-30 22:58:10 +0000596
Reid Klecknerc71d6272015-09-28 23:56:30 +0000597 // Indicate that all calls from the prologue to the first invoke unwind to
598 // caller. We handle this as a special case since other ranges starting at end
599 // labels need to use LtmpN+1.
600 IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000601
David Majnemercde33032015-03-30 22:58:10 +0000602 for (const auto &MBB : *MF) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000603 // FIXME: Do we need to emit entries for funclet base states?
604
David Majnemercde33032015-03-30 22:58:10 +0000605 for (const auto &MI : MBB) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000606 // Find all the EH_LABEL instructions, tracking if we've crossed a
607 // potentially throwing call since the last label.
David Majnemercde33032015-03-30 22:58:10 +0000608 if (!MI.isEHLabel()) {
609 if (MI.isCall())
610 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
611 continue;
612 }
613
Reid Klecknerc71d6272015-09-28 23:56:30 +0000614 // If this was an end label, return SawPotentiallyThrowing to the start
615 // state and keep going. Otherwise, we will consider the call between the
616 // begin/end labels to be a potentially throwing call and generate extra
617 // table entries.
618 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
619 if (Label == LastEndLabel)
David Majnemercde33032015-03-30 22:58:10 +0000620 SawPotentiallyThrowing = false;
621
Reid Klecknerc71d6272015-09-28 23:56:30 +0000622 // Check if this was a begin label. Otherwise, it must be an end label or
623 // some random label, and we should continue.
624 auto StateAndEnd = FuncInfo.InvokeToStateMap.find(Label);
625 if (StateAndEnd == FuncInfo.InvokeToStateMap.end())
David Majnemercde33032015-03-30 22:58:10 +0000626 continue;
627
Reid Klecknerc71d6272015-09-28 23:56:30 +0000628 // Extract the state and end label.
629 int State;
630 MCSymbol *EndLabel;
631 std::tie(State, EndLabel) = StateAndEnd->second;
David Majnemercde33032015-03-30 22:58:10 +0000632
Reid Klecknerc71d6272015-09-28 23:56:30 +0000633 // If there was a potentially throwing call between this begin label and
634 // the last end label, we need an extra base state entry to indicate that
635 // those calls unwind directly to the caller.
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000636 if (SawPotentiallyThrowing && LastEHState != -1) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000637 IPToStateTable.push_back(
638 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
David Majnemercde33032015-03-30 22:58:10 +0000639 SawPotentiallyThrowing = false;
640 LastEHState = -1;
641 }
642
Reid Klecknerc71d6272015-09-28 23:56:30 +0000643 // Emit an entry indicating that PCs after 'Label' have this EH state.
644 if (State != LastEHState)
645 IPToStateTable.push_back(std::make_pair(create32bitRef(Label), State));
646 LastEHState = State;
647 LastEndLabel = EndLabel;
David Majnemercde33032015-03-30 22:58:10 +0000648 }
649 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000650
651 if (LastEndLabel != Asm->getFunctionBegin()) {
652 // Indicate that all calls from the last invoke until the epilogue unwind to
653 // caller. This also ensures that we have at least one ip2state entry, if
654 // somehow all invokes were deleted during CodeGen.
655 IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
656 }
David Majnemercde33032015-03-30 22:58:10 +0000657}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000658
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000659void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
660 StringRef FLinkageName) {
661 // Outlined helpers called by the EH runtime need to know the offset of the EH
662 // registration in order to recover the parent frame pointer. Now that we know
663 // we've code generated the parent, we can emit the label assignment that
664 // those helpers use to get the offset of the registration node.
665 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000666 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000667 MCSymbol *ParentFrameOffset =
668 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
669 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
670 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
671 const MCExpr *RegistrationOffsetSymRef =
672 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
673 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
674}
675
Reid Klecknerf12c0302015-06-09 21:42:19 +0000676/// Emit the language-specific data that _except_handler3 and 4 expect. This is
677/// functionally equivalent to the __C_specific_handler table, except it is
678/// indexed by state number instead of IP.
679void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000680 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000681 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000682 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000683
684 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
685 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000686
687 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000688 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000689 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000690 OS.EmitLabel(LSDALabel);
691
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000692 const Function *Per =
693 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000694 StringRef PerName = Per->getName();
695 int BaseState = -1;
696 if (PerName == "_except_handler4") {
697 // The LSDA for _except_handler4 starts with this struct, followed by the
698 // scope table:
699 //
700 // struct EH4ScopeTable {
701 // int32_t GSCookieOffset;
702 // int32_t GSCookieXOROffset;
703 // int32_t EHCookieOffset;
704 // int32_t EHCookieXOROffset;
705 // ScopeTableEntry ScopeRecord[];
706 // };
707 //
708 // Only the EHCookieOffset field appears to vary, and it appears to be the
709 // offset from the final saved SP value to the retaddr.
710 OS.EmitIntValue(-2, 4);
711 OS.EmitIntValue(0, 4);
712 // FIXME: Calculate.
713 OS.EmitIntValue(9999, 4);
714 OS.EmitIntValue(0, 4);
715 BaseState = -2;
716 }
717
Reid Kleckner94b704c2015-09-09 21:10:03 +0000718 if (!FuncInfo.SEHUnwindMap.empty()) {
719 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
720 MCSymbol *ExceptOrFinally =
721 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
722 OS.EmitIntValue(UME.ToState, 4); // ToState
723 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
724 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
725 }
726 return;
727 }
728 // FIXME: The following code is for the old landingpad-based SEH
729 // implementation. Remove it when possible.
730
Reid Klecknerf12c0302015-06-09 21:42:19 +0000731 // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
732 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
733 SmallVector<const LandingPadInfo *, 4> LPads;
734 LPads.reserve((PadInfos.size()));
735 for (const LandingPadInfo &LPInfo : PadInfos)
736 LPads.push_back(&LPInfo);
737 std::sort(LPads.begin(), LPads.end(),
738 [](const LandingPadInfo *L, const LandingPadInfo *R) {
739 return L->WinEHState < R->WinEHState;
740 });
741
742 // For each action in each lpad, emit one of these:
743 // struct ScopeTableEntry {
744 // int32_t EnclosingLevel;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000745 // int32_t (__cdecl *Filter)();
746 // void *HandlerOrFinally;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000747 // };
748 //
749 // The "outermost" action will use BaseState as its enclosing level. Each
750 // other action will refer to the previous state as its enclosing level.
751 int CurState = 0;
752 for (const LandingPadInfo *LPInfo : LPads) {
753 int EnclosingLevel = BaseState;
Reid Kleckner7912d9b2015-06-10 00:04:53 +0000754 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
755 LPInfo->WinEHState &&
Reid Klecknerf12c0302015-06-09 21:42:19 +0000756 "gaps in the SEH scope table");
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000757 for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
758 I != E; ++I) {
759 const SEHHandler &Handler = *I;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000760 const BlockAddress *BA = Handler.RecoverBA;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000761 const Function *F = Handler.FilterOrFinally;
762 assert(F && "cannot catch all in 32-bit SEH without filter function");
763 const MCExpr *FilterOrNull =
764 create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
765 const MCExpr *ExceptOrFinally = create32bitRef(
766 BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
Reid Klecknerf12c0302015-06-09 21:42:19 +0000767
768 OS.EmitIntValue(EnclosingLevel, 4);
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000769 OS.EmitValue(FilterOrNull, 4);
770 OS.EmitValue(ExceptOrFinally, 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000771
772 // The next state unwinds to this state.
773 EnclosingLevel = CurState;
774 CurState++;
775 }
776 }
777}