1 //===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing Win64 exception info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "Win64Exception.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
40 Win64Exception::Win64Exception(AsmPrinter *A)
41 : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
42 shouldEmitMoves(false) {}
44 Win64Exception::~Win64Exception() {}
46 /// endModule - Emit all exception information that should come after the
48 void Win64Exception::endModule() {
51 void Win64Exception::beginFunction(const MachineFunction *MF) {
52 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
54 // If any landing pads survive, we need an EH table.
55 bool hasLandingPads = !MMI->getLandingPads().empty();
57 shouldEmitMoves = Asm->needsSEHMoves();
59 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
60 unsigned PerEncoding = TLOF.getPersonalityEncoding();
61 const Function *Per = MF->getMMI().getPersonality();
63 shouldEmitPersonality = hasLandingPads &&
64 PerEncoding != dwarf::DW_EH_PE_omit && Per;
66 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
67 shouldEmitLSDA = shouldEmitPersonality &&
68 LSDAEncoding != dwarf::DW_EH_PE_omit;
70 if (!shouldEmitPersonality && !shouldEmitMoves)
73 Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
75 if (!shouldEmitPersonality)
78 const MCSymbol *PersHandlerSym =
79 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
80 Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
83 /// endFunction - Gather and emit post-function exception information.
85 void Win64Exception::endFunction(const MachineFunction *) {
86 if (!shouldEmitPersonality && !shouldEmitMoves)
89 // Map all labels and get rid of any dead landing pads.
90 MMI->TidyLandingPads();
92 if (shouldEmitPersonality) {
93 Asm->OutStreamer.PushSection();
95 // Emit an UNWIND_INFO struct describing the prologue.
96 Asm->OutStreamer.EmitWinEHHandlerData();
98 // Emit the tables appropriate to the personality function in use. If we
99 // don't recognize the personality, assume it uses an Itanium-style LSDA.
100 EHPersonality Per = MMI->getPersonalityType();
101 if (Per == EHPersonality::MSVC_Win64SEH)
102 emitCSpecificHandlerTable();
104 emitExceptionTable();
106 Asm->OutStreamer.PopSection();
108 Asm->OutStreamer.EmitWinCFIEndProc();
111 const MCSymbolRefExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
112 return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
116 /// Emit the language-specific data that __C_specific_handler expects. This
117 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
118 /// up after faults with __try, __except, and __finally. The typeinfo values
119 /// are not really RTTI data, but pointers to filter functions that return an
120 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
121 /// blocks and other cleanups, the landing pad label is zero, and the filter
122 /// function is actually a cleanup handler with the same prototype. A catch-all
123 /// entry is modeled with a null filter function field and a non-zero landing
126 /// Possible filter function return values:
127 /// EXCEPTION_EXECUTE_HANDLER (1):
128 /// Jump to the landing pad label after cleanups.
129 /// EXCEPTION_CONTINUE_SEARCH (0):
130 /// Continue searching this table or continue unwinding.
131 /// EXCEPTION_CONTINUE_EXECUTION (-1):
132 /// Resume execution at the trapping PC.
134 /// Inferred table structure:
138 /// imagerel32 LabelStart;
139 /// imagerel32 LabelEnd;
140 /// imagerel32 FilterOrFinally; // One means catch-all.
141 /// imagerel32 LabelLPad; // Zero means __finally.
142 /// } Entries[NumEntries];
144 void Win64Exception::emitCSpecificHandlerTable() {
145 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
147 // Simplifying assumptions for first implementation:
148 // - Cleanups are not implemented.
149 // - Filters are not implemented.
151 // The Itanium LSDA table sorts similar landing pads together to simplify the
152 // actions table, but we don't need that.
153 SmallVector<const LandingPadInfo *, 64> LandingPads;
154 LandingPads.reserve(PadInfos.size());
155 for (const auto &LP : PadInfos)
156 LandingPads.push_back(&LP);
158 // Compute label ranges for call sites as we would for the Itanium LSDA, but
159 // use an all zero action table because we aren't using these actions.
160 SmallVector<unsigned, 64> FirstActions;
161 FirstActions.resize(LandingPads.size());
162 SmallVector<CallSiteEntry, 64> CallSites;
163 computeCallSiteTable(CallSites, LandingPads, FirstActions);
165 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
166 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
168 // Emit the number of table entries.
169 unsigned NumEntries = 0;
170 for (const CallSiteEntry &CSE : CallSites) {
172 continue; // Ignore gaps.
173 for (int Selector : CSE.LPad->TypeIds) {
174 // Ignore C++ filter clauses in SEH.
175 // FIXME: Implement cleanup clauses.
176 if (isCatchEHSelector(Selector))
180 Asm->OutStreamer.EmitIntValue(NumEntries, 4);
182 // Emit the four-label records for each call site entry. The table has to be
183 // sorted in layout order, and the call sites should already be sorted.
184 for (const CallSiteEntry &CSE : CallSites) {
185 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
186 // an EH table entry will propagate the exception rather than terminating
190 const LandingPadInfo *LPad = CSE.LPad;
192 // Compute the label range. We may reuse the function begin and end labels
193 // rather than forming new ones.
194 const MCExpr *Begin =
195 createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
198 // The interval is half-open, so we have to add one to include the return
199 // address of the last invoke in the range.
200 End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
201 MCConstantExpr::Create(1, Asm->OutContext),
204 End = createImageRel32(EHFuncEndSym);
207 // These aren't really type info globals, they are actually pointers to
208 // filter functions ordered by selector. The zero selector is used for
209 // cleanups, so slot zero corresponds to selector 1.
210 const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
212 // Do a parallel iteration across typeids and clause labels, skipping filter
214 size_t NextClauseLabel = 0;
215 for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
216 // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
218 int Selector = LPad->TypeIds[E - I - 1];
220 // Ignore C++ filter clauses in SEH.
221 // FIXME: Implement cleanup clauses.
222 if (!isCatchEHSelector(Selector))
225 Asm->OutStreamer.EmitValue(Begin, 4);
226 Asm->OutStreamer.EmitValue(End, 4);
227 if (isCatchEHSelector(Selector)) {
228 assert(unsigned(Selector - 1) < SelectorToFilter.size());
229 const GlobalValue *TI = SelectorToFilter[Selector - 1];
230 if (TI) // Emit the filter function pointer.
231 Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
232 else // Otherwise, this is a "catch i8* null", or catch all.
233 Asm->OutStreamer.EmitIntValue(1, 4);
235 MCSymbol *ClauseLabel = LPad->ClauseLabels[NextClauseLabel++];
236 Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);