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