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