[WinEH] Run cleanup handlers when an exception is thrown
[oota-llvm.git] / lib / CodeGen / AsmPrinter / Win64Exception.cpp
1 //===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===//
2 //
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
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/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Module.h"
26 #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"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 using namespace llvm;
40
41 Win64Exception::Win64Exception(AsmPrinter *A)
42   : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
43     shouldEmitMoves(false) {}
44
45 Win64Exception::~Win64Exception() {}
46
47 /// endModule - Emit all exception information that should come after the
48 /// content.
49 void Win64Exception::endModule() {
50 }
51
52 void Win64Exception::beginFunction(const MachineFunction *MF) {
53   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
54
55   // If any landing pads survive, we need an EH table.
56   bool hasLandingPads = !MMI->getLandingPads().empty();
57
58   shouldEmitMoves = Asm->needsSEHMoves();
59
60   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
61   unsigned PerEncoding = TLOF.getPersonalityEncoding();
62   const Function *Per = MF->getMMI().getPersonality();
63
64   shouldEmitPersonality = hasLandingPads &&
65     PerEncoding != dwarf::DW_EH_PE_omit && Per;
66
67   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
68   shouldEmitLSDA = shouldEmitPersonality &&
69     LSDAEncoding != dwarf::DW_EH_PE_omit;
70
71   if (!shouldEmitPersonality && !shouldEmitMoves)
72     return;
73
74   Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
75
76   if (!shouldEmitPersonality)
77     return;
78
79   const MCSymbol *PersHandlerSym =
80       TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
81   Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
82 }
83
84 /// endFunction - Gather and emit post-function exception information.
85 ///
86 void Win64Exception::endFunction(const MachineFunction *MF) {
87   if (!shouldEmitPersonality && !shouldEmitMoves)
88     return;
89
90   // Map all labels and get rid of any dead landing pads.
91   MMI->TidyLandingPads();
92
93   if (shouldEmitPersonality) {
94     Asm->OutStreamer.PushSection();
95
96     // Emit an UNWIND_INFO struct describing the prologue.
97     Asm->OutStreamer.EmitWinEHHandlerData();
98
99     // Emit the tables appropriate to the personality function in use. If we
100     // don't recognize the personality, assume it uses an Itanium-style LSDA.
101     EHPersonality Per = MMI->getPersonalityType();
102     if (Per == EHPersonality::MSVC_Win64SEH)
103       emitCSpecificHandlerTable();
104     else if (Per == EHPersonality::MSVC_CXX)
105       emitCXXFrameHandler3Table(MF);
106     else
107       emitExceptionTable();
108
109     Asm->OutStreamer.PopSection();
110   }
111   Asm->OutStreamer.EmitWinCFIEndProc();
112 }
113
114 const MCExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
115   if (!Value)
116     return MCConstantExpr::Create(0, Asm->OutContext);
117   return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
118                                  Asm->OutContext);
119 }
120
121 const MCExpr *Win64Exception::createImageRel32(const GlobalValue *GV) {
122   if (!GV)
123     return MCConstantExpr::Create(0, Asm->OutContext);
124   return createImageRel32(Asm->getSymbol(GV));
125 }
126
127 /// Emit the language-specific data that __C_specific_handler expects.  This
128 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
129 /// up after faults with __try, __except, and __finally.  The typeinfo values
130 /// are not really RTTI data, but pointers to filter functions that return an
131 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
132 /// blocks and other cleanups, the landing pad label is zero, and the filter
133 /// function is actually a cleanup handler with the same prototype.  A catch-all
134 /// entry is modeled with a null filter function field and a non-zero landing
135 /// pad label.
136 ///
137 /// Possible filter function return values:
138 ///   EXCEPTION_EXECUTE_HANDLER (1):
139 ///     Jump to the landing pad label after cleanups.
140 ///   EXCEPTION_CONTINUE_SEARCH (0):
141 ///     Continue searching this table or continue unwinding.
142 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
143 ///     Resume execution at the trapping PC.
144 ///
145 /// Inferred table structure:
146 ///   struct Table {
147 ///     int NumEntries;
148 ///     struct Entry {
149 ///       imagerel32 LabelStart;
150 ///       imagerel32 LabelEnd;
151 ///       imagerel32 FilterOrFinally;  // One means catch-all.
152 ///       imagerel32 LabelLPad;        // Zero means __finally.
153 ///     } Entries[NumEntries];
154 ///   };
155 void Win64Exception::emitCSpecificHandlerTable() {
156   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
157
158   // Simplifying assumptions for first implementation:
159   // - Cleanups are not implemented.
160   // - Filters are not implemented.
161
162   // The Itanium LSDA table sorts similar landing pads together to simplify the
163   // actions table, but we don't need that.
164   SmallVector<const LandingPadInfo *, 64> LandingPads;
165   LandingPads.reserve(PadInfos.size());
166   for (const auto &LP : PadInfos)
167     LandingPads.push_back(&LP);
168
169   // Compute label ranges for call sites as we would for the Itanium LSDA, but
170   // use an all zero action table because we aren't using these actions.
171   SmallVector<unsigned, 64> FirstActions;
172   FirstActions.resize(LandingPads.size());
173   SmallVector<CallSiteEntry, 64> CallSites;
174   computeCallSiteTable(CallSites, LandingPads, FirstActions);
175
176   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
177   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
178
179   // Emit the number of table entries.
180   unsigned NumEntries = 0;
181   for (const CallSiteEntry &CSE : CallSites) {
182     if (!CSE.LPad)
183       continue; // Ignore gaps.
184     for (int Selector : CSE.LPad->TypeIds) {
185       // Ignore C++ filter clauses in SEH.
186       // FIXME: Implement cleanup clauses.
187       if (isCatchEHSelector(Selector))
188         ++NumEntries;
189     }
190   }
191   Asm->OutStreamer.EmitIntValue(NumEntries, 4);
192
193   // Emit the four-label records for each call site entry. The table has to be
194   // sorted in layout order, and the call sites should already be sorted.
195   for (const CallSiteEntry &CSE : CallSites) {
196     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
197     // an EH table entry will propagate the exception rather than terminating
198     // the program.
199     if (!CSE.LPad)
200       continue;
201     const LandingPadInfo *LPad = CSE.LPad;
202
203     // Compute the label range. We may reuse the function begin and end labels
204     // rather than forming new ones.
205     const MCExpr *Begin =
206         createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
207     const MCExpr *End;
208     if (CSE.EndLabel) {
209       // The interval is half-open, so we have to add one to include the return
210       // address of the last invoke in the range.
211       End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
212                                     MCConstantExpr::Create(1, Asm->OutContext),
213                                     Asm->OutContext);
214     } else {
215       End = createImageRel32(EHFuncEndSym);
216     }
217
218     // These aren't really type info globals, they are actually pointers to
219     // filter functions ordered by selector. The zero selector is used for
220     // cleanups, so slot zero corresponds to selector 1.
221     const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
222
223     // Do a parallel iteration across typeids and clause labels, skipping filter
224     // clauses.
225     size_t NextClauseLabel = 0;
226     for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
227       // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
228       // to change that.
229       int Selector = LPad->TypeIds[E - I - 1];
230
231       // Ignore C++ filter clauses in SEH.
232       // FIXME: Implement cleanup clauses.
233       if (!isCatchEHSelector(Selector))
234         continue;
235
236       Asm->OutStreamer.EmitValue(Begin, 4);
237       Asm->OutStreamer.EmitValue(End, 4);
238       if (isCatchEHSelector(Selector)) {
239         assert(unsigned(Selector - 1) < SelectorToFilter.size());
240         const GlobalValue *TI = SelectorToFilter[Selector - 1];
241         if (TI) // Emit the filter function pointer.
242           Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
243         else  // Otherwise, this is a "catch i8* null", or catch all.
244           Asm->OutStreamer.EmitIntValue(1, 4);
245       }
246       MCSymbol *ClauseLabel = LPad->ClauseLabels[NextClauseLabel++];
247       Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);
248     }
249   }
250 }
251
252 void Win64Exception::emitCXXFrameHandler3Table(const MachineFunction *MF) {
253   const Function *F = MF->getFunction();
254   const Function *ParentF = MMI->getWinEHParent(F);
255   auto &OS = Asm->OutStreamer;
256
257   StringRef ParentLinkageName =
258       GlobalValue::getRealLinkageName(ParentF->getName());
259
260   MCSymbol *FuncInfoXData =
261       Asm->OutContext.GetOrCreateSymbol(Twine("$cppxdata$", ParentLinkageName));
262   OS.EmitValue(createImageRel32(FuncInfoXData), 4);
263
264   // The Itanium LSDA table sorts similar landing pads together to simplify the
265   // actions table, but we don't need that.
266   SmallVector<const LandingPadInfo *, 64> LandingPads;
267   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
268   LandingPads.reserve(PadInfos.size());
269   for (const auto &LP : PadInfos)
270     LandingPads.push_back(&LP);
271
272   RangeMapType PadMap;
273   computePadMap(LandingPads, PadMap);
274
275   // The end label of the previous invoke or nounwind try-range.
276   MCSymbol *LastLabel = Asm->getFunctionBegin();
277
278   // Whether there is a potentially throwing instruction (currently this means
279   // an ordinary call) between the end of the previous try-range and now.
280   bool SawPotentiallyThrowing = false;
281
282   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
283
284   int LastEHState = -2;
285
286   // The parent function and the catch handlers contribute to the 'ip2state'
287   // table.
288   for (const auto &MBB : *MF) {
289     for (const auto &MI : MBB) {
290       if (!MI.isEHLabel()) {
291         if (MI.isCall())
292           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
293         continue;
294       }
295
296       // End of the previous try-range?
297       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
298       if (BeginLabel == LastLabel)
299         SawPotentiallyThrowing = false;
300
301       // Beginning of a new try-range?
302       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
303       if (L == PadMap.end())
304         // Nope, it was just some random label.
305         continue;
306
307       const PadRange &P = L->second;
308       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
309       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
310              "Inconsistent landing pad map!");
311
312       if (SawPotentiallyThrowing) {
313         FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
314         SawPotentiallyThrowing = false;
315         LastEHState = -1;
316       }
317
318       if (LandingPad->WinEHState != LastEHState)
319         FuncInfo.IPToStateList.push_back(
320             std::make_pair(BeginLabel, LandingPad->WinEHState));
321       LastEHState = LandingPad->WinEHState;
322       LastLabel = LandingPad->EndLabels[P.RangeIndex];
323     }
324   }
325
326   if (ParentF != F)
327     return;
328
329   MCSymbol *UnwindMapXData = nullptr;
330   MCSymbol *TryBlockMapXData = nullptr;
331   MCSymbol *IPToStateXData = nullptr;
332   if (!FuncInfo.UnwindMap.empty())
333     UnwindMapXData = Asm->OutContext.GetOrCreateSymbol(
334         Twine("$stateUnwindMap$", ParentLinkageName));
335   if (!FuncInfo.TryBlockMap.empty())
336     TryBlockMapXData = Asm->OutContext.GetOrCreateSymbol(
337         Twine("$tryMap$", ParentLinkageName));
338   if (!FuncInfo.IPToStateList.empty())
339     IPToStateXData = Asm->OutContext.GetOrCreateSymbol(
340         Twine("$ip2state$", ParentLinkageName));
341
342   // FuncInfo {
343   //   uint32_t           MagicNumber
344   //   int32_t            MaxState;
345   //   UnwindMapEntry    *UnwindMap;
346   //   uint32_t           NumTryBlocks;
347   //   TryBlockMapEntry  *TryBlockMap;
348   //   uint32_t           IPMapEntries;
349   //   IPToStateMapEntry *IPToStateMap;
350   //   uint32_t           UnwindHelp; // (x64/ARM only)
351   //   ESTypeList        *ESTypeList;
352   //   int32_t            EHFlags;
353   // }
354   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
355   // EHFlags & 2 -> ???
356   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
357   OS.EmitLabel(FuncInfoXData);
358   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
359   OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4);       // MaxState
360   OS.EmitValue(createImageRel32(UnwindMapXData), 4);   // UnwindMap
361   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
362   OS.EmitValue(createImageRel32(TryBlockMapXData), 4); // TryBlockMap
363   OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4);   // IPMapEntries
364   OS.EmitValue(createImageRel32(IPToStateXData), 4);   // IPToStateMap
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) {
376       OS.EmitIntValue(UME.ToState, 4);                // ToState
377       OS.EmitValue(createImageRel32(UME.Cleanup), 4); // Action
378     }
379   }
380
381   // TryBlockMap {
382   //   int32_t      TryLow;
383   //   int32_t      TryHigh;
384   //   int32_t      CatchHigh;
385   //   int32_t      NumCatches;
386   //   HandlerType *HandlerArray;
387   // };
388   if (TryBlockMapXData) {
389     OS.EmitLabel(TryBlockMapXData);
390     SmallVector<MCSymbol *, 1> HandlerMaps;
391     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
392       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
393       MCSymbol *HandlerMapXData = nullptr;
394
395       if (!TBME.HandlerArray.empty())
396         HandlerMapXData =
397             Asm->OutContext.GetOrCreateSymbol(Twine("$handlerMap$")
398                                                   .concat(Twine(I))
399                                                   .concat("$")
400                                                   .concat(ParentLinkageName));
401
402       HandlerMaps.push_back(HandlerMapXData);
403
404       assert(TBME.TryLow <= TBME.TryHigh);
405       assert(TBME.CatchHigh > TBME.TryHigh);
406       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
407       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
408       OS.EmitIntValue(TBME.CatchHigh, 4);                 // CatchHigh
409       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
410       OS.EmitValue(createImageRel32(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         OS.EmitIntValue(HT.Adjectives, 4);                    // Adjectives
428         OS.EmitValue(createImageRel32(HT.TypeDescriptor), 4); // Type
429         OS.EmitIntValue(0, 4);                                // CatchObjOffset
430         OS.EmitValue(createImageRel32(HT.Handler), 4);        // Handler
431         OS.EmitIntValue(0, 4);                                // ParentFrameOffset
432       }
433     }
434   }
435
436   // IPToStateMapEntry {
437   //   void   *IP;
438   //   int32_t State;
439   // };
440   if (IPToStateXData) {
441     OS.EmitLabel(IPToStateXData);
442     for (auto &IPStatePair : FuncInfo.IPToStateList) {
443       OS.EmitValue(createImageRel32(IPStatePair.first), 4); // IP
444       OS.EmitIntValue(IPStatePair.second, 4);               // State
445     }
446   }
447 }