Move get[S|U]LEB128Size() to LEB128.h.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfException.cpp
1 //===-- CodeGen/AsmPrinter/DwarfException.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 DWARF exception info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DwarfException.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/Support/LEB128.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 DwarfException::DwarfException(AsmPrinter *A)
42   : Asm(A), MMI(Asm->MMI) {}
43
44 DwarfException::~DwarfException() {}
45
46 /// SharedTypeIds - How many leading type ids two landing pads have in common.
47 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
48                                        const LandingPadInfo *R) {
49   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
50   unsigned LSize = LIds.size(), RSize = RIds.size();
51   unsigned MinSize = LSize < RSize ? LSize : RSize;
52   unsigned Count = 0;
53
54   for (; Count != MinSize; ++Count)
55     if (LIds[Count] != RIds[Count])
56       return Count;
57
58   return Count;
59 }
60
61 /// PadLT - Order landing pads lexicographically by type id.
62 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
63   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
64   unsigned LSize = LIds.size(), RSize = RIds.size();
65   unsigned MinSize = LSize < RSize ? LSize : RSize;
66
67   for (unsigned i = 0; i != MinSize; ++i)
68     if (LIds[i] != RIds[i])
69       return LIds[i] < RIds[i];
70
71   return LSize < RSize;
72 }
73
74 /// ComputeActionsTable - Compute the actions table and gather the first action
75 /// index for each landing pad site.
76 unsigned DwarfException::
77 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
78                     SmallVectorImpl<ActionEntry> &Actions,
79                     SmallVectorImpl<unsigned> &FirstActions) {
80
81   // The action table follows the call-site table in the LSDA. The individual
82   // records are of two types:
83   //
84   //   * Catch clause
85   //   * Exception specification
86   //
87   // The two record kinds have the same format, with only small differences.
88   // They are distinguished by the "switch value" field: Catch clauses
89   // (TypeInfos) have strictly positive switch values, and exception
90   // specifications (FilterIds) have strictly negative switch values. Value 0
91   // indicates a catch-all clause.
92   //
93   // Negative type IDs index into FilterIds. Positive type IDs index into
94   // TypeInfos.  The value written for a positive type ID is just the type ID
95   // itself.  For a negative type ID, however, the value written is the
96   // (negative) byte offset of the corresponding FilterIds entry.  The byte
97   // offset is usually equal to the type ID (because the FilterIds entries are
98   // written using a variable width encoding, which outputs one byte per entry
99   // as long as the value written is not too large) but can differ.  This kind
100   // of complication does not occur for positive type IDs because type infos are
101   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
102   // offset corresponding to FilterIds[i].
103
104   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
105   SmallVector<int, 16> FilterOffsets;
106   FilterOffsets.reserve(FilterIds.size());
107   int Offset = -1;
108
109   for (std::vector<unsigned>::const_iterator
110          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
111     FilterOffsets.push_back(Offset);
112     Offset -= getULEB128Size(*I);
113   }
114
115   FirstActions.reserve(LandingPads.size());
116
117   int FirstAction = 0;
118   unsigned SizeActions = 0;
119   const LandingPadInfo *PrevLPI = 0;
120
121   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
122          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
123     const LandingPadInfo *LPI = *I;
124     const std::vector<int> &TypeIds = LPI->TypeIds;
125     unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
126     unsigned SizeSiteActions = 0;
127
128     if (NumShared < TypeIds.size()) {
129       unsigned SizeAction = 0;
130       unsigned PrevAction = (unsigned)-1;
131
132       if (NumShared) {
133         unsigned SizePrevIds = PrevLPI->TypeIds.size();
134         assert(Actions.size());
135         PrevAction = Actions.size() - 1;
136         SizeAction = getSLEB128Size(Actions[PrevAction].NextAction) +
137                      getSLEB128Size(Actions[PrevAction].ValueForTypeID);
138
139         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
140           assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
141           SizeAction -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
142           SizeAction += -Actions[PrevAction].NextAction;
143           PrevAction = Actions[PrevAction].Previous;
144         }
145       }
146
147       // Compute the actions.
148       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
149         int TypeID = TypeIds[J];
150         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
151         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
152         unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
153
154         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
155         SizeAction = SizeTypeID + getSLEB128Size(NextAction);
156         SizeSiteActions += SizeAction;
157
158         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
159         Actions.push_back(Action);
160         PrevAction = Actions.size() - 1;
161       }
162
163       // Record the first action of the landing pad site.
164       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
165     } // else identical - re-use previous FirstAction
166
167     // Information used when created the call-site table. The action record
168     // field of the call site record is the offset of the first associated
169     // action record, relative to the start of the actions table. This value is
170     // biased by 1 (1 indicating the start of the actions table), and 0
171     // indicates that there are no actions.
172     FirstActions.push_back(FirstAction);
173
174     // Compute this sites contribution to size.
175     SizeActions += SizeSiteActions;
176
177     PrevLPI = LPI;
178   }
179
180   return SizeActions;
181 }
182
183 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
184 /// marked `nounwind'. Return `false' otherwise.
185 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
186   assert(MI->isCall() && "This should be a call instruction!");
187
188   bool MarkedNoUnwind = false;
189   bool SawFunc = false;
190
191   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
192     const MachineOperand &MO = MI->getOperand(I);
193
194     if (!MO.isGlobal()) continue;
195
196     const Function *F = dyn_cast<Function>(MO.getGlobal());
197     if (F == 0) continue;
198
199     if (SawFunc) {
200       // Be conservative. If we have more than one function operand for this
201       // call, then we can't make the assumption that it's the callee and
202       // not a parameter to the call.
203       //
204       // FIXME: Determine if there's a way to say that `F' is the callee or
205       // parameter.
206       MarkedNoUnwind = false;
207       break;
208     }
209
210     MarkedNoUnwind = F->doesNotThrow();
211     SawFunc = true;
212   }
213
214   return MarkedNoUnwind;
215 }
216
217 /// ComputeCallSiteTable - Compute the call-site table.  The entry for an invoke
218 /// has a try-range containing the call, a non-zero landing pad, and an
219 /// appropriate action.  The entry for an ordinary call has a try-range
220 /// containing the call and zero for the landing pad and the action.  Calls
221 /// marked 'nounwind' have no entry and must not be contained in the try-range
222 /// of any entry - they form gaps in the table.  Entries must be ordered by
223 /// try-range address.
224 void DwarfException::
225 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
226                      const RangeMapType &PadMap,
227                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
228                      const SmallVectorImpl<unsigned> &FirstActions) {
229   // The end label of the previous invoke or nounwind try-range.
230   MCSymbol *LastLabel = 0;
231
232   // Whether there is a potentially throwing instruction (currently this means
233   // an ordinary call) between the end of the previous try-range and now.
234   bool SawPotentiallyThrowing = false;
235
236   // Whether the last CallSite entry was for an invoke.
237   bool PreviousIsInvoke = false;
238
239   // Visit all instructions in order of address.
240   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
241        I != E; ++I) {
242     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
243          MI != E; ++MI) {
244       if (!MI->isLabel()) {
245         if (MI->isCall())
246           SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
247         continue;
248       }
249
250       // End of the previous try-range?
251       MCSymbol *BeginLabel = MI->getOperand(0).getMCSymbol();
252       if (BeginLabel == LastLabel)
253         SawPotentiallyThrowing = false;
254
255       // Beginning of a new try-range?
256       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
257       if (L == PadMap.end())
258         // Nope, it was just some random label.
259         continue;
260
261       const PadRange &P = L->second;
262       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
263       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
264              "Inconsistent landing pad map!");
265
266       // For Dwarf exception handling (SjLj handling doesn't use this). If some
267       // instruction between the previous try-range and this one may throw,
268       // create a call-site entry with no landing pad for the region between the
269       // try-ranges.
270       if (SawPotentiallyThrowing && Asm->MAI->isExceptionHandlingDwarf()) {
271         CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
272         CallSites.push_back(Site);
273         PreviousIsInvoke = false;
274       }
275
276       LastLabel = LandingPad->EndLabels[P.RangeIndex];
277       assert(BeginLabel && LastLabel && "Invalid landing pad!");
278
279       if (!LandingPad->LandingPadLabel) {
280         // Create a gap.
281         PreviousIsInvoke = false;
282       } else {
283         // This try-range is for an invoke.
284         CallSiteEntry Site = {
285           BeginLabel,
286           LastLabel,
287           LandingPad->LandingPadLabel,
288           FirstActions[P.PadIndex]
289         };
290
291         // Try to merge with the previous call-site. SJLJ doesn't do this
292         if (PreviousIsInvoke && Asm->MAI->isExceptionHandlingDwarf()) {
293           CallSiteEntry &Prev = CallSites.back();
294           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
295             // Extend the range of the previous entry.
296             Prev.EndLabel = Site.EndLabel;
297             continue;
298           }
299         }
300
301         // Otherwise, create a new call-site.
302         if (Asm->MAI->isExceptionHandlingDwarf())
303           CallSites.push_back(Site);
304         else {
305           // SjLj EH must maintain the call sites in the order assigned
306           // to them by the SjLjPrepare pass.
307           unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
308           if (CallSites.size() < SiteNo)
309             CallSites.resize(SiteNo);
310           CallSites[SiteNo - 1] = Site;
311         }
312         PreviousIsInvoke = true;
313       }
314     }
315   }
316
317   // If some instruction between the previous try-range and the end of the
318   // function may throw, create a call-site entry with no landing pad for the
319   // region following the try-range.
320   if (SawPotentiallyThrowing && Asm->MAI->isExceptionHandlingDwarf()) {
321     CallSiteEntry Site = { LastLabel, 0, 0, 0 };
322     CallSites.push_back(Site);
323   }
324 }
325
326 /// EmitExceptionTable - Emit landing pads and actions.
327 ///
328 /// The general organization of the table is complex, but the basic concepts are
329 /// easy.  First there is a header which describes the location and organization
330 /// of the three components that follow.
331 ///
332 ///  1. The landing pad site information describes the range of code covered by
333 ///     the try.  In our case it's an accumulation of the ranges covered by the
334 ///     invokes in the try.  There is also a reference to the landing pad that
335 ///     handles the exception once processed.  Finally an index into the actions
336 ///     table.
337 ///  2. The action table, in our case, is composed of pairs of type IDs and next
338 ///     action offset.  Starting with the action index from the landing pad
339 ///     site, each type ID is checked for a match to the current exception.  If
340 ///     it matches then the exception and type id are passed on to the landing
341 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
342 ///     with a next action of zero.  If no type id is found then the frame is
343 ///     unwound and handling continues.
344 ///  3. Type ID table contains references to all the C++ typeinfo for all
345 ///     catches in the function.  This tables is reverse indexed base 1.
346 void DwarfException::EmitExceptionTable() {
347   const std::vector<const GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
348   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
349   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
350
351   // Sort the landing pads in order of their type ids.  This is used to fold
352   // duplicate actions.
353   SmallVector<const LandingPadInfo *, 64> LandingPads;
354   LandingPads.reserve(PadInfos.size());
355
356   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
357     LandingPads.push_back(&PadInfos[i]);
358
359   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
360
361   // Compute the actions table and gather the first action index for each
362   // landing pad site.
363   SmallVector<ActionEntry, 32> Actions;
364   SmallVector<unsigned, 64> FirstActions;
365   unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
366
367   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
368   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
369   // try-ranges for them need be deduced when using DWARF exception handling.
370   RangeMapType PadMap;
371   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
372     const LandingPadInfo *LandingPad = LandingPads[i];
373     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
374       MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
375       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
376       PadRange P = { i, j };
377       PadMap[BeginLabel] = P;
378     }
379   }
380
381   // Compute the call-site table.
382   SmallVector<CallSiteEntry, 64> CallSites;
383   ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
384
385   // Final tallies.
386
387   // Call sites.
388   bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
389   bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
390
391   unsigned CallSiteTableLength;
392   if (IsSJLJ)
393     CallSiteTableLength = 0;
394   else {
395     unsigned SiteStartSize  = 4; // dwarf::DW_EH_PE_udata4
396     unsigned SiteLengthSize = 4; // dwarf::DW_EH_PE_udata4
397     unsigned LandingPadSize = 4; // dwarf::DW_EH_PE_udata4
398     CallSiteTableLength =
399       CallSites.size() * (SiteStartSize + SiteLengthSize + LandingPadSize);
400   }
401
402   for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
403     CallSiteTableLength += getULEB128Size(CallSites[i].Action);
404     if (IsSJLJ)
405       CallSiteTableLength += getULEB128Size(i);
406   }
407
408   // Type infos.
409   const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
410   unsigned TTypeEncoding;
411   unsigned TypeFormatSize;
412
413   if (!HaveTTData) {
414     // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
415     // that we're omitting that bit.
416     TTypeEncoding = dwarf::DW_EH_PE_omit;
417     // dwarf::DW_EH_PE_absptr
418     TypeFormatSize = Asm->getDataLayout().getPointerSize();
419   } else {
420     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
421     // pick a type encoding for them.  We're about to emit a list of pointers to
422     // typeinfo objects at the end of the LSDA.  However, unless we're in static
423     // mode, this reference will require a relocation by the dynamic linker.
424     //
425     // Because of this, we have a couple of options:
426     //
427     //   1) If we are in -static mode, we can always use an absolute reference
428     //      from the LSDA, because the static linker will resolve it.
429     //
430     //   2) Otherwise, if the LSDA section is writable, we can output the direct
431     //      reference to the typeinfo and allow the dynamic linker to relocate
432     //      it.  Since it is in a writable section, the dynamic linker won't
433     //      have a problem.
434     //
435     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
436     //      we need to use some form of indirection.  For example, on Darwin,
437     //      we can output a statically-relocatable reference to a dyld stub. The
438     //      offset to the stub is constant, but the contents are in a section
439     //      that is updated by the dynamic linker.  This is easy enough, but we
440     //      need to tell the personality function of the unwinder to indirect
441     //      through the dyld stub.
442     //
443     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
444     // somewhere.  This predicate should be moved to a shared location that is
445     // in target-independent code.
446     //
447     TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
448     TypeFormatSize = Asm->GetSizeOfEncodedValue(TTypeEncoding);
449   }
450
451   // Begin the exception table.
452   // Sometimes we want not to emit the data into separate section (e.g. ARM
453   // EHABI). In this case LSDASection will be NULL.
454   if (LSDASection)
455     Asm->OutStreamer.SwitchSection(LSDASection);
456   Asm->EmitAlignment(2);
457
458   // Emit the LSDA.
459   MCSymbol *GCCETSym =
460     Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
461                                       Twine(Asm->getFunctionNumber()));
462   Asm->OutStreamer.EmitLabel(GCCETSym);
463   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("exception",
464                                                 Asm->getFunctionNumber()));
465
466   if (IsSJLJ)
467     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("_LSDA_",
468                                                   Asm->getFunctionNumber()));
469
470   // Emit the LSDA header.
471   Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
472   Asm->EmitEncodingByte(TTypeEncoding, "@TType");
473
474   // The type infos need to be aligned. GCC does this by inserting padding just
475   // before the type infos. However, this changes the size of the exception
476   // table, so you need to take this into account when you output the exception
477   // table size. However, the size is output using a variable length encoding.
478   // So by increasing the size by inserting padding, you may increase the number
479   // of bytes used for writing the size. If it increases, say by one byte, then
480   // you now need to output one less byte of padding to get the type infos
481   // aligned. However this decreases the size of the exception table. This
482   // changes the value you have to output for the exception table size. Due to
483   // the variable length encoding, the number of bytes used for writing the
484   // length may decrease. If so, you then have to increase the amount of
485   // padding. And so on. If you look carefully at the GCC code you will see that
486   // it indeed does this in a loop, going on and on until the values stabilize.
487   // We chose another solution: don't output padding inside the table like GCC
488   // does, instead output it before the table.
489   unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
490   unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength);
491   unsigned TTypeBaseOffset =
492     sizeof(int8_t) +                            // Call site format
493     CallSiteTableLengthSize +                   // Call site table length size
494     CallSiteTableLength +                       // Call site table length
495     SizeActions +                               // Actions size
496     SizeTypes;
497   unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset);
498   unsigned TotalSize =
499     sizeof(int8_t) +                            // LPStart format
500     sizeof(int8_t) +                            // TType format
501     (HaveTTData ? TTypeBaseOffsetSize : 0) +    // TType base offset size
502     TTypeBaseOffset;                            // TType base offset
503   unsigned SizeAlign = (4 - TotalSize) & 3;
504
505   if (HaveTTData) {
506     // Account for any extra padding that will be added to the call site table
507     // length.
508     Asm->EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
509     SizeAlign = 0;
510   }
511
512   bool VerboseAsm = Asm->OutStreamer.isVerboseAsm();
513
514   // SjLj Exception handling
515   if (IsSJLJ) {
516     Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
517
518     // Add extra padding if it wasn't added to the TType base offset.
519     Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
520
521     // Emit the landing pad site information.
522     unsigned idx = 0;
523     for (SmallVectorImpl<CallSiteEntry>::const_iterator
524          I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
525       const CallSiteEntry &S = *I;
526
527       // Offset of the landing pad, counted in 16-byte bundles relative to the
528       // @LPStart address.
529       if (VerboseAsm) {
530         Asm->OutStreamer.AddComment(">> Call Site " + Twine(idx) + " <<");
531         Asm->OutStreamer.AddComment("  On exception at call site "+Twine(idx));
532       }
533       Asm->EmitULEB128(idx);
534
535       // Offset of the first associated action record, relative to the start of
536       // the action table. This value is biased by 1 (1 indicates the start of
537       // the action table), and 0 indicates that there are no actions.
538       if (VerboseAsm) {
539         if (S.Action == 0)
540           Asm->OutStreamer.AddComment("  Action: cleanup");
541         else
542           Asm->OutStreamer.AddComment("  Action: " +
543                                       Twine((S.Action - 1) / 2 + 1));
544       }
545       Asm->EmitULEB128(S.Action);
546     }
547   } else {
548     // DWARF Exception handling
549     assert(Asm->MAI->isExceptionHandlingDwarf());
550
551     // The call-site table is a list of all call sites that may throw an
552     // exception (including C++ 'throw' statements) in the procedure
553     // fragment. It immediately follows the LSDA header. Each entry indicates,
554     // for a given call, the first corresponding action record and corresponding
555     // landing pad.
556     //
557     // The table begins with the number of bytes, stored as an LEB128
558     // compressed, unsigned integer. The records immediately follow the record
559     // count. They are sorted in increasing call-site address. Each record
560     // indicates:
561     //
562     //   * The position of the call-site.
563     //   * The position of the landing pad.
564     //   * The first action record for that call site.
565     //
566     // A missing entry in the call-site table indicates that a call is not
567     // supposed to throw.
568
569     // Emit the landing pad call site table.
570     Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
571
572     // Add extra padding if it wasn't added to the TType base offset.
573     Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
574
575     unsigned Entry = 0;
576     for (SmallVectorImpl<CallSiteEntry>::const_iterator
577          I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
578       const CallSiteEntry &S = *I;
579
580       MCSymbol *EHFuncBeginSym =
581         Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
582
583       MCSymbol *BeginLabel = S.BeginLabel;
584       if (BeginLabel == 0)
585         BeginLabel = EHFuncBeginSym;
586       MCSymbol *EndLabel = S.EndLabel;
587       if (EndLabel == 0)
588         EndLabel = Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
589
590
591       // Offset of the call site relative to the previous call site, counted in
592       // number of 16-byte bundles. The first call site is counted relative to
593       // the start of the procedure fragment.
594       if (VerboseAsm)
595         Asm->OutStreamer.AddComment(">> Call Site " + Twine(++Entry) + " <<");
596       Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
597       if (VerboseAsm)
598         Asm->OutStreamer.AddComment(Twine("  Call between ") +
599                                     BeginLabel->getName() + " and " +
600                                     EndLabel->getName());
601       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
602
603       // Offset of the landing pad, counted in 16-byte bundles relative to the
604       // @LPStart address.
605       if (!S.PadLabel) {
606         if (VerboseAsm)
607           Asm->OutStreamer.AddComment("    has no landing pad");
608         Asm->OutStreamer.EmitIntValue(0, 4/*size*/);
609       } else {
610         if (VerboseAsm)
611           Asm->OutStreamer.AddComment(Twine("    jumps to ") +
612                                       S.PadLabel->getName());
613         Asm->EmitLabelDifference(S.PadLabel, EHFuncBeginSym, 4);
614       }
615
616       // Offset of the first associated action record, relative to the start of
617       // the action table. This value is biased by 1 (1 indicates the start of
618       // the action table), and 0 indicates that there are no actions.
619       if (VerboseAsm) {
620         if (S.Action == 0)
621           Asm->OutStreamer.AddComment("  On action: cleanup");
622         else
623           Asm->OutStreamer.AddComment("  On action: " +
624                                       Twine((S.Action - 1) / 2 + 1));
625       }
626       Asm->EmitULEB128(S.Action);
627     }
628   }
629
630   // Emit the Action Table.
631   int Entry = 0;
632   for (SmallVectorImpl<ActionEntry>::const_iterator
633          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
634     const ActionEntry &Action = *I;
635
636     if (VerboseAsm) {
637       // Emit comments that decode the action table.
638       Asm->OutStreamer.AddComment(">> Action Record " + Twine(++Entry) + " <<");
639     }
640
641     // Type Filter
642     //
643     //   Used by the runtime to match the type of the thrown exception to the
644     //   type of the catch clauses or the types in the exception specification.
645     if (VerboseAsm) {
646       if (Action.ValueForTypeID > 0)
647         Asm->OutStreamer.AddComment("  Catch TypeInfo " +
648                                     Twine(Action.ValueForTypeID));
649       else if (Action.ValueForTypeID < 0)
650         Asm->OutStreamer.AddComment("  Filter TypeInfo " +
651                                     Twine(Action.ValueForTypeID));
652       else
653         Asm->OutStreamer.AddComment("  Cleanup");
654     }
655     Asm->EmitSLEB128(Action.ValueForTypeID);
656
657     // Action Record
658     //
659     //   Self-relative signed displacement in bytes of the next action record,
660     //   or 0 if there is no next action record.
661     if (VerboseAsm) {
662       if (Action.NextAction == 0) {
663         Asm->OutStreamer.AddComment("  No further actions");
664       } else {
665         unsigned NextAction = Entry + (Action.NextAction + 1) / 2;
666         Asm->OutStreamer.AddComment("  Continue to action "+Twine(NextAction));
667       }
668     }
669     Asm->EmitSLEB128(Action.NextAction);
670   }
671
672   EmitTypeInfos(TTypeEncoding);
673
674   Asm->EmitAlignment(2);
675 }
676
677 void DwarfException::EmitTypeInfos(unsigned TTypeEncoding) {
678   const std::vector<const GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
679   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
680
681   bool VerboseAsm = Asm->OutStreamer.isVerboseAsm();
682
683   int Entry = 0;
684   // Emit the Catch TypeInfos.
685   if (VerboseAsm && !TypeInfos.empty()) {
686     Asm->OutStreamer.AddComment(">> Catch TypeInfos <<");
687     Asm->OutStreamer.AddBlankLine();
688     Entry = TypeInfos.size();
689   }
690
691   for (std::vector<const GlobalVariable *>::const_reverse_iterator
692          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
693     const GlobalVariable *GV = *I;
694     if (VerboseAsm)
695       Asm->OutStreamer.AddComment("TypeInfo " + Twine(Entry--));
696     Asm->EmitTTypeReference(GV, TTypeEncoding);
697   }
698
699   // Emit the Exception Specifications.
700   if (VerboseAsm && !FilterIds.empty()) {
701     Asm->OutStreamer.AddComment(">> Filter TypeInfos <<");
702     Asm->OutStreamer.AddBlankLine();
703     Entry = 0;
704   }
705   for (std::vector<unsigned>::const_iterator
706          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
707     unsigned TypeID = *I;
708     if (VerboseAsm) {
709       --Entry;
710       if (TypeID != 0)
711         Asm->OutStreamer.AddComment("FilterInfo " + Twine(Entry));
712     }
713
714     Asm->EmitULEB128(TypeID);
715   }
716 }
717
718 /// endModule - Emit all exception information that should come after the
719 /// content.
720 void DwarfException::endModule() {
721   llvm_unreachable("Should be implemented");
722 }
723
724 /// beginFunction - Gather pre-function exception information. Assumes it's
725 /// being emitted immediately after the function entry point.
726 void DwarfException::beginFunction(const MachineFunction *MF) {
727   llvm_unreachable("Should be implemented");
728 }
729
730 /// endFunction - Gather and emit post-function exception information.
731 void DwarfException::endFunction(const MachineFunction *) {
732   llvm_unreachable("Should be implemented");
733 }