blob: 2bd9af55c30f50b2ee9c2a96f588f51672709f1b [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/Dwarf.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000036#include "llvm/Target/TargetFrameLowering.h"
37#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000038#include "llvm/Target/TargetOptions.h"
39#include "llvm/Target/TargetRegisterInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000040using namespace llvm;
41
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000042WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
43 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
44 // platforms use an imagerel32 relocation to refer to symbols.
45 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
46}
Charles Davis91ed7992011-05-27 23:47:32 +000047
Reid Kleckner60b640b2015-05-28 22:47:01 +000048WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000049
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000050/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000051/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000052void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000053 auto &OS = *Asm->OutStreamer;
54 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000055 for (const Function &F : *M)
56 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000057 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000058}
59
Reid Kleckner60b640b2015-05-28 22:47:01 +000060void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000061 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
62
63 // If any landing pads survive, we need an EH table.
64 bool hasLandingPads = !MMI->getLandingPads().empty();
65
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000066 const Function *F = MF->getFunction();
67 const Function *ParentF = MMI->getWinEHParent(F);
68
Charles Davis5638b9f2011-05-28 04:21:04 +000069 shouldEmitMoves = Asm->needsSEHMoves();
70
71 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
72 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000073 const Function *Per = MMI->getPersonality();
Charles Davis5638b9f2011-05-28 04:21:04 +000074
75 shouldEmitPersonality = hasLandingPads &&
76 PerEncoding != dwarf::DW_EH_PE_omit && Per;
77
78 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
79 shouldEmitLSDA = shouldEmitPersonality &&
80 LSDAEncoding != dwarf::DW_EH_PE_omit;
81
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000082 // If we're not using CFI, we don't want the CFI or the personality. Emit the
83 // LSDA if this is the parent function.
84 if (!Asm->MAI->usesWindowsCFI()) {
85 shouldEmitLSDA = (hasLandingPads && F == ParentF);
86 shouldEmitPersonality = false;
87 return;
88 }
David Majnemera225a192015-03-31 22:35:44 +000089
90 // If this was an outlined handler, we need to define the label corresponding
91 // to the offset of the parent frame relative to the stack pointer after the
92 // prologue.
David Majnemera225a192015-03-31 22:35:44 +000093 if (F != ParentF) {
94 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
95 auto I = FuncInfo.CatchHandlerParentFrameObjOffset.find(F);
96 if (I != FuncInfo.CatchHandlerParentFrameObjOffset.end()) {
97 MCSymbol *HandlerTypeParentFrameOffset =
98 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
99 GlobalValue::getRealLinkageName(F->getName()));
100
101 // Emit a symbol assignment.
Lang Hames9ff69c82015-04-24 19:11:51 +0000102 Asm->OutStreamer->EmitAssignment(
David Majnemera225a192015-03-31 22:35:44 +0000103 HandlerTypeParentFrameOffset,
Jim Grosbach13760bd2015-05-30 01:25:56 +0000104 MCConstantExpr::create(I->second, Asm->OutContext));
David Majnemera225a192015-03-31 22:35:44 +0000105 }
106 }
107
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000108 if (shouldEmitMoves || shouldEmitPersonality)
109 Asm->OutStreamer->EmitWinCFIStartProc(Asm->CurrentFnSym);
Charles Davis5638b9f2011-05-28 04:21:04 +0000110
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000111 if (shouldEmitPersonality) {
112 const MCSymbol *PersHandlerSym =
113 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
114 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
115 }
Charles Davis91ed7992011-05-27 23:47:32 +0000116}
117
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000118/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000119///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000120void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000121 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000122 return;
123
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000124 EHPersonality Per = MMI->getPersonalityType();
125
126 // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
127 // Windows EH schemes, the landing pad is not actually reachable. It only
128 // exists so that we can emit the right table data.
129 if (!isMSVCEHPersonality(Per))
130 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000131
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000132 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000133 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000134
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000135 if (shouldEmitMoves || shouldEmitPersonality) {
136 // Emit an UNWIND_INFO struct describing the prologue.
137 Asm->OutStreamer->EmitWinEHHandlerData();
138 } else {
139 // Just switch sections to the right xdata section. This use of
140 // CurrentFnSym assumes that we only emit the LSDA when ending the parent
141 // function.
142 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(
143 Asm->CurrentFnSym, Asm->OutContext);
144 Asm->OutStreamer->SwitchSection(XData);
145 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000146
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000147 // Emit the tables appropriate to the personality function in use. If we
148 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000149 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000150 emitCSpecificHandlerTable();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000151 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000152 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000153 else if (Per == EHPersonality::MSVC_CXX)
154 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000155 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000156 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000157
Lang Hames9ff69c82015-04-24 19:11:51 +0000158 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000159 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000160
161 if (shouldEmitMoves)
162 Asm->OutStreamer->EmitWinCFIEndProc();
Charles Davis91ed7992011-05-27 23:47:32 +0000163}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000164
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000165const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000166 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000167 return MCConstantExpr::create(0, Asm->OutContext);
168 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000169 ? MCSymbolRefExpr::VK_COFF_IMGREL32
170 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000171 Asm->OutContext);
172}
173
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000174const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
David Majnemercde33032015-03-30 22:58:10 +0000175 if (!GV)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000176 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000177 return create32bitRef(Asm->getSymbol(GV));
David Majnemercde33032015-03-30 22:58:10 +0000178}
179
Reid Kleckner0a57f652015-01-14 01:05:27 +0000180/// Emit the language-specific data that __C_specific_handler expects. This
181/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
182/// up after faults with __try, __except, and __finally. The typeinfo values
183/// are not really RTTI data, but pointers to filter functions that return an
184/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
185/// blocks and other cleanups, the landing pad label is zero, and the filter
186/// function is actually a cleanup handler with the same prototype. A catch-all
187/// entry is modeled with a null filter function field and a non-zero landing
188/// pad label.
189///
190/// Possible filter function return values:
191/// EXCEPTION_EXECUTE_HANDLER (1):
192/// Jump to the landing pad label after cleanups.
193/// EXCEPTION_CONTINUE_SEARCH (0):
194/// Continue searching this table or continue unwinding.
195/// EXCEPTION_CONTINUE_EXECUTION (-1):
196/// Resume execution at the trapping PC.
197///
198/// Inferred table structure:
199/// struct Table {
200/// int NumEntries;
201/// struct Entry {
202/// imagerel32 LabelStart;
203/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000204/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000205/// imagerel32 LabelLPad; // Zero means __finally.
206/// } Entries[NumEntries];
207/// };
Reid Kleckner60b640b2015-05-28 22:47:01 +0000208void WinException::emitCSpecificHandlerTable() {
Reid Kleckner0a57f652015-01-14 01:05:27 +0000209 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
210
211 // Simplifying assumptions for first implementation:
212 // - Cleanups are not implemented.
213 // - Filters are not implemented.
214
215 // The Itanium LSDA table sorts similar landing pads together to simplify the
216 // actions table, but we don't need that.
217 SmallVector<const LandingPadInfo *, 64> LandingPads;
218 LandingPads.reserve(PadInfos.size());
219 for (const auto &LP : PadInfos)
220 LandingPads.push_back(&LP);
221
222 // Compute label ranges for call sites as we would for the Itanium LSDA, but
223 // use an all zero action table because we aren't using these actions.
224 SmallVector<unsigned, 64> FirstActions;
225 FirstActions.resize(LandingPads.size());
226 SmallVector<CallSiteEntry, 64> CallSites;
227 computeCallSiteTable(CallSites, LandingPads, FirstActions);
228
Rafael Espindola629cdba2015-02-27 18:18:39 +0000229 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
230 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000231
232 // Emit the number of table entries.
233 unsigned NumEntries = 0;
234 for (const CallSiteEntry &CSE : CallSites) {
235 if (!CSE.LPad)
236 continue; // Ignore gaps.
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000237 NumEntries += CSE.LPad->SEHHandlers.size();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000238 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000239 Asm->OutStreamer->EmitIntValue(NumEntries, 4);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000240
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000241 // If there are no actions, we don't need to iterate again.
242 if (NumEntries == 0)
243 return;
244
Reid Kleckner0a57f652015-01-14 01:05:27 +0000245 // Emit the four-label records for each call site entry. The table has to be
246 // sorted in layout order, and the call sites should already be sorted.
247 for (const CallSiteEntry &CSE : CallSites) {
248 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
249 // an EH table entry will propagate the exception rather than terminating
250 // the program.
251 if (!CSE.LPad)
252 continue;
253 const LandingPadInfo *LPad = CSE.LPad;
254
255 // Compute the label range. We may reuse the function begin and end labels
256 // rather than forming new ones.
257 const MCExpr *Begin =
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000258 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000259 const MCExpr *End;
260 if (CSE.EndLabel) {
261 // The interval is half-open, so we have to add one to include the return
262 // address of the last invoke in the range.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000263 End = MCBinaryExpr::createAdd(create32bitRef(CSE.EndLabel),
264 MCConstantExpr::create(1, Asm->OutContext),
Reid Kleckner0a57f652015-01-14 01:05:27 +0000265 Asm->OutContext);
266 } else {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000267 End = create32bitRef(EHFuncEndSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000268 }
269
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000270 // Emit an entry for each action.
271 for (SEHHandler Handler : LPad->SEHHandlers) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000272 Asm->OutStreamer->EmitValue(Begin, 4);
273 Asm->OutStreamer->EmitValue(End, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000274
275 // Emit the filter or finally function pointer, if present. Otherwise,
276 // emit '1' to indicate a catch-all.
277 const Function *F = Handler.FilterOrFinally;
278 if (F)
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000279 Asm->OutStreamer->EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000280 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000281 Asm->OutStreamer->EmitIntValue(1, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000282
283 // Emit the recovery address, if present. Otherwise, this must be a
284 // finally.
285 const BlockAddress *BA = Handler.RecoverBA;
286 if (BA)
Lang Hames9ff69c82015-04-24 19:11:51 +0000287 Asm->OutStreamer->EmitValue(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000288 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000289 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000290 Asm->OutStreamer->EmitIntValue(0, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000291 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000292 }
293}
David Majnemercde33032015-03-30 22:58:10 +0000294
Reid Kleckner60b640b2015-05-28 22:47:01 +0000295void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000296 const Function *F = MF->getFunction();
297 const Function *ParentF = MMI->getWinEHParent(F);
Lang Hames9ff69c82015-04-24 19:11:51 +0000298 auto &OS = *Asm->OutStreamer;
David Majnemera225a192015-03-31 22:35:44 +0000299 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
David Majnemercde33032015-03-30 22:58:10 +0000300
301 StringRef ParentLinkageName =
302 GlobalValue::getRealLinkageName(ParentF->getName());
303
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000304 MCSymbol *FuncInfoXData = nullptr;
305 if (shouldEmitPersonality) {
306 FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
307 Twine("$cppxdata$", ParentLinkageName));
308 OS.EmitValue(create32bitRef(FuncInfoXData), 4);
309
310 extendIP2StateTable(MF, ParentF, FuncInfo);
311
312 // Defer emission until we've visited the parent function and all the catch
313 // handlers. Cleanups don't contribute to the ip2state table, so don't count
314 // them.
315 if (ParentF != F && !FuncInfo.CatchHandlerMaxState.count(F))
316 return;
317 ++FuncInfo.NumIPToStateFuncsVisited;
318 if (FuncInfo.NumIPToStateFuncsVisited != FuncInfo.CatchHandlerMaxState.size())
319 return;
320 } else {
321 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(ParentLinkageName);
322 }
323
324 MCSymbol *UnwindMapXData = nullptr;
325 MCSymbol *TryBlockMapXData = nullptr;
326 MCSymbol *IPToStateXData = nullptr;
327 if (!FuncInfo.UnwindMap.empty())
328 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
329 Twine("$stateUnwindMap$", ParentLinkageName));
330 if (!FuncInfo.TryBlockMap.empty())
331 TryBlockMapXData = Asm->OutContext.getOrCreateSymbol(
332 Twine("$tryMap$", ParentLinkageName));
333 if (!FuncInfo.IPToStateList.empty())
334 IPToStateXData = Asm->OutContext.getOrCreateSymbol(
335 Twine("$ip2state$", ParentLinkageName));
336
337 // FuncInfo {
338 // uint32_t MagicNumber
339 // int32_t MaxState;
340 // UnwindMapEntry *UnwindMap;
341 // uint32_t NumTryBlocks;
342 // TryBlockMapEntry *TryBlockMap;
343 // uint32_t IPMapEntries; // always 0 for x86
344 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
345 // uint32_t UnwindHelp; // non-x86 only
346 // ESTypeList *ESTypeList;
347 // int32_t EHFlags;
348 // }
349 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
350 // EHFlags & 2 -> ???
351 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
352 OS.EmitLabel(FuncInfoXData);
353 OS.EmitIntValue(0x19930522, 4); // MagicNumber
354 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
355 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
356 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
357 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
358 OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4); // IPMapEntries
359 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
360 if (Asm->MAI->usesWindowsCFI())
361 OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
362 OS.EmitIntValue(0, 4); // ESTypeList
363 OS.EmitIntValue(1, 4); // EHFlags
364
365 // UnwindMapEntry {
366 // int32_t ToState;
367 // void (*Action)();
368 // };
369 if (UnwindMapXData) {
370 OS.EmitLabel(UnwindMapXData);
371 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
372 OS.EmitIntValue(UME.ToState, 4); // ToState
373 OS.EmitValue(create32bitRef(UME.Cleanup), 4); // Action
374 }
375 }
376
377 // TryBlockMap {
378 // int32_t TryLow;
379 // int32_t TryHigh;
380 // int32_t CatchHigh;
381 // int32_t NumCatches;
382 // HandlerType *HandlerArray;
383 // };
384 if (TryBlockMapXData) {
385 OS.EmitLabel(TryBlockMapXData);
386 SmallVector<MCSymbol *, 1> HandlerMaps;
387 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
388 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
389 MCSymbol *HandlerMapXData = nullptr;
390
391 if (!TBME.HandlerArray.empty())
392 HandlerMapXData =
393 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
394 .concat(Twine(I))
395 .concat("$")
396 .concat(ParentLinkageName));
397
398 HandlerMaps.push_back(HandlerMapXData);
399
400 int CatchHigh = -1;
401 for (WinEHHandlerType &HT : TBME.HandlerArray)
402 CatchHigh =
403 std::max(CatchHigh, FuncInfo.CatchHandlerMaxState[HT.Handler]);
404
405 assert(TBME.TryLow <= TBME.TryHigh);
406 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
407 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
408 OS.EmitIntValue(CatchHigh, 4); // CatchHigh
409 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
410 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
411 }
412
413 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
414 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
415 MCSymbol *HandlerMapXData = HandlerMaps[I];
416 if (!HandlerMapXData)
417 continue;
418 // HandlerType {
419 // int32_t Adjectives;
420 // TypeDescriptor *Type;
421 // int32_t CatchObjOffset;
422 // void (*Handler)();
423 // int32_t ParentFrameOffset; // x64 only
424 // };
425 OS.EmitLabel(HandlerMapXData);
426 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
427 // Get the frame escape label with the offset of the catch object. If
428 // the index is -1, then there is no catch object, and we should emit an
429 // offset of zero, indicating that no copy will occur.
430 const MCExpr *FrameAllocOffsetRef = nullptr;
431 if (HT.CatchObjRecoverIdx >= 0) {
432 MCSymbol *FrameAllocOffset =
433 Asm->OutContext.getOrCreateFrameAllocSymbol(
434 GlobalValue::getRealLinkageName(ParentF->getName()),
435 HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000436 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000437 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
438 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000439 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000440 }
441
442 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
443 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
444 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
445 OS.EmitValue(create32bitRef(HT.Handler), 4); // Handler
446
447 if (shouldEmitPersonality) {
448 MCSymbol *ParentFrameOffset =
449 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
450 GlobalValue::getRealLinkageName(HT.Handler->getName()));
Jim Grosbach13760bd2015-05-30 01:25:56 +0000451 const MCSymbolRefExpr *ParentFrameOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000452 ParentFrameOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
453 OS.EmitValue(ParentFrameOffsetRef, 4); // ParentFrameOffset
454 }
455 }
456 }
457 }
458
459 // IPToStateMapEntry {
460 // void *IP;
461 // int32_t State;
462 // };
463 if (IPToStateXData) {
464 OS.EmitLabel(IPToStateXData);
465 for (auto &IPStatePair : FuncInfo.IPToStateList) {
466 OS.EmitValue(create32bitRef(IPStatePair.first), 4); // IP
467 OS.EmitIntValue(IPStatePair.second, 4); // State
468 }
469 }
470}
471
472void WinException::extendIP2StateTable(const MachineFunction *MF,
473 const Function *ParentF,
474 WinEHFuncInfo &FuncInfo) {
475 const Function *F = MF->getFunction();
David Majnemercde33032015-03-30 22:58:10 +0000476
477 // The Itanium LSDA table sorts similar landing pads together to simplify the
478 // actions table, but we don't need that.
479 SmallVector<const LandingPadInfo *, 64> LandingPads;
480 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
481 LandingPads.reserve(PadInfos.size());
482 for (const auto &LP : PadInfos)
483 LandingPads.push_back(&LP);
484
485 RangeMapType PadMap;
486 computePadMap(LandingPads, PadMap);
487
488 // The end label of the previous invoke or nounwind try-range.
489 MCSymbol *LastLabel = Asm->getFunctionBegin();
490
491 // Whether there is a potentially throwing instruction (currently this means
492 // an ordinary call) between the end of the previous try-range and now.
493 bool SawPotentiallyThrowing = false;
494
David Majnemercde33032015-03-30 22:58:10 +0000495 int LastEHState = -2;
496
497 // The parent function and the catch handlers contribute to the 'ip2state'
498 // table.
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000499
500 // Include ip2state entries for the beginning of the main function and
501 // for catch handler functions.
502 if (F == ParentF) {
503 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
504 LastEHState = -1;
505 } else if (FuncInfo.HandlerBaseState.count(F)) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000506 FuncInfo.IPToStateList.push_back(
507 std::make_pair(LastLabel, FuncInfo.HandlerBaseState[F]));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000508 LastEHState = FuncInfo.HandlerBaseState[F];
509 }
David Majnemercde33032015-03-30 22:58:10 +0000510 for (const auto &MBB : *MF) {
511 for (const auto &MI : MBB) {
512 if (!MI.isEHLabel()) {
513 if (MI.isCall())
514 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
515 continue;
516 }
517
518 // End of the previous try-range?
519 MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
520 if (BeginLabel == LastLabel)
521 SawPotentiallyThrowing = false;
522
523 // Beginning of a new try-range?
524 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
525 if (L == PadMap.end())
526 // Nope, it was just some random label.
527 continue;
528
529 const PadRange &P = L->second;
530 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
531 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
532 "Inconsistent landing pad map!");
533
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000534 // FIXME: Should this be using FuncInfo.HandlerBaseState?
535 if (SawPotentiallyThrowing && LastEHState != -1) {
David Majnemercde33032015-03-30 22:58:10 +0000536 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
537 SawPotentiallyThrowing = false;
538 LastEHState = -1;
539 }
540
541 if (LandingPad->WinEHState != LastEHState)
542 FuncInfo.IPToStateList.push_back(
543 std::make_pair(BeginLabel, LandingPad->WinEHState));
544 LastEHState = LandingPad->WinEHState;
545 LastLabel = LandingPad->EndLabels[P.RangeIndex];
546 }
547 }
David Majnemercde33032015-03-30 22:58:10 +0000548}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000549
550/// Emit the language-specific data that _except_handler3 and 4 expect. This is
551/// functionally equivalent to the __C_specific_handler table, except it is
552/// indexed by state number instead of IP.
553void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
554 auto &OS = *Asm->OutStreamer;
555
556 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
557 const Function *F = MF->getFunction();
558 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
559 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
560 OS.EmitLabel(LSDALabel);
561
562 const Function *Per = MMI->getPersonality();
563 StringRef PerName = Per->getName();
564 int BaseState = -1;
565 if (PerName == "_except_handler4") {
566 // The LSDA for _except_handler4 starts with this struct, followed by the
567 // scope table:
568 //
569 // struct EH4ScopeTable {
570 // int32_t GSCookieOffset;
571 // int32_t GSCookieXOROffset;
572 // int32_t EHCookieOffset;
573 // int32_t EHCookieXOROffset;
574 // ScopeTableEntry ScopeRecord[];
575 // };
576 //
577 // Only the EHCookieOffset field appears to vary, and it appears to be the
578 // offset from the final saved SP value to the retaddr.
579 OS.EmitIntValue(-2, 4);
580 OS.EmitIntValue(0, 4);
581 // FIXME: Calculate.
582 OS.EmitIntValue(9999, 4);
583 OS.EmitIntValue(0, 4);
584 BaseState = -2;
585 }
586
587 // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
588 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
589 SmallVector<const LandingPadInfo *, 4> LPads;
590 LPads.reserve((PadInfos.size()));
591 for (const LandingPadInfo &LPInfo : PadInfos)
592 LPads.push_back(&LPInfo);
593 std::sort(LPads.begin(), LPads.end(),
594 [](const LandingPadInfo *L, const LandingPadInfo *R) {
595 return L->WinEHState < R->WinEHState;
596 });
597
598 // For each action in each lpad, emit one of these:
599 // struct ScopeTableEntry {
600 // int32_t EnclosingLevel;
601 // int32_t (__cdecl *FilterOrFinally)();
602 // void *HandlerLabel;
603 // };
604 //
605 // The "outermost" action will use BaseState as its enclosing level. Each
606 // other action will refer to the previous state as its enclosing level.
607 int CurState = 0;
608 for (const LandingPadInfo *LPInfo : LPads) {
609 int EnclosingLevel = BaseState;
Reid Kleckner7912d9b2015-06-10 00:04:53 +0000610 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
611 LPInfo->WinEHState &&
Reid Klecknerf12c0302015-06-09 21:42:19 +0000612 "gaps in the SEH scope table");
613 for (const SEHHandler &Handler : LPInfo->SEHHandlers) {
614 // Emit the filter or finally function pointer, if present. Otherwise,
615 // emit '1' to indicate a catch-all.
616 const MCExpr *FilterOrFinally;
617 if (const Function *F = Handler.FilterOrFinally)
618 FilterOrFinally = create32bitRef(Asm->getSymbol(F));
619 else
620 FilterOrFinally = MCConstantExpr::create(1, Asm->OutContext);
621
622 // Compute the recovery address, which is a block address or null.
623 const BlockAddress *BA = Handler.RecoverBA;
624 const MCExpr *RecoverBBOrNull =
625 create32bitRef(BA ? Asm->GetBlockAddressSymbol(BA) : nullptr);
626
627 OS.EmitIntValue(EnclosingLevel, 4);
628 OS.EmitValue(FilterOrFinally, 4);
629 OS.EmitValue(RecoverBBOrNull, 4);
630
631 // The next state unwinds to this state.
632 EnclosingLevel = CurState;
633 CurState++;
634 }
635 }
636}