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