change the LabelSDNode to be EHLabelSDNode and make it hold
[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), 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 = 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(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.
163 void 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     EmitFrameMoves(EHFuncBeginSym, EHFrameInfo.Moves, true);
251
252     // On Darwin the linker honors the alignment of eh_frame, which means it
253     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise you
254     // get holes which confuse readers of eh_frame.
255     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
256                        0, 0, false);
257     Asm->OutStreamer.EmitLabel(getDWLabel("eh_frame_end", EHFrameInfo.Number));
258
259     // If the function is marked used, this table should be also.  We cannot
260     // make the mark unconditional in this case, since retaining the table also
261     // retains the function in this case, and there is code around that depends
262     // on unused functions (calling undefined externals) being dead-stripped to
263     // link correctly.  Yes, there really is.
264     if (MMI->isUsedFunction(EHFrameInfo.function))
265       if (MAI->hasNoDeadStrip())
266         Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
267                                              MCSA_NoDeadStrip);
268   }
269   Asm->OutStreamer.AddBlankLine();
270 }
271
272 /// SharedTypeIds - How many leading type ids two landing pads have in common.
273 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
274                                        const LandingPadInfo *R) {
275   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
276   unsigned LSize = LIds.size(), RSize = RIds.size();
277   unsigned MinSize = LSize < RSize ? LSize : RSize;
278   unsigned Count = 0;
279
280   for (; Count != MinSize; ++Count)
281     if (LIds[Count] != RIds[Count])
282       return Count;
283
284   return Count;
285 }
286
287 /// PadLT - Order landing pads lexicographically by type id.
288 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
289   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
290   unsigned LSize = LIds.size(), RSize = RIds.size();
291   unsigned MinSize = LSize < RSize ? LSize : RSize;
292
293   for (unsigned i = 0; i != MinSize; ++i)
294     if (LIds[i] != RIds[i])
295       return LIds[i] < RIds[i];
296
297   return LSize < RSize;
298 }
299
300 /// ComputeActionsTable - Compute the actions table and gather the first action
301 /// index for each landing pad site.
302 unsigned DwarfException::
303 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
304                     SmallVectorImpl<ActionEntry> &Actions,
305                     SmallVectorImpl<unsigned> &FirstActions) {
306
307   // The action table follows the call-site table in the LSDA. The individual
308   // records are of two types:
309   //
310   //   * Catch clause
311   //   * Exception specification
312   //
313   // The two record kinds have the same format, with only small differences.
314   // They are distinguished by the "switch value" field: Catch clauses
315   // (TypeInfos) have strictly positive switch values, and exception
316   // specifications (FilterIds) have strictly negative switch values. Value 0
317   // indicates a catch-all clause.
318   //
319   // Negative type IDs index into FilterIds. Positive type IDs index into
320   // TypeInfos.  The value written for a positive type ID is just the type ID
321   // itself.  For a negative type ID, however, the value written is the
322   // (negative) byte offset of the corresponding FilterIds entry.  The byte
323   // offset is usually equal to the type ID (because the FilterIds entries are
324   // written using a variable width encoding, which outputs one byte per entry
325   // as long as the value written is not too large) but can differ.  This kind
326   // of complication does not occur for positive type IDs because type infos are
327   // output using a fixed width encoding.  FilterOffsets[i] holds the byte
328   // offset corresponding to FilterIds[i].
329
330   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
331   SmallVector<int, 16> FilterOffsets;
332   FilterOffsets.reserve(FilterIds.size());
333   int Offset = -1;
334
335   for (std::vector<unsigned>::const_iterator
336          I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
337     FilterOffsets.push_back(Offset);
338     Offset -= MCAsmInfo::getULEB128Size(*I);
339   }
340
341   FirstActions.reserve(LandingPads.size());
342
343   int FirstAction = 0;
344   unsigned SizeActions = 0;
345   const LandingPadInfo *PrevLPI = 0;
346
347   for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
348          I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
349     const LandingPadInfo *LPI = *I;
350     const std::vector<int> &TypeIds = LPI->TypeIds;
351     const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
352     unsigned SizeSiteActions = 0;
353
354     if (NumShared < TypeIds.size()) {
355       unsigned SizeAction = 0;
356       unsigned PrevAction = (unsigned)-1;
357
358       if (NumShared) {
359         const unsigned SizePrevIds = PrevLPI->TypeIds.size();
360         assert(Actions.size());
361         PrevAction = Actions.size() - 1;
362         SizeAction =
363           MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
364           MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
365
366         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
367           assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
368           SizeAction -=
369             MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
370           SizeAction += -Actions[PrevAction].NextAction;
371           PrevAction = Actions[PrevAction].Previous;
372         }
373       }
374
375       // Compute the actions.
376       for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
377         int TypeID = TypeIds[J];
378         assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
379         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
380         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
381
382         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
383         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
384         SizeSiteActions += SizeAction;
385
386         ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
387         Actions.push_back(Action);
388         PrevAction = Actions.size() - 1;
389       }
390
391       // Record the first action of the landing pad site.
392       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
393     } // else identical - re-use previous FirstAction
394
395     // Information used when created the call-site table. The action record
396     // field of the call site record is the offset of the first associated
397     // action record, relative to the start of the actions table. This value is
398     // biased by 1 (1 indicating the start of the actions table), and 0
399     // indicates that there are no actions.
400     FirstActions.push_back(FirstAction);
401
402     // Compute this sites contribution to size.
403     SizeActions += SizeSiteActions;
404
405     PrevLPI = LPI;
406   }
407
408   return SizeActions;
409 }
410
411 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
412 /// marked `nounwind'. Return `false' otherwise.
413 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
414   assert(MI->getDesc().isCall() && "This should be a call instruction!");
415
416   bool MarkedNoUnwind = false;
417   bool SawFunc = false;
418
419   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
420     const MachineOperand &MO = MI->getOperand(I);
421
422     if (MO.isGlobal()) {
423       if (Function *F = dyn_cast<Function>(MO.getGlobal())) {
424         if (SawFunc) {
425           // Be conservative. If we have more than one function operand for this
426           // call, then we can't make the assumption that it's the callee and
427           // not a parameter to the call.
428           // 
429           // FIXME: Determine if there's a way to say that `F' is the callee or
430           // parameter.
431           MarkedNoUnwind = false;
432           break;
433         }
434
435         MarkedNoUnwind = F->doesNotThrow();
436         SawFunc = true;
437       }
438     }
439   }
440
441   return MarkedNoUnwind;
442 }
443
444 /// ComputeCallSiteTable - Compute the call-site table.  The entry for an invoke
445 /// has a try-range containing the call, a non-zero landing pad, and an
446 /// appropriate action.  The entry for an ordinary call has a try-range
447 /// containing the call and zero for the landing pad and the action.  Calls
448 /// marked 'nounwind' have no entry and must not be contained in the try-range
449 /// of any entry - they form gaps in the table.  Entries must be ordered by
450 /// try-range address.
451 void DwarfException::
452 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
453                      const RangeMapType &PadMap,
454                      const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
455                      const SmallVectorImpl<unsigned> &FirstActions) {
456   // The end label of the previous invoke or nounwind try-range.
457   MCSymbol *LastLabel = 0;
458
459   // Whether there is a potentially throwing instruction (currently this means
460   // an ordinary call) between the end of the previous try-range and now.
461   bool SawPotentiallyThrowing = false;
462
463   // Whether the last CallSite entry was for an invoke.
464   bool PreviousIsInvoke = false;
465
466   // Visit all instructions in order of address.
467   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
468        I != E; ++I) {
469     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
470          MI != E; ++MI) {
471       if (!MI->isLabel()) {
472         if (MI->getDesc().isCall())
473           SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
474
475         continue;
476       }
477
478       MCSymbol *BeginLabel;
479       if (MI->getOperand(0).isImm()) {
480         unsigned BeginLabelNo = MI->getOperand(0).getImm();
481         assert(BeginLabelNo && "Invalid label!");
482         BeginLabel = getDWLabel("label", BeginLabelNo);
483       } else {
484         BeginLabel = MI->getOperand(0).getMCSymbol();
485       }
486       
487
488       // End of the previous try-range?
489       if (BeginLabel == LastLabel)
490         SawPotentiallyThrowing = false;
491
492       // Beginning of a new try-range?
493       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
494       if (L == PadMap.end())
495         // Nope, it was just some random label.
496         continue;
497
498       const PadRange &P = L->second;
499       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
500       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
501              "Inconsistent landing pad map!");
502
503       // For Dwarf exception handling (SjLj handling doesn't use this). If some
504       // instruction between the previous try-range and this one may throw,
505       // create a call-site entry with no landing pad for the region between the
506       // try-ranges.
507       if (SawPotentiallyThrowing &&
508           MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
509         CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
510         CallSites.push_back(Site);
511         PreviousIsInvoke = false;
512       }
513
514       LastLabel = LandingPad->EndLabels[P.RangeIndex];
515       assert(BeginLabel && LastLabel && "Invalid landing pad!");
516
517       if (LandingPad->LandingPadLabel) {
518         // This try-range is for an invoke.
519         CallSiteEntry Site = {
520           BeginLabel,
521           LastLabel,
522           LandingPad->LandingPadLabel,
523           FirstActions[P.PadIndex]
524         };
525
526         // Try to merge with the previous call-site. SJLJ doesn't do this
527         if (PreviousIsInvoke &&
528           MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
529           CallSiteEntry &Prev = CallSites.back();
530           if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
531             // Extend the range of the previous entry.
532             Prev.EndLabel = Site.EndLabel;
533             continue;
534           }
535         }
536
537         // Otherwise, create a new call-site.
538         if (MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
539           CallSites.push_back(Site);
540         else {
541           // SjLj EH must maintain the call sites in the order assigned
542           // to them by the SjLjPrepare pass.
543           unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
544           if (CallSites.size() < SiteNo)
545             CallSites.resize(SiteNo);
546           CallSites[SiteNo - 1] = Site;
547         }
548         PreviousIsInvoke = true;
549       } else {
550         // Create a gap.
551         PreviousIsInvoke = false;
552       }
553     }
554   }
555
556   // If some instruction between the previous try-range and the end of the
557   // function may throw, create a call-site entry with no landing pad for the
558   // region following the try-range.
559   if (SawPotentiallyThrowing &&
560       MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
561     CallSiteEntry Site = { LastLabel, 0, 0, 0 };
562     CallSites.push_back(Site);
563   }
564 }
565
566 /// EmitExceptionTable - Emit landing pads and actions.
567 ///
568 /// The general organization of the table is complex, but the basic concepts are
569 /// easy.  First there is a header which describes the location and organization
570 /// of the three components that follow.
571 ///
572 ///  1. The landing pad site information describes the range of code covered by
573 ///     the try.  In our case it's an accumulation of the ranges covered by the
574 ///     invokes in the try.  There is also a reference to the landing pad that
575 ///     handles the exception once processed.  Finally an index into the actions
576 ///     table.
577 ///  2. The action table, in our case, is composed of pairs of type IDs and next
578 ///     action offset.  Starting with the action index from the landing pad
579 ///     site, each type ID is checked for a match to the current exception.  If
580 ///     it matches then the exception and type id are passed on to the landing
581 ///     pad.  Otherwise the next action is looked up.  This chain is terminated
582 ///     with a next action of zero.  If no type id is found then the frame is
583 ///     unwound and handling continues.
584 ///  3. Type ID table contains references to all the C++ typeinfo for all
585 ///     catches in the function.  This tables is reverse indexed base 1.
586 void DwarfException::EmitExceptionTable() {
587   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
588   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
589   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
590
591   // Sort the landing pads in order of their type ids.  This is used to fold
592   // duplicate actions.
593   SmallVector<const LandingPadInfo *, 64> LandingPads;
594   LandingPads.reserve(PadInfos.size());
595
596   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
597     LandingPads.push_back(&PadInfos[i]);
598
599   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
600
601   // Compute the actions table and gather the first action index for each
602   // landing pad site.
603   SmallVector<ActionEntry, 32> Actions;
604   SmallVector<unsigned, 64> FirstActions;
605   unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
606
607   // Invokes and nounwind calls have entries in PadMap (due to being bracketed
608   // by try-range labels when lowered).  Ordinary calls do not, so appropriate
609   // try-ranges for them need be deduced when using DWARF exception handling.
610   RangeMapType PadMap;
611   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
612     const LandingPadInfo *LandingPad = LandingPads[i];
613     for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
614       MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
615       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
616       PadRange P = { i, j };
617       PadMap[BeginLabel] = P;
618     }
619   }
620
621   // Compute the call-site table.
622   SmallVector<CallSiteEntry, 64> CallSites;
623   ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
624
625   // Final tallies.
626
627   // Call sites.
628   const unsigned SiteStartSize  = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
629   const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
630   const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
631   bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
632   bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
633   unsigned CallSiteTableLength;
634
635   if (IsSJLJ)
636     CallSiteTableLength = 0;
637   else
638     CallSiteTableLength = CallSites.size() *
639       (SiteStartSize + SiteLengthSize + LandingPadSize);
640
641   for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
642     CallSiteTableLength += MCAsmInfo::getULEB128Size(CallSites[i].Action);
643     if (IsSJLJ)
644       CallSiteTableLength += MCAsmInfo::getULEB128Size(i);
645   }
646
647   // Type infos.
648   const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
649   unsigned TTypeEncoding;
650   unsigned TypeFormatSize;
651
652   if (!HaveTTData) {
653     // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
654     // that we're omitting that bit.
655     TTypeEncoding = dwarf::DW_EH_PE_omit;
656     TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
657   } else {
658     // Okay, we have actual filters or typeinfos to emit.  As such, we need to
659     // pick a type encoding for them.  We're about to emit a list of pointers to
660     // typeinfo objects at the end of the LSDA.  However, unless we're in static
661     // mode, this reference will require a relocation by the dynamic linker.
662     //
663     // Because of this, we have a couple of options:
664     // 
665     //   1) If we are in -static mode, we can always use an absolute reference
666     //      from the LSDA, because the static linker will resolve it.
667     //      
668     //   2) Otherwise, if the LSDA section is writable, we can output the direct
669     //      reference to the typeinfo and allow the dynamic linker to relocate
670     //      it.  Since it is in a writable section, the dynamic linker won't
671     //      have a problem.
672     //      
673     //   3) Finally, if we're in PIC mode and the LDSA section isn't writable,
674     //      we need to use some form of indirection.  For example, on Darwin,
675     //      we can output a statically-relocatable reference to a dyld stub. The
676     //      offset to the stub is constant, but the contents are in a section
677     //      that is updated by the dynamic linker.  This is easy enough, but we
678     //      need to tell the personality function of the unwinder to indirect
679     //      through the dyld stub.
680     //
681     // FIXME: When (3) is actually implemented, we'll have to emit the stubs
682     // somewhere.  This predicate should be moved to a shared location that is
683     // in target-independent code.
684     //
685     TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
686     TypeFormatSize = SizeOfEncodedValue(TTypeEncoding);
687   }
688
689   // Begin the exception table.
690   Asm->OutStreamer.SwitchSection(LSDASection);
691   Asm->EmitAlignment(2, 0, 0, false);
692
693   // Emit the LSDA.
694   MCSymbol *GCCETSym = 
695     Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
696                                       Twine(SubprogramCount));
697   Asm->OutStreamer.EmitLabel(GCCETSym);
698   Asm->OutStreamer.EmitLabel(getDWLabel("exception", SubprogramCount));
699
700   if (IsSJLJ)
701     Asm->OutStreamer.EmitLabel(getDWLabel("_LSDA_", Asm->getFunctionNumber()));
702
703   // Emit the LSDA header.
704   EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
705   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     EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
743     SizeAlign = 0;
744   }
745
746   // SjLj Exception handling
747   if (IsSJLJ) {
748     EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
749
750     // Add extra padding if it wasn't added to the TType base offset.
751     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       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       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     EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
792
793     // Add extra padding if it wasn't added to the TType base offset.
794     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 = getDWLabel("eh_func_begin", SubprogramCount);
801       
802       MCSymbol *BeginLabel = S.BeginLabel;
803       if (BeginLabel == 0)
804         BeginLabel = EHFuncBeginSym;
805       MCSymbol *EndLabel = S.EndLabel;
806       if (EndLabel == 0)
807         EndLabel = getDWLabel("eh_func_end", SubprogramCount);
808         
809       // Offset of the call site relative to the previous call site, counted in
810       // number of 16-byte bundles. The first call site is counted relative to
811       // the start of the procedure fragment.
812       Asm->OutStreamer.AddComment("Region start");
813       EmitSectionOffset(EHFuncBeginSym, EndLabel, true);
814       
815       Asm->OutStreamer.AddComment("Region length");
816       EmitDifference(EndLabel, BeginLabel, true);
817
818
819       // Offset of the landing pad, counted in 16-byte bundles relative to the
820       // @LPStart address.
821       Asm->OutStreamer.AddComment("Landing pad");
822       if (!S.PadLabel)
823         Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
824       else
825         EmitSectionOffset(S.PadLabel, EHFuncBeginSym, true, true);
826
827       // Offset of the first associated action record, relative to the start of
828       // the action table. This value is biased by 1 (1 indicates the start of
829       // the action table), and 0 indicates that there are no actions.
830       EmitULEB128(S.Action, "Action");
831     }
832   }
833
834   // Emit the Action Table.
835   if (Actions.size() != 0) {
836     Asm->OutStreamer.AddComment("-- Action Record Table --");
837     Asm->OutStreamer.AddBlankLine();
838   }
839   
840   for (SmallVectorImpl<ActionEntry>::const_iterator
841          I = Actions.begin(), E = Actions.end(); I != E; ++I) {
842     const ActionEntry &Action = *I;
843     Asm->OutStreamer.AddComment("Action Record");
844     Asm->OutStreamer.AddBlankLine();
845
846     // Type Filter
847     //
848     //   Used by the runtime to match the type of the thrown exception to the
849     //   type of the catch clauses or the types in the exception specification.
850     EmitSLEB128(Action.ValueForTypeID, "  TypeInfo index");
851
852     // Action Record
853     //
854     //   Self-relative signed displacement in bytes of the next action record,
855     //   or 0 if there is no next action record.
856     EmitSLEB128(Action.NextAction, "  Next action");
857   }
858
859   // Emit the Catch TypeInfos.
860   if (!TypeInfos.empty()) {
861     Asm->OutStreamer.AddComment("-- Catch TypeInfos --");
862     Asm->OutStreamer.AddBlankLine();
863   }
864   for (std::vector<GlobalVariable *>::const_reverse_iterator
865          I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
866     const GlobalVariable *GV = *I;
867
868     Asm->OutStreamer.AddComment("TypeInfo");
869     if (GV)
870       EmitReference(GV, TTypeEncoding);
871     else
872       Asm->OutStreamer.EmitIntValue(0, SizeOfEncodedValue(TTypeEncoding), 0);
873   }
874
875   // Emit the Exception Specifications.
876   if (!FilterIds.empty()) {
877     Asm->OutStreamer.AddComment("-- Filter IDs --");
878     Asm->OutStreamer.AddBlankLine();
879   }
880   for (std::vector<unsigned>::const_iterator
881          I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
882     unsigned TypeID = *I;
883     EmitULEB128(TypeID, TypeID != 0 ? "Exception specification" : 0);
884   }
885
886   Asm->EmitAlignment(2, 0, 0, false);
887 }
888
889 /// EndModule - Emit all exception information that should come after the
890 /// content.
891 void DwarfException::EndModule() {
892   if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
893     return;
894
895   if (!shouldEmitMovesModule && !shouldEmitTableModule)
896     return;
897
898   if (TimePassesIsEnabled)
899     ExceptionTimer->startTimer();
900
901   const std::vector<Function *> Personalities = MMI->getPersonalities();
902
903   for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
904     EmitCIE(Personalities[I], I);
905
906   for (std::vector<FunctionEHFrameInfo>::iterator
907          I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
908     EmitFDE(*I);
909
910   if (TimePassesIsEnabled)
911     ExceptionTimer->stopTimer();
912 }
913
914 /// BeginFunction - Gather pre-function exception information. Assumes it's
915 /// being emitted immediately after the function entry point.
916 void DwarfException::BeginFunction(const MachineFunction *MF) {
917   if (!MMI || !MAI->doesSupportExceptionHandling()) return;
918
919   if (TimePassesIsEnabled)
920     ExceptionTimer->startTimer();
921
922   this->MF = MF;
923   shouldEmitTable = shouldEmitMoves = false;
924
925   // If any landing pads survive, we need an EH table.
926   shouldEmitTable = !MMI->getLandingPads().empty();
927
928   // See if we need frame move info.
929   shouldEmitMoves = !MF->getFunction()->doesNotThrow() || UnwindTablesMandatory;
930
931   if (shouldEmitMoves || shouldEmitTable)
932     // Assumes in correct section after the entry point.
933     Asm->OutStreamer.EmitLabel(getDWLabel("eh_func_begin", ++SubprogramCount));
934
935   shouldEmitTableModule |= shouldEmitTable;
936   shouldEmitMovesModule |= shouldEmitMoves;
937
938   if (TimePassesIsEnabled)
939     ExceptionTimer->stopTimer();
940 }
941
942 /// EndFunction - Gather and emit post-function exception information.
943 ///
944 void DwarfException::EndFunction() {
945   if (!shouldEmitMoves && !shouldEmitTable) return;
946
947   if (TimePassesIsEnabled)
948     ExceptionTimer->startTimer();
949
950   Asm->OutStreamer.EmitLabel(getDWLabel("eh_func_end", SubprogramCount));
951
952   // Record if this personality index uses a landing pad.
953   bool HasLandingPad = !MMI->getLandingPads().empty();
954   UsesLSDA[MMI->getPersonalityIndex()] |= HasLandingPad;
955   
956   // Map all labels and get rid of any dead landing pads.
957   MMI->TidyLandingPads();
958
959   if (HasLandingPad)
960     EmitExceptionTable();
961
962   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
963   MCSymbol *FunctionEHSym =
964     Asm->GetSymbolWithGlobalValueBase(MF->getFunction(), ".eh",
965                                       TLOF.isFunctionEHFrameSymbolPrivate());
966   
967   // Save EH frame information
968   EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym, SubprogramCount,
969                                          MMI->getPersonalityIndex(),
970                                          MF->getFrameInfo()->hasCalls(),
971                                          !MMI->getLandingPads().empty(),
972                                          MMI->getFrameMoves(),
973                                          MF->getFunction()));
974
975   if (TimePassesIsEnabled)
976     ExceptionTimer->stopTimer();
977 }