blob: 95947cb88c41058749cd6e3f4582d80237ae74e4 [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();
Reid Kleckner0e288232015-08-27 23:27:47 +000065 bool hasEHFunclets = MMI->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000066
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000067 const Function *F = MF->getFunction();
68 const Function *ParentF = MMI->getWinEHParent(F);
69
Charles Davis5638b9f2011-05-28 04:21:04 +000070 shouldEmitMoves = Asm->needsSEHMoves();
71
72 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
73 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Reid Kleckner9a1a9192015-07-13 20:41:46 +000074 const Function *Per = nullptr;
75 if (F->hasPersonalityFn())
76 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Charles Davis5638b9f2011-05-28 04:21:04 +000077
Keno Fischeraff703a2015-07-14 19:22:51 +000078 bool forceEmitPersonality =
79 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
80 F->needsUnwindTableEntry();
81
Reid Kleckner0e288232015-08-27 23:27:47 +000082 shouldEmitPersonality =
83 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
84 PerEncoding != dwarf::DW_EH_PE_omit && Per);
Charles Davis5638b9f2011-05-28 04:21:04 +000085
86 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
87 shouldEmitLSDA = shouldEmitPersonality &&
88 LSDAEncoding != dwarf::DW_EH_PE_omit;
89
Reid Kleckner0e288232015-08-27 23:27:47 +000090 // If we're not using CFI, we don't want the CFI or the personality, but we
91 // might want EH tables if we had EH pads.
92 // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
93 // this once WinEHPrepare stops doing that.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000094 if (!Asm->MAI->usesWindowsCFI()) {
Reid Kleckner0e288232015-08-27 23:27:47 +000095 shouldEmitLSDA =
96 hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000097 shouldEmitPersonality = false;
98 return;
99 }
David Majnemera225a192015-03-31 22:35:44 +0000100
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000101 if (shouldEmitMoves || shouldEmitPersonality)
102 Asm->OutStreamer->EmitWinCFIStartProc(Asm->CurrentFnSym);
Charles Davis5638b9f2011-05-28 04:21:04 +0000103
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000104 if (shouldEmitPersonality) {
105 const MCSymbol *PersHandlerSym =
106 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
107 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
108 }
Charles Davis91ed7992011-05-27 23:47:32 +0000109}
110
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000111/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000112///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000113void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000114 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000115 return;
116
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000117 const Function *F = MF->getFunction();
118 EHPersonality Per = EHPersonality::Unknown;
119 if (F->hasPersonalityFn())
120 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000121
122 // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
123 // Windows EH schemes, the landing pad is not actually reachable. It only
124 // exists so that we can emit the right table data.
125 if (!isMSVCEHPersonality(Per))
126 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000127
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000128 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000129 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000130
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000131 if (shouldEmitMoves || shouldEmitPersonality) {
132 // Emit an UNWIND_INFO struct describing the prologue.
133 Asm->OutStreamer->EmitWinEHHandlerData();
134 } else {
135 // Just switch sections to the right xdata section. This use of
136 // CurrentFnSym assumes that we only emit the LSDA when ending the parent
137 // function.
138 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(
139 Asm->CurrentFnSym, Asm->OutContext);
140 Asm->OutStreamer->SwitchSection(XData);
141 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000142
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000143 // Emit the tables appropriate to the personality function in use. If we
144 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000145 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000146 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000147 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000148 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000149 else if (Per == EHPersonality::MSVC_CXX)
150 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000151 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000152 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000153
Lang Hames9ff69c82015-04-24 19:11:51 +0000154 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000155 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000156
David Majnemer0e705982015-09-11 17:34:34 +0000157 if (shouldEmitMoves || shouldEmitPersonality)
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000158 Asm->OutStreamer->EmitWinCFIEndProc();
Charles Davis91ed7992011-05-27 23:47:32 +0000159}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000160
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000161const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000162 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000163 return MCConstantExpr::create(0, Asm->OutContext);
164 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000165 ? MCSymbolRefExpr::VK_COFF_IMGREL32
166 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000167 Asm->OutContext);
168}
169
David Majnemer0ad363e2015-08-18 19:07:12 +0000170const MCExpr *WinException::create32bitRef(const Value *V) {
171 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000172 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000173 // FIXME: Delete the GlobalValue case once the new IR is fully functional.
174 if (const auto *GV = dyn_cast<GlobalValue>(V))
175 return create32bitRef(Asm->getSymbol(GV));
176 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000177}
178
Reid Kleckner0a57f652015-01-14 01:05:27 +0000179/// Emit the language-specific data that __C_specific_handler expects. This
180/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
181/// up after faults with __try, __except, and __finally. The typeinfo values
182/// are not really RTTI data, but pointers to filter functions that return an
183/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
184/// blocks and other cleanups, the landing pad label is zero, and the filter
185/// function is actually a cleanup handler with the same prototype. A catch-all
186/// entry is modeled with a null filter function field and a non-zero landing
187/// pad label.
188///
189/// Possible filter function return values:
190/// EXCEPTION_EXECUTE_HANDLER (1):
191/// Jump to the landing pad label after cleanups.
192/// EXCEPTION_CONTINUE_SEARCH (0):
193/// Continue searching this table or continue unwinding.
194/// EXCEPTION_CONTINUE_EXECUTION (-1):
195/// Resume execution at the trapping PC.
196///
197/// Inferred table structure:
198/// struct Table {
199/// int NumEntries;
200/// struct Entry {
201/// imagerel32 LabelStart;
202/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000203/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000204/// imagerel32 LabelLPad; // Zero means __finally.
205/// } Entries[NumEntries];
206/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000207void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Kleckner0a57f652015-01-14 01:05:27 +0000208 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
209
Reid Kleckner94b704c2015-09-09 21:10:03 +0000210 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
211 if (!FuncInfo.SEHUnwindMap.empty())
212 report_fatal_error("x64 SEH tables not yet implemented");
213
Reid Kleckner0a57f652015-01-14 01:05:27 +0000214 // Simplifying assumptions for first implementation:
215 // - Cleanups are not implemented.
216 // - Filters are not implemented.
217
218 // The Itanium LSDA table sorts similar landing pads together to simplify the
219 // actions table, but we don't need that.
220 SmallVector<const LandingPadInfo *, 64> LandingPads;
221 LandingPads.reserve(PadInfos.size());
222 for (const auto &LP : PadInfos)
223 LandingPads.push_back(&LP);
224
225 // Compute label ranges for call sites as we would for the Itanium LSDA, but
226 // use an all zero action table because we aren't using these actions.
227 SmallVector<unsigned, 64> FirstActions;
228 FirstActions.resize(LandingPads.size());
229 SmallVector<CallSiteEntry, 64> CallSites;
230 computeCallSiteTable(CallSites, LandingPads, FirstActions);
231
Rafael Espindola629cdba2015-02-27 18:18:39 +0000232 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
233 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000234
235 // Emit the number of table entries.
236 unsigned NumEntries = 0;
237 for (const CallSiteEntry &CSE : CallSites) {
238 if (!CSE.LPad)
239 continue; // Ignore gaps.
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000240 NumEntries += CSE.LPad->SEHHandlers.size();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000241 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000242 Asm->OutStreamer->EmitIntValue(NumEntries, 4);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000243
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000244 // If there are no actions, we don't need to iterate again.
245 if (NumEntries == 0)
246 return;
247
Reid Kleckner0a57f652015-01-14 01:05:27 +0000248 // Emit the four-label records for each call site entry. The table has to be
249 // sorted in layout order, and the call sites should already be sorted.
250 for (const CallSiteEntry &CSE : CallSites) {
251 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
252 // an EH table entry will propagate the exception rather than terminating
253 // the program.
254 if (!CSE.LPad)
255 continue;
256 const LandingPadInfo *LPad = CSE.LPad;
257
258 // Compute the label range. We may reuse the function begin and end labels
259 // rather than forming new ones.
260 const MCExpr *Begin =
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000261 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000262 const MCExpr *End;
263 if (CSE.EndLabel) {
264 // The interval is half-open, so we have to add one to include the return
265 // address of the last invoke in the range.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000266 End = MCBinaryExpr::createAdd(create32bitRef(CSE.EndLabel),
267 MCConstantExpr::create(1, Asm->OutContext),
Reid Kleckner0a57f652015-01-14 01:05:27 +0000268 Asm->OutContext);
269 } else {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000270 End = create32bitRef(EHFuncEndSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000271 }
272
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000273 // Emit an entry for each action.
274 for (SEHHandler Handler : LPad->SEHHandlers) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000275 Asm->OutStreamer->EmitValue(Begin, 4);
276 Asm->OutStreamer->EmitValue(End, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000277
278 // Emit the filter or finally function pointer, if present. Otherwise,
279 // emit '1' to indicate a catch-all.
280 const Function *F = Handler.FilterOrFinally;
281 if (F)
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000282 Asm->OutStreamer->EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000283 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000284 Asm->OutStreamer->EmitIntValue(1, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000285
286 // Emit the recovery address, if present. Otherwise, this must be a
287 // finally.
288 const BlockAddress *BA = Handler.RecoverBA;
289 if (BA)
Lang Hames9ff69c82015-04-24 19:11:51 +0000290 Asm->OutStreamer->EmitValue(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000291 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000292 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000293 Asm->OutStreamer->EmitIntValue(0, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000294 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000295 }
296}
David Majnemercde33032015-03-30 22:58:10 +0000297
Reid Kleckner94b704c2015-09-09 21:10:03 +0000298/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
299/// are used in the old WinEH scheme, and they will be removed eventually.
300static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
Reid Kleckner78783912015-09-10 00:25:23 +0000301 if (!Handler)
302 return nullptr;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000303 if (Handler.is<MachineBasicBlock *>())
304 return Handler.get<MachineBasicBlock *>()->getSymbol();
Reid Kleckner78783912015-09-10 00:25:23 +0000305 return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
Reid Kleckner94b704c2015-09-09 21:10:03 +0000306}
307
Reid Kleckner60b640b2015-05-28 22:47:01 +0000308void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000309 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000310 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000311 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000312
Reid Kleckner813f1b62015-09-16 22:14:46 +0000313 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000314
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000315 MCSymbol *FuncInfoXData = nullptr;
316 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000317 FuncInfoXData =
318 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000319 OS.EmitValue(create32bitRef(FuncInfoXData), 4);
320
Reid Kleckner813f1b62015-09-16 22:14:46 +0000321 extendIP2StateTable(MF, FuncInfo);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000322 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000323 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
324 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000325 }
326
327 MCSymbol *UnwindMapXData = nullptr;
328 MCSymbol *TryBlockMapXData = nullptr;
329 MCSymbol *IPToStateXData = nullptr;
330 if (!FuncInfo.UnwindMap.empty())
331 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000332 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000333 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000334 TryBlockMapXData =
335 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000336 if (!FuncInfo.IPToStateList.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000337 IPToStateXData =
338 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000339
340 // FuncInfo {
341 // uint32_t MagicNumber
342 // int32_t MaxState;
343 // UnwindMapEntry *UnwindMap;
344 // uint32_t NumTryBlocks;
345 // TryBlockMapEntry *TryBlockMap;
346 // uint32_t IPMapEntries; // always 0 for x86
347 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
348 // uint32_t UnwindHelp; // non-x86 only
349 // ESTypeList *ESTypeList;
350 // int32_t EHFlags;
351 // }
352 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
353 // EHFlags & 2 -> ???
354 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000355 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000356 OS.EmitLabel(FuncInfoXData);
357 OS.EmitIntValue(0x19930522, 4); // MagicNumber
358 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
359 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
360 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
361 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
362 OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4); // IPMapEntries
363 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
364 if (Asm->MAI->usesWindowsCFI())
365 OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
366 OS.EmitIntValue(0, 4); // ESTypeList
367 OS.EmitIntValue(1, 4); // EHFlags
368
369 // UnwindMapEntry {
370 // int32_t ToState;
371 // void (*Action)();
372 // };
373 if (UnwindMapXData) {
374 OS.EmitLabel(UnwindMapXData);
375 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
Reid Kleckner78783912015-09-10 00:25:23 +0000376 MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
377 OS.EmitIntValue(UME.ToState, 4); // ToState
378 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000379 }
380 }
381
382 // TryBlockMap {
383 // int32_t TryLow;
384 // int32_t TryHigh;
385 // int32_t CatchHigh;
386 // int32_t NumCatches;
387 // HandlerType *HandlerArray;
388 // };
389 if (TryBlockMapXData) {
390 OS.EmitLabel(TryBlockMapXData);
391 SmallVector<MCSymbol *, 1> HandlerMaps;
392 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
393 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000394
Reid Kleckner813f1b62015-09-16 22:14:46 +0000395 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000396 if (!TBME.HandlerArray.empty())
397 HandlerMapXData =
398 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
399 .concat(Twine(I))
400 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000401 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000402 HandlerMaps.push_back(HandlerMapXData);
403
Reid Kleckner813f1b62015-09-16 22:14:46 +0000404 // TBMEs should form intervals.
405 assert(0 <= TBME.TryLow && "bad trymap interval");
406 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
407 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
408 assert(TBME.CatchHigh < int(FuncInfo.UnwindMap.size()) &&
409 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000410
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000411 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
412 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000413 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000414 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
415 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
416 }
417
418 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
419 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
420 MCSymbol *HandlerMapXData = HandlerMaps[I];
421 if (!HandlerMapXData)
422 continue;
423 // HandlerType {
424 // int32_t Adjectives;
425 // TypeDescriptor *Type;
426 // int32_t CatchObjOffset;
427 // void (*Handler)();
428 // int32_t ParentFrameOffset; // x64 only
429 // };
430 OS.EmitLabel(HandlerMapXData);
431 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
432 // Get the frame escape label with the offset of the catch object. If
433 // the index is -1, then there is no catch object, and we should emit an
434 // offset of zero, indicating that no copy will occur.
435 const MCExpr *FrameAllocOffsetRef = nullptr;
436 if (HT.CatchObjRecoverIdx >= 0) {
437 MCSymbol *FrameAllocOffset =
438 Asm->OutContext.getOrCreateFrameAllocSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000439 FuncLinkageName, HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000440 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000441 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
Reid Klecknerb005d282015-09-16 20:16:27 +0000442 } else if (HT.CatchObj.FrameOffset != INT_MAX) {
443 int Offset = HT.CatchObj.FrameOffset;
444 // For 32-bit, the catch object offset is relative to the end of the
445 // EH registration node. For 64-bit, it's relative to SP at the end of
446 // the prologue.
447 if (!shouldEmitPersonality) {
448 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
449 Offset += FuncInfo.EHRegNodeEndOffset;
450 }
451 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000452 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000453 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000454 }
455
Reid Kleckner94b704c2015-09-09 21:10:03 +0000456 MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
457
458 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
459 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
460 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
461 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000462
463 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000464 // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
465 // Keep this in sync with X86FrameLowering::emitPrologue.
466 int ParentFrameOffset =
467 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
468 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000469 }
470 }
471 }
472 }
473
474 // IPToStateMapEntry {
475 // void *IP;
476 // int32_t State;
477 // };
478 if (IPToStateXData) {
479 OS.EmitLabel(IPToStateXData);
480 for (auto &IPStatePair : FuncInfo.IPToStateList) {
481 OS.EmitValue(create32bitRef(IPStatePair.first), 4); // IP
482 OS.EmitIntValue(IPStatePair.second, 4); // State
483 }
484 }
485}
486
487void WinException::extendIP2StateTable(const MachineFunction *MF,
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000488 WinEHFuncInfo &FuncInfo) {
David Majnemercde33032015-03-30 22:58:10 +0000489 // The Itanium LSDA table sorts similar landing pads together to simplify the
490 // actions table, but we don't need that.
491 SmallVector<const LandingPadInfo *, 64> LandingPads;
492 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
493 LandingPads.reserve(PadInfos.size());
494 for (const auto &LP : PadInfos)
495 LandingPads.push_back(&LP);
496
497 RangeMapType PadMap;
498 computePadMap(LandingPads, PadMap);
499
500 // The end label of the previous invoke or nounwind try-range.
501 MCSymbol *LastLabel = Asm->getFunctionBegin();
502
503 // Whether there is a potentially throwing instruction (currently this means
504 // an ordinary call) between the end of the previous try-range and now.
505 bool SawPotentiallyThrowing = false;
506
David Majnemercde33032015-03-30 22:58:10 +0000507 int LastEHState = -2;
508
509 // The parent function and the catch handlers contribute to the 'ip2state'
510 // table.
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000511
512 // Include ip2state entries for the beginning of the main function and
513 // for catch handler functions.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000514 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
515 LastEHState = -1;
David Majnemercde33032015-03-30 22:58:10 +0000516 for (const auto &MBB : *MF) {
517 for (const auto &MI : MBB) {
518 if (!MI.isEHLabel()) {
519 if (MI.isCall())
520 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
521 continue;
522 }
523
524 // End of the previous try-range?
525 MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
526 if (BeginLabel == LastLabel)
527 SawPotentiallyThrowing = false;
528
529 // Beginning of a new try-range?
530 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
531 if (L == PadMap.end())
532 // Nope, it was just some random label.
533 continue;
534
535 const PadRange &P = L->second;
536 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
537 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
538 "Inconsistent landing pad map!");
539
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000540 // FIXME: Should this be using FuncInfo.HandlerBaseState?
541 if (SawPotentiallyThrowing && LastEHState != -1) {
David Majnemercde33032015-03-30 22:58:10 +0000542 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
543 SawPotentiallyThrowing = false;
544 LastEHState = -1;
545 }
546
547 if (LandingPad->WinEHState != LastEHState)
548 FuncInfo.IPToStateList.push_back(
549 std::make_pair(BeginLabel, LandingPad->WinEHState));
550 LastEHState = LandingPad->WinEHState;
551 LastLabel = LandingPad->EndLabels[P.RangeIndex];
552 }
553 }
David Majnemercde33032015-03-30 22:58:10 +0000554}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000555
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000556void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
557 StringRef FLinkageName) {
558 // Outlined helpers called by the EH runtime need to know the offset of the EH
559 // registration in order to recover the parent frame pointer. Now that we know
560 // we've code generated the parent, we can emit the label assignment that
561 // those helpers use to get the offset of the registration node.
562 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000563 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000564 MCSymbol *ParentFrameOffset =
565 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
566 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
567 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
568 const MCExpr *RegistrationOffsetSymRef =
569 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
570 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
571}
572
Reid Klecknerf12c0302015-06-09 21:42:19 +0000573/// Emit the language-specific data that _except_handler3 and 4 expect. This is
574/// functionally equivalent to the __C_specific_handler table, except it is
575/// indexed by state number instead of IP.
576void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000577 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000578 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000579 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000580
581 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
582 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000583
584 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000585 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000586 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000587 OS.EmitLabel(LSDALabel);
588
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000589 const Function *Per =
590 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000591 StringRef PerName = Per->getName();
592 int BaseState = -1;
593 if (PerName == "_except_handler4") {
594 // The LSDA for _except_handler4 starts with this struct, followed by the
595 // scope table:
596 //
597 // struct EH4ScopeTable {
598 // int32_t GSCookieOffset;
599 // int32_t GSCookieXOROffset;
600 // int32_t EHCookieOffset;
601 // int32_t EHCookieXOROffset;
602 // ScopeTableEntry ScopeRecord[];
603 // };
604 //
605 // Only the EHCookieOffset field appears to vary, and it appears to be the
606 // offset from the final saved SP value to the retaddr.
607 OS.EmitIntValue(-2, 4);
608 OS.EmitIntValue(0, 4);
609 // FIXME: Calculate.
610 OS.EmitIntValue(9999, 4);
611 OS.EmitIntValue(0, 4);
612 BaseState = -2;
613 }
614
Reid Kleckner94b704c2015-09-09 21:10:03 +0000615 if (!FuncInfo.SEHUnwindMap.empty()) {
616 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
617 MCSymbol *ExceptOrFinally =
618 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
619 OS.EmitIntValue(UME.ToState, 4); // ToState
620 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
621 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
622 }
623 return;
624 }
625 // FIXME: The following code is for the old landingpad-based SEH
626 // implementation. Remove it when possible.
627
Reid Klecknerf12c0302015-06-09 21:42:19 +0000628 // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
629 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
630 SmallVector<const LandingPadInfo *, 4> LPads;
631 LPads.reserve((PadInfos.size()));
632 for (const LandingPadInfo &LPInfo : PadInfos)
633 LPads.push_back(&LPInfo);
634 std::sort(LPads.begin(), LPads.end(),
635 [](const LandingPadInfo *L, const LandingPadInfo *R) {
636 return L->WinEHState < R->WinEHState;
637 });
638
639 // For each action in each lpad, emit one of these:
640 // struct ScopeTableEntry {
641 // int32_t EnclosingLevel;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000642 // int32_t (__cdecl *Filter)();
643 // void *HandlerOrFinally;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000644 // };
645 //
646 // The "outermost" action will use BaseState as its enclosing level. Each
647 // other action will refer to the previous state as its enclosing level.
648 int CurState = 0;
649 for (const LandingPadInfo *LPInfo : LPads) {
650 int EnclosingLevel = BaseState;
Reid Kleckner7912d9b2015-06-10 00:04:53 +0000651 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
652 LPInfo->WinEHState &&
Reid Klecknerf12c0302015-06-09 21:42:19 +0000653 "gaps in the SEH scope table");
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000654 for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
655 I != E; ++I) {
656 const SEHHandler &Handler = *I;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000657 const BlockAddress *BA = Handler.RecoverBA;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000658 const Function *F = Handler.FilterOrFinally;
659 assert(F && "cannot catch all in 32-bit SEH without filter function");
660 const MCExpr *FilterOrNull =
661 create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
662 const MCExpr *ExceptOrFinally = create32bitRef(
663 BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
Reid Klecknerf12c0302015-06-09 21:42:19 +0000664
665 OS.EmitIntValue(EnclosingLevel, 4);
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000666 OS.EmitValue(FilterOrNull, 4);
667 OS.EmitValue(ExceptOrFinally, 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000668
669 // The next state unwinds to this state.
670 EnclosingLevel = CurState;
671 CurState++;
672 }
673 }
674}