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