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