DwarfException.cpp revision fb65807c349b82e3f464158e89acd894cbd0b6ed
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/Module.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/MachineFrameInfo.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/CodeGen/MachineLocation.h"
20#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCSection.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSymbol.h"
26#include "llvm/Target/Mangler.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetFrameInfo.h"
29#include "llvm/Target/TargetLoweringObjectFile.h"
30#include "llvm/Target/TargetOptions.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include "llvm/Support/Dwarf.h"
33#include "llvm/Support/FormattedStream.h"
34#include "llvm/Support/Timer.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/Twine.h"
38using namespace llvm;
39
40DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
41                               const MCAsmInfo *T)
42  : DwarfPrinter(OS, A, T), shouldEmitTable(false),shouldEmitMoves(false),
43    shouldEmitTableModule(false), shouldEmitMovesModule(false),
44    ExceptionTimer(0) {
45  if (TimePassesIsEnabled)
46    ExceptionTimer = new Timer("DWARF Exception Writer");
47}
48
49DwarfException::~DwarfException() {
50  delete ExceptionTimer;
51}
52
53/// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
54/// is shared among many Frame Description Entries.  There is at least one CIE
55/// in every non-empty .debug_frame section.
56void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
57  // Size and sign of stack growth.
58  int stackGrowth =
59    Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
60    TargetFrameInfo::StackGrowsUp ?
61    TD->getPointerSize() : -TD->getPointerSize();
62
63  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
64
65  // Begin eh frame section.
66  Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
67
68  MCSymbol *EHFrameSym;
69  if (TLOF.isFunctionEHFrameSymbolPrivate())
70    EHFrameSym = getDWLabel("EH_frame", Index);
71  else
72    EHFrameSym = Asm->OutContext.GetOrCreateSymbol(Twine("EH_frame") +
73                                                   Twine(Index));
74  Asm->OutStreamer.EmitLabel(EHFrameSym);
75
76  Asm->OutStreamer.EmitLabel(getDWLabel("section_eh_frame", Index));
77
78  // Define base labels.
79  Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_common", Index));
80
81  // Define the eh frame length.
82  Asm->OutStreamer.AddComment("Length of Common Information Entry");
83  EmitDifference(getDWLabel("eh_frame_common_end", Index),
84                 getDWLabel("eh_frame_common_begin", Index), true);
85
86  // EH frame header.
87  Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_common_begin", Index));
88  Asm->OutStreamer.AddComment("CIE Identifier Tag");
89  Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
90  Asm->OutStreamer.AddComment("DW_CIE_VERSION");
91  Asm->OutStreamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1/*size*/, 0/*addr*/);
92
93  // The personality presence indicates that language specific information will
94  // show up in the eh frame.  Find out how we are supposed to lower the
95  // personality function reference:
96
97  unsigned LSDAEncoding = TLOF.getLSDAEncoding();
98  unsigned FDEEncoding = TLOF.getFDEEncoding();
99  unsigned PerEncoding = TLOF.getPersonalityEncoding();
100
101  char Augmentation[6] = { 0 };
102  unsigned AugmentationSize = 0;
103  char *APtr = Augmentation + 1;
104
105  if (PersonalityFn) {
106    // There is a personality function.
107    *APtr++ = 'P';
108    AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
109  }
110
111  if (UsesLSDA[Index]) {
112    // An LSDA pointer is in the FDE augmentation.
113    *APtr++ = 'L';
114    ++AugmentationSize;
115  }
116
117  if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
118    // A non-default pointer encoding for the FDE.
119    *APtr++ = 'R';
120    ++AugmentationSize;
121  }
122
123  if (APtr != Augmentation + 1)
124    Augmentation[0] = 'z';
125
126  Asm->OutStreamer.AddComment("CIE Augmentation");
127  Asm->OutStreamer.EmitBytes(StringRef(Augmentation, strlen(Augmentation)+1),0);
128
129  // Round out reader.
130  EmitULEB128(1, "CIE Code Alignment Factor");
131  EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
132  Asm->OutStreamer.AddComment("CIE Return Address Column");
133  Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
134
135  if (Augmentation[0]) {
136    EmitULEB128(AugmentationSize, "Augmentation Size");
137
138    // If there is a personality, we need to indicate the function's location.
139    if (PersonalityFn) {
140      EmitEncodingByte(PerEncoding, "Personality");
141      Asm->OutStreamer.AddComment("Personality");
142      EmitReference(PersonalityFn, PerEncoding);
143    }
144    if (UsesLSDA[Index])
145      EmitEncodingByte(LSDAEncoding, "LSDA");
146    if (FDEEncoding != dwarf::DW_EH_PE_absptr)
147      EmitEncodingByte(FDEEncoding, "FDE");
148  }
149
150  // Indicate locations of general callee saved registers in frame.
151  std::vector<MachineMove> Moves;
152  RI->getInitialFrameState(Moves);
153  EmitFrameMoves(NULL, 0, Moves, true);
154
155  // On Darwin the linker honors the alignment of eh_frame, which means it must
156  // be 8-byte on 64-bit targets to match what gcc does.  Otherwise you get
157  // holes which confuse readers of eh_frame.
158  Asm->EmitAlignment(TD->getPointerSize() == 4 ? 2 : 3, 0, 0, false);
159  Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_common_end", Index));
160}
161
162/// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
163void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
164  assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
165         "Should not emit 'available externally' functions at all");
166
167  const Function *TheFunc = EHFrameInfo.function;
168  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
169
170  unsigned LSDAEncoding = TLOF.getLSDAEncoding();
171  unsigned FDEEncoding = TLOF.getFDEEncoding();
172
173  Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
174
175  // Externally visible entry into the functions eh frame info. If the
176  // corresponding function is static, this should not be externally visible.
177  if (!TheFunc->hasLocalLinkage() && TLOF.isFunctionEHSymbolGlobal())
178    Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,MCSA_Global);
179
180  // If corresponding function is weak definition, this should be too.
181  if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
182    Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
183                                         MCSA_WeakDefinition);
184
185  // If corresponding function is hidden, this should be too.
186  if (TheFunc->hasHiddenVisibility())
187    if (MCSymbolAttr HiddenAttr = MAI->getHiddenVisibilityAttr())
188      Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
189                                           HiddenAttr);
190
191  // If there are no calls then you can't unwind.  This may mean we can omit the
192  // EH Frame, but some environments do not handle weak absolute symbols. If
193  // UnwindTablesMandatory is set we cannot do this optimization; the unwind
194  // info is to be available for non-EH uses.
195  if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
196      (!TheFunc->isWeakForLinker() ||
197       !MAI->getWeakDefDirective() ||
198       TLOF.getSupportsWeakOmittedEHFrame())) {
199    Asm->OutStreamer.EmitAssignment(EHFrameInfo.FunctionEHSym,
200                                    MCConstantExpr::Create(0, Asm->OutContext));
201    // This name has no connection to the function, so it might get
202    // dead-stripped when the function is not, erroneously.  Prohibit
203    // dead-stripping unconditionally.
204    if (MAI->hasNoDeadStrip())
205      Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
206                                           MCSA_NoDeadStrip);
207  } else {
208    Asm->OutStreamer.EmitLabel(EHFrameInfo.FunctionEHSym);
209
210    // EH frame header.
211    Asm->OutStreamer.AddComment("Length of Frame Information Entry");
212    EmitDifference(getDWLabel("eh_frame_end", EHFrameInfo.Number),
213                   getDWLabel("eh_frame_begin", EHFrameInfo.Number),
214                   true);
215
216    Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_begin",EHFrameInfo.Number));
217
218    Asm->OutStreamer.AddComment("FDE CIE offset");
219    EmitSectionOffset(getDWLabel("eh_frame_begin", EHFrameInfo.Number),
220                      getDWLabel("eh_frame_common",
221                                 EHFrameInfo.PersonalityIndex),
222                      true, true);
223
224    MCSymbol *EHFuncBeginSym = getDWLabel("eh_func_begin", EHFrameInfo.Number);
225
226    Asm->OutStreamer.AddComment("FDE initial location");
227    EmitReference(EHFuncBeginSym, FDEEncoding);
228
229    Asm->OutStreamer.AddComment("FDE address range");
230    EmitDifference(getDWLabel("eh_func_end", EHFrameInfo.Number),EHFuncBeginSym,
231                   SizeOfEncodedValue(FDEEncoding) == 4);
232
233    // If there is a personality and landing pads then point to the language
234    // specific data area in the exception table.
235    if (MMI->getPersonalities()[0] != NULL) {
236      unsigned Size = SizeOfEncodedValue(LSDAEncoding);
237
238      EmitULEB128(Size, "Augmentation size");
239      Asm->OutStreamer.AddComment("Language Specific Data Area");
240      if (EHFrameInfo.hasLandingPads)
241        EmitReference(getDWLabel("exception", EHFrameInfo.Number),LSDAEncoding);
242      else
243        Asm->OutStreamer.EmitIntValue(0, Size/*size*/, 0/*addrspace*/);
244
245    } else {
246      EmitULEB128(0, "Augmentation size");
247    }
248
249    // Indicate locations of function specific callee saved registers in frame.
250    // EHFuncBeginSym
251    EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
252                   true);
253
254    // On Darwin the linker honors the alignment of eh_frame, which means it
255    // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise you
256    // get holes which confuse readers of eh_frame.
257    Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
258                       0, 0, false);
259    Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_end", EHFrameInfo.Number));
260
261    // If the function is marked used, this table should be also.  We cannot
262    // make the mark unconditional in this case, since retaining the table also
263    // retains the function in this case, and there is code around that depends
264    // on unused functions (calling undefined externals) being dead-stripped to
265    // link correctly.  Yes, there really is.
266    if (MMI->isUsedFunction(EHFrameInfo.function))
267      if (MAI->hasNoDeadStrip())
268        Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
269                                             MCSA_NoDeadStrip);
270  }
271  Asm->OutStreamer.AddBlankLine();
272}
273
274/// SharedTypeIds - How many leading type ids two landing pads have in common.
275unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
276                                       const LandingPadInfo *R) {
277  const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
278  unsigned LSize = LIds.size(), RSize = RIds.size();
279  unsigned MinSize = LSize < RSize ? LSize : RSize;
280  unsigned Count = 0;
281
282  for (; Count != MinSize; ++Count)
283    if (LIds[Count] != RIds[Count])
284      return Count;
285
286  return Count;
287}
288
289/// PadLT - Order landing pads lexicographically by type id.
290bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
291  const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
292  unsigned LSize = LIds.size(), RSize = RIds.size();
293  unsigned MinSize = LSize < RSize ? LSize : RSize;
294
295  for (unsigned i = 0; i != MinSize; ++i)
296    if (LIds[i] != RIds[i])
297      return LIds[i] < RIds[i];
298
299  return LSize < RSize;
300}
301
302/// ComputeActionsTable - Compute the actions table and gather the first action
303/// index for each landing pad site.
304unsigned DwarfException::
305ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
306                    SmallVectorImpl<ActionEntry> &Actions,
307                    SmallVectorImpl<unsigned> &FirstActions) {
308
309  // The action table follows the call-site table in the LSDA. The individual
310  // records are of two types:
311  //
312  //   * Catch clause
313  //   * Exception specification
314  //
315  // The two record kinds have the same format, with only small differences.
316  // They are distinguished by the "switch value" field: Catch clauses
317  // (TypeInfos) have strictly positive switch values, and exception
318  // specifications (FilterIds) have strictly negative switch values. Value 0
319  // indicates a catch-all clause.
320  //
321  // Negative type IDs index into FilterIds. Positive type IDs index into
322  // TypeInfos.  The value written for a positive type ID is just the type ID
323  // itself.  For a negative type ID, however, the value written is the
324  // (negative) byte offset of the corresponding FilterIds entry.  The byte
325  // offset is usually equal to the type ID (because the FilterIds entries are
326  // written using a variable width encoding, which outputs one byte per entry
327  // as long as the value written is not too large) but can differ.  This kind
328  // of complication does not occur for positive type IDs because type infos are
329  // output using a fixed width encoding.  FilterOffsets[i] holds the byte
330  // offset corresponding to FilterIds[i].
331
332  const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
333  SmallVector<int, 16> FilterOffsets;
334  FilterOffsets.reserve(FilterIds.size());
335  int Offset = -1;
336
337  for (std::vector<unsigned>::const_iterator
338         I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
339    FilterOffsets.push_back(Offset);
340    Offset -= MCAsmInfo::getULEB128Size(*I);
341  }
342
343  FirstActions.reserve(LandingPads.size());
344
345  int FirstAction = 0;
346  unsigned SizeActions = 0;
347  const LandingPadInfo *PrevLPI = 0;
348
349  for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
350         I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
351    const LandingPadInfo *LPI = *I;
352    const std::vector<int> &TypeIds = LPI->TypeIds;
353    const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
354    unsigned SizeSiteActions = 0;
355
356    if (NumShared < TypeIds.size()) {
357      unsigned SizeAction = 0;
358      unsigned PrevAction = (unsigned)-1;
359
360      if (NumShared) {
361        const unsigned SizePrevIds = PrevLPI->TypeIds.size();
362        assert(Actions.size());
363        PrevAction = Actions.size() - 1;
364        SizeAction =
365          MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
366          MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
367
368        for (unsigned j = NumShared; j != SizePrevIds; ++j) {
369          assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
370          SizeAction -=
371            MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
372          SizeAction += -Actions[PrevAction].NextAction;
373          PrevAction = Actions[PrevAction].Previous;
374        }
375      }
376
377      // Compute the actions.
378      for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
379        int TypeID = TypeIds[J];
380        assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
381        int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
382        unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
383
384        int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
385        SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
386        SizeSiteActions += SizeAction;
387
388        ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
389        Actions.push_back(Action);
390        PrevAction = Actions.size() - 1;
391      }
392
393      // Record the first action of the landing pad site.
394      FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
395    } // else identical - re-use previous FirstAction
396
397    // Information used when created the call-site table. The action record
398    // field of the call site record is the offset of the first associated
399    // action record, relative to the start of the actions table. This value is
400    // biased by 1 (1 indicating the start of the actions table), and 0
401    // indicates that there are no actions.
402    FirstActions.push_back(FirstAction);
403
404    // Compute this sites contribution to size.
405    SizeActions += SizeSiteActions;
406
407    PrevLPI = LPI;
408  }
409
410  return SizeActions;
411}
412
413/// CallToNoUnwindFunction - Return `true' if this is a call to a function
414/// marked `nounwind'. Return `false' otherwise.
415bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
416  assert(MI->getDesc().isCall() && "This should be a call instruction!");
417
418  bool MarkedNoUnwind = false;
419  bool SawFunc = false;
420
421  for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
422    const MachineOperand &MO = MI->getOperand(I);
423
424    if (MO.isGlobal()) {
425      if (Function *F = dyn_cast<Function>(MO.getGlobal())) {
426        if (SawFunc) {
427          // Be conservative. If we have more than one function operand for this
428          // call, then we can't make the assumption that it's the callee and
429          // not a parameter to the call.
430          //
431          // FIXME: Determine if there's a way to say that `F' is the callee or
432          // parameter.
433          MarkedNoUnwind = false;
434          break;
435        }
436
437        MarkedNoUnwind = F->doesNotThrow();
438        SawFunc = true;
439      }
440    }
441  }
442
443  return MarkedNoUnwind;
444}
445
446/// ComputeCallSiteTable - Compute the call-site table.  The entry for an invoke
447/// has a try-range containing the call, a non-zero landing pad, and an
448/// appropriate action.  The entry for an ordinary call has a try-range
449/// containing the call and zero for the landing pad and the action.  Calls
450/// marked 'nounwind' have no entry and must not be contained in the try-range
451/// of any entry - they form gaps in the table.  Entries must be ordered by
452/// try-range address.
453void DwarfException::
454ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
455                     const RangeMapType &PadMap,
456                     const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
457                     const SmallVectorImpl<unsigned> &FirstActions) {
458  // The end label of the previous invoke or nounwind try-range.
459  unsigned LastLabel = 0;
460
461  // Whether there is a potentially throwing instruction (currently this means
462  // an ordinary call) between the end of the previous try-range and now.
463  bool SawPotentiallyThrowing = false;
464
465  // Whether the last CallSite entry was for an invoke.
466  bool PreviousIsInvoke = false;
467
468  // Visit all instructions in order of address.
469  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
470       I != E; ++I) {
471    for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
472         MI != E; ++MI) {
473      if (!MI->isLabel()) {
474        if (MI->getDesc().isCall())
475          SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
476
477        continue;
478      }
479
480      unsigned BeginLabel = MI->getOperand(0).getImm();
481      assert(BeginLabel && "Invalid label!");
482
483      // End of the previous try-range?
484      if (BeginLabel == LastLabel)
485        SawPotentiallyThrowing = false;
486
487      // Beginning of a new try-range?
488      RangeMapType::const_iterator L = PadMap.find(BeginLabel);
489      if (L == PadMap.end())
490        // Nope, it was just some random label.
491        continue;
492
493      const PadRange &P = L->second;
494      const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
495      assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
496             "Inconsistent landing pad map!");
497
498      // For Dwarf exception handling (SjLj handling doesn't use this). If some
499      // instruction between the previous try-range and this one may throw,
500      // create a call-site entry with no landing pad for the region between the
501      // try-ranges.
502      if (SawPotentiallyThrowing &&
503          MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
504        CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
505        CallSites.push_back(Site);
506        PreviousIsInvoke = false;
507      }
508
509      LastLabel = LandingPad->EndLabels[P.RangeIndex];
510      assert(BeginLabel && LastLabel && "Invalid landing pad!");
511
512      if (LandingPad->LandingPadLabel) {
513        // This try-range is for an invoke.
514        CallSiteEntry Site = {
515          BeginLabel,
516          LastLabel,
517          LandingPad->LandingPadLabel,
518          FirstActions[P.PadIndex]
519        };
520
521        // Try to merge with the previous call-site. SJLJ doesn't do this
522        if (PreviousIsInvoke &&
523          MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
524          CallSiteEntry &Prev = CallSites.back();
525          if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
526            // Extend the range of the previous entry.
527            Prev.EndLabel = Site.EndLabel;
528            continue;
529          }
530        }
531
532        // Otherwise, create a new call-site.
533        if (MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
534          CallSites.push_back(Site);
535        else {
536          // SjLj EH must maintain the call sites in the order assigned
537          // to them by the SjLjPrepare pass.
538          unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
539          if (CallSites.size() < SiteNo)
540            CallSites.resize(SiteNo);
541          CallSites[SiteNo - 1] = Site;
542        }
543        PreviousIsInvoke = true;
544      } else {
545        // Create a gap.
546        PreviousIsInvoke = false;
547      }
548    }
549  }
550
551  // If some instruction between the previous try-range and the end of the
552  // function may throw, create a call-site entry with no landing pad for the
553  // region following the try-range.
554  if (SawPotentiallyThrowing &&
555      MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
556    CallSiteEntry Site = { LastLabel, 0, 0, 0 };
557    CallSites.push_back(Site);
558  }
559}
560
561/// EmitExceptionTable - Emit landing pads and actions.
562///
563/// The general organization of the table is complex, but the basic concepts are
564/// easy.  First there is a header which describes the location and organization
565/// of the three components that follow.
566///
567///  1. The landing pad site information describes the range of code covered by
568///     the try.  In our case it's an accumulation of the ranges covered by the
569///     invokes in the try.  There is also a reference to the landing pad that
570///     handles the exception once processed.  Finally an index into the actions
571///     table.
572///  2. The action table, in our case, is composed of pairs of type IDs and next
573///     action offset.  Starting with the action index from the landing pad
574///     site, each type ID is checked for a match to the current exception.  If
575///     it matches then the exception and type id are passed on to the landing
576///     pad.  Otherwise the next action is looked up.  This chain is terminated
577///     with a next action of zero.  If no type id is found then the frame is
578///     unwound and handling continues.
579///  3. Type ID table contains references to all the C++ typeinfo for all
580///     catches in the function.  This tables is reverse indexed base 1.
581void DwarfException::EmitExceptionTable() {
582  const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
583  const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
584  const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
585  if (PadInfos.empty()) return;
586
587  // Sort the landing pads in order of their type ids.  This is used to fold
588  // duplicate actions.
589  SmallVector<const LandingPadInfo *, 64> LandingPads;
590  LandingPads.reserve(PadInfos.size());
591
592  for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
593    LandingPads.push_back(&PadInfos[i]);
594
595  std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
596
597  // Compute the actions table and gather the first action index for each
598  // landing pad site.
599  SmallVector<ActionEntry, 32> Actions;
600  SmallVector<unsigned, 64> FirstActions;
601  unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
602
603  // Invokes and nounwind calls have entries in PadMap (due to being bracketed
604  // by try-range labels when lowered).  Ordinary calls do not, so appropriate
605  // try-ranges for them need be deduced when using DWARF exception handling.
606  RangeMapType PadMap;
607  for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
608    const LandingPadInfo *LandingPad = LandingPads[i];
609    for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
610      unsigned BeginLabel = LandingPad->BeginLabels[j];
611      assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
612      PadRange P = { i, j };
613      PadMap[BeginLabel] = P;
614    }
615  }
616
617  // Compute the call-site table.
618  SmallVector<CallSiteEntry, 64> CallSites;
619  ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
620
621  // Final tallies.
622
623  // Call sites.
624  const unsigned SiteStartSize  = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
625  const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
626  const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
627  bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
628  bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
629  unsigned CallSiteTableLength;
630
631  if (IsSJLJ)
632    CallSiteTableLength = 0;
633  else
634    CallSiteTableLength = CallSites.size() *
635      (SiteStartSize + SiteLengthSize + LandingPadSize);
636
637  for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
638    CallSiteTableLength += MCAsmInfo::getULEB128Size(CallSites[i].Action);
639    if (IsSJLJ)
640      CallSiteTableLength += MCAsmInfo::getULEB128Size(i);
641  }
642
643  // Type infos.
644  const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
645  unsigned TTypeEncoding;
646  unsigned TypeFormatSize;
647
648  if (!HaveTTData) {
649    // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
650    // that we're omitting that bit.
651    TTypeEncoding = dwarf::DW_EH_PE_omit;
652    TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
653  } else {
654    // Okay, we have actual filters or typeinfos to emit.  As such, we need to
655    // pick a type encoding for them.  We're about to emit a list of pointers to
656    // typeinfo objects at the end of the LSDA.  However, unless we're in static
657    // mode, this reference will require a relocation by the dynamic linker.
658    //
659    // Because of this, we have a couple of options:
660    //
661    //   1) If we are in -static mode, we can always use an absolute reference
662    //      from the LSDA, because the static linker will resolve it.
663    //
664    //   2) Otherwise, if the LSDA section is writable, we can output the direct
665    //      reference to the typeinfo and allow the dynamic linker to relocate
666    //      it.  Since it is in a writable section, the dynamic linker won't
667    //      have a problem.
668    //
669    //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
670    //      we need to use some form of indirection.  For example, on Darwin,
671    //      we can output a statically-relocatable reference to a dyld stub. The
672    //      offset to the stub is constant, but the contents are in a section
673    //      that is updated by the dynamic linker.  This is easy enough, but we
674    //      need to tell the personality function of the unwinder to indirect
675    //      through the dyld stub.
676    //
677    // FIXME: When (3) is actually implemented, we'll have to emit the stubs
678    // somewhere.  This predicate should be moved to a shared location that is
679    // in target-independent code.
680    //
681    TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
682    TypeFormatSize = SizeOfEncodedValue(TTypeEncoding);
683  }
684
685  // Begin the exception table.
686  Asm->OutStreamer.SwitchSection(LSDASection);
687  Asm->EmitAlignment(2, 0, 0, false);
688
689  // Emit the LSDA.
690  MCSymbol *GCCETSym =
691    Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
692                                      Twine(SubprogramCount));
693  Asm->OutStreamer.EmitLabel(GCCETSym);
694  Asm->OutStreamer.EmitLabel(getDWLabel("exception", SubprogramCount));
695
696  if (IsSJLJ)
697    Asm->OutStreamer.EmitLabel(getDWLabel("_LSDA_", Asm->getFunctionNumber()));
698
699  // Emit the LSDA header.
700  EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
701  EmitEncodingByte(TTypeEncoding, "@TType");
702
703  // The type infos need to be aligned. GCC does this by inserting padding just
704  // before the type infos. However, this changes the size of the exception
705  // table, so you need to take this into account when you output the exception
706  // table size. However, the size is output using a variable length encoding.
707  // So by increasing the size by inserting padding, you may increase the number
708  // of bytes used for writing the size. If it increases, say by one byte, then
709  // you now need to output one less byte of padding to get the type infos
710  // aligned. However this decreases the size of the exception table. This
711  // changes the value you have to output for the exception table size. Due to
712  // the variable length encoding, the number of bytes used for writing the
713  // length may decrease. If so, you then have to increase the amount of
714  // padding. And so on. If you look carefully at the GCC code you will see that
715  // it indeed does this in a loop, going on and on until the values stabilize.
716  // We chose another solution: don't output padding inside the table like GCC
717  // does, instead output it before the table.
718  unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
719  unsigned CallSiteTableLengthSize =
720    MCAsmInfo::getULEB128Size(CallSiteTableLength);
721  unsigned TTypeBaseOffset =
722    sizeof(int8_t) +                            // Call site format
723    CallSiteTableLengthSize +                   // Call site table length size
724    CallSiteTableLength +                       // Call site table length
725    SizeActions +                               // Actions size
726    SizeTypes;
727  unsigned TTypeBaseOffsetSize = MCAsmInfo::getULEB128Size(TTypeBaseOffset);
728  unsigned TotalSize =
729    sizeof(int8_t) +                            // LPStart format
730    sizeof(int8_t) +                            // TType format
731    (HaveTTData ? TTypeBaseOffsetSize : 0) +    // TType base offset size
732    TTypeBaseOffset;                            // TType base offset
733  unsigned SizeAlign = (4 - TotalSize) & 3;
734
735  if (HaveTTData) {
736    // Account for any extra padding that will be added to the call site table
737    // length.
738    EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
739    SizeAlign = 0;
740  }
741
742  // SjLj Exception handling
743  if (IsSJLJ) {
744    EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
745
746    // Add extra padding if it wasn't added to the TType base offset.
747    EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
748
749    // Emit the landing pad site information.
750    unsigned idx = 0;
751    for (SmallVectorImpl<CallSiteEntry>::const_iterator
752         I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
753      const CallSiteEntry &S = *I;
754
755      // Offset of the landing pad, counted in 16-byte bundles relative to the
756      // @LPStart address.
757      EmitULEB128(idx, "Landing pad");
758
759      // Offset of the first associated action record, relative to the start of
760      // the action table. This value is biased by 1 (1 indicates the start of
761      // the action table), and 0 indicates that there are no actions.
762      EmitULEB128(S.Action, "Action");
763    }
764  } else {
765    // DWARF Exception handling
766    assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
767
768    // The call-site table is a list of all call sites that may throw an
769    // exception (including C++ 'throw' statements) in the procedure
770    // fragment. It immediately follows the LSDA header. Each entry indicates,
771    // for a given call, the first corresponding action record and corresponding
772    // landing pad.
773    //
774    // The table begins with the number of bytes, stored as an LEB128
775    // compressed, unsigned integer. The records immediately follow the record
776    // count. They are sorted in increasing call-site address. Each record
777    // indicates:
778    //
779    //   * The position of the call-site.
780    //   * The position of the landing pad.
781    //   * The first action record for that call site.
782    //
783    // A missing entry in the call-site table indicates that a call is not
784    // supposed to throw.
785
786    // Emit the landing pad call site table.
787    EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
788
789    // Add extra padding if it wasn't added to the TType base offset.
790    EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
791
792    for (SmallVectorImpl<CallSiteEntry>::const_iterator
793         I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
794      const CallSiteEntry &S = *I;
795      const char *BeginTag;
796      unsigned BeginNumber;
797
798      if (!S.BeginLabel) {
799        BeginTag = "eh_func_begin";
800        BeginNumber = SubprogramCount;
801      } else {
802        BeginTag = "label";
803        BeginNumber = S.BeginLabel;
804      }
805
806      // Offset of the call site relative to the previous call site, counted in
807      // number of 16-byte bundles. The first call site is counted relative to
808      // the start of the procedure fragment.
809      Asm->OutStreamer.AddComment("Region start");
810      EmitSectionOffset(getDWLabel(BeginTag, BeginNumber),
811                        getDWLabel("eh_func_begin", SubprogramCount),
812                        true, true);
813
814      Asm->OutStreamer.AddComment("Region length");
815      if (!S.EndLabel)
816        EmitDifference(getDWLabel("eh_func_end", SubprogramCount),
817                       getDWLabel(BeginTag, BeginNumber),
818                       true);
819      else
820        EmitDifference(getDWLabel("label", S.EndLabel),
821                       getDWLabel(BeginTag, BeginNumber), true);
822
823
824      // Offset of the landing pad, counted in 16-byte bundles relative to the
825      // @LPStart address.
826      Asm->OutStreamer.AddComment("Landing pad");
827      if (!S.PadLabel) {
828        Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
829      } else {
830        EmitSectionOffset(getDWLabel("label", S.PadLabel),
831                          getDWLabel("eh_func_begin", SubprogramCount),
832                          true, true);
833      }
834
835      // Offset of the first associated action record, relative to the start of
836      // the action table. This value is biased by 1 (1 indicates the start of
837      // the action table), and 0 indicates that there are no actions.
838      EmitULEB128(S.Action, "Action");
839    }
840  }
841
842  // Emit the Action Table.
843  if (Actions.size() != 0) {
844    Asm->OutStreamer.AddComment("-- Action Record Table --");
845    Asm->OutStreamer.AddBlankLine();
846  }
847
848  for (SmallVectorImpl<ActionEntry>::const_iterator
849         I = Actions.begin(), E = Actions.end(); I != E; ++I) {
850    const ActionEntry &Action = *I;
851    Asm->OutStreamer.AddComment("Action Record");
852    Asm->OutStreamer.AddBlankLine();
853
854    // Type Filter
855    //
856    //   Used by the runtime to match the type of the thrown exception to the
857    //   type of the catch clauses or the types in the exception specification.
858    EmitSLEB128(Action.ValueForTypeID, "  TypeInfo index");
859
860    // Action Record
861    //
862    //   Self-relative signed displacement in bytes of the next action record,
863    //   or 0 if there is no next action record.
864    EmitSLEB128(Action.NextAction, "  Next action");
865  }
866
867  // Emit the Catch TypeInfos.
868  if (!TypeInfos.empty()) {
869    Asm->OutStreamer.AddComment("-- Catch TypeInfos --");
870    Asm->OutStreamer.AddBlankLine();
871  }
872  for (std::vector<GlobalVariable *>::const_reverse_iterator
873         I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
874    const GlobalVariable *GV = *I;
875
876    Asm->OutStreamer.AddComment("TypeInfo");
877    if (GV)
878      EmitReference(GV, TTypeEncoding);
879    else
880      Asm->OutStreamer.EmitIntValue(0, SizeOfEncodedValue(TTypeEncoding), 0);
881  }
882
883  // Emit the Exception Specifications.
884  if (!FilterIds.empty()) {
885    Asm->OutStreamer.AddComment("-- Filter IDs --");
886    Asm->OutStreamer.AddBlankLine();
887  }
888  for (std::vector<unsigned>::const_iterator
889         I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
890    unsigned TypeID = *I;
891    EmitULEB128(TypeID, TypeID != 0 ? "Exception specification" : 0);
892  }
893
894  Asm->EmitAlignment(2, 0, 0, false);
895}
896
897/// EndModule - Emit all exception information that should come after the
898/// content.
899void DwarfException::EndModule() {
900  if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
901    return;
902
903  if (!shouldEmitMovesModule && !shouldEmitTableModule)
904    return;
905
906  if (TimePassesIsEnabled)
907    ExceptionTimer->startTimer();
908
909  const std::vector<Function *> Personalities = MMI->getPersonalities();
910
911  for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
912    EmitCIE(Personalities[I], I);
913
914  for (std::vector<FunctionEHFrameInfo>::iterator
915         I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
916    EmitFDE(*I);
917
918  if (TimePassesIsEnabled)
919    ExceptionTimer->stopTimer();
920}
921
922/// BeginFunction - Gather pre-function exception information. Assumes it's
923/// being emitted immediately after the function entry point.
924void DwarfException::BeginFunction(const MachineFunction *MF) {
925  if (!MMI || !MAI->doesSupportExceptionHandling()) return;
926
927  if (TimePassesIsEnabled)
928    ExceptionTimer->startTimer();
929
930  this->MF = MF;
931  shouldEmitTable = shouldEmitMoves = false;
932
933  // Map all labels and get rid of any dead landing pads.
934  MMI->TidyLandingPads();
935
936  // If any landing pads survive, we need an EH table.
937  if (!MMI->getLandingPads().empty())
938    shouldEmitTable = true;
939
940  // See if we need frame move info.
941  if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
942    shouldEmitMoves = true;
943
944  if (shouldEmitMoves || shouldEmitTable)
945    // Assumes in correct section after the entry point.
946    Asm->OutStreamer.EmitLabel(getDWLabel("eh_func_begin", ++SubprogramCount));
947
948  shouldEmitTableModule |= shouldEmitTable;
949  shouldEmitMovesModule |= shouldEmitMoves;
950
951  if (TimePassesIsEnabled)
952    ExceptionTimer->stopTimer();
953}
954
955/// EndFunction - Gather and emit post-function exception information.
956///
957void DwarfException::EndFunction() {
958  if (!shouldEmitMoves && !shouldEmitTable) return;
959
960  if (TimePassesIsEnabled)
961    ExceptionTimer->startTimer();
962
963  Asm->OutStreamer.EmitLabel(getDWLabel("eh_func_end", SubprogramCount));
964  EmitExceptionTable();
965
966  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
967  MCSymbol *FunctionEHSym =
968    Asm->GetSymbolWithGlobalValueBase(MF->getFunction(), ".eh",
969                                      TLOF.isFunctionEHFrameSymbolPrivate());
970
971  // Save EH frame information
972  EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym, SubprogramCount,
973                                         MMI->getPersonalityIndex(),
974                                         MF->getFrameInfo()->hasCalls(),
975                                         !MMI->getLandingPads().empty(),
976                                         MMI->getFrameMoves(),
977                                         MF->getFunction()));
978
979  // Record if this personality index uses a landing pad.
980  UsesLSDA[MMI->getPersonalityIndex()] |= !MMI->getLandingPads().empty();
981
982  if (TimePassesIsEnabled)
983    ExceptionTimer->stopTimer();
984}
985