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