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