OSDN Git Service

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