[WinEH] Delete the old landingpad implementation of Windows EH
[oota-llvm.git] / lib / CodeGen / SelectionDAG / FunctionLoweringInfo.cpp
1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
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 implements routines for translating functions from LLVM IR into
11 // Machine IR.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/FunctionLoweringInfo.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include <algorithm>
43 using namespace llvm;
44
45 #define DEBUG_TYPE "function-lowering-info"
46
47 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
48 /// PHI nodes or outside of the basic block that defines it, or used by a
49 /// switch or atomic instruction, which may expand to multiple basic blocks.
50 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
51   if (I->use_empty()) return false;
52   if (isa<PHINode>(I)) return true;
53   const BasicBlock *BB = I->getParent();
54   for (const User *U : I->users())
55     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
56       return true;
57
58   return false;
59 }
60
61 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
62   // For the users of the source value being used for compare instruction, if
63   // the number of signed predicate is greater than unsigned predicate, we
64   // prefer to use SIGN_EXTEND.
65   //
66   // With this optimization, we would be able to reduce some redundant sign or
67   // zero extension instruction, and eventually more machine CSE opportunities
68   // can be exposed.
69   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
70   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
71   for (const User *U : V->users()) {
72     if (const auto *CI = dyn_cast<CmpInst>(U)) {
73       NumOfSigned += CI->isSigned();
74       NumOfUnsigned += CI->isUnsigned();
75     }
76   }
77   if (NumOfSigned > NumOfUnsigned)
78     ExtendKind = ISD::SIGN_EXTEND;
79
80   return ExtendKind;
81 }
82
83 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
84                                SelectionDAG *DAG) {
85   Fn = &fn;
86   MF = &mf;
87   TLI = MF->getSubtarget().getTargetLowering();
88   RegInfo = &MF->getRegInfo();
89   MachineModuleInfo &MMI = MF->getMMI();
90
91   // Check whether the function can return without sret-demotion.
92   SmallVector<ISD::OutputArg, 4> Outs;
93   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
94                 mf.getDataLayout());
95   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
96                                        Fn->isVarArg(), Outs, Fn->getContext());
97
98   // Initialize the mapping of values to registers.  This is only set up for
99   // instruction values that are used outside of the block that defines
100   // them.
101   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
102   for (; BB != EB; ++BB)
103     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
104          I != E; ++I) {
105       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
106         // Static allocas can be folded into the initial stack frame adjustment.
107         if (AI->isStaticAlloca()) {
108           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
109           Type *Ty = AI->getAllocatedType();
110           uint64_t TySize = MF->getDataLayout().getTypeAllocSize(Ty);
111           unsigned Align =
112               std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
113                        AI->getAlignment());
114
115           TySize *= CUI->getZExtValue();   // Get total allocated size.
116           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
117
118           StaticAllocaMap[AI] =
119             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
120
121         } else {
122           unsigned Align =
123               std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(
124                            AI->getAllocatedType()),
125                        AI->getAlignment());
126           unsigned StackAlign =
127               MF->getSubtarget().getFrameLowering()->getStackAlignment();
128           if (Align <= StackAlign)
129             Align = 0;
130           // Inform the Frame Information that we have variable-sized objects.
131           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
132         }
133       }
134
135       // Look for inline asm that clobbers the SP register.
136       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
137         ImmutableCallSite CS(I);
138         if (isa<InlineAsm>(CS.getCalledValue())) {
139           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
140           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
141           std::vector<TargetLowering::AsmOperandInfo> Ops =
142               TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
143           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
144             TargetLowering::AsmOperandInfo &Op = Ops[I];
145             if (Op.Type == InlineAsm::isClobber) {
146               // Clobbers don't have SDValue operands, hence SDValue().
147               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
148               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
149                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
150                                                     Op.ConstraintVT);
151               if (PhysReg.first == SP)
152                 MF->getFrameInfo()->setHasOpaqueSPAdjustment(true);
153             }
154           }
155         }
156       }
157
158       // Look for calls to the @llvm.va_start intrinsic. We can omit some
159       // prologue boilerplate for variadic functions that don't examine their
160       // arguments.
161       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
162         if (II->getIntrinsicID() == Intrinsic::vastart)
163           MF->getFrameInfo()->setHasVAStart(true);
164       }
165
166       // If we have a musttail call in a variadic funciton, we need to ensure we
167       // forward implicit register parameters.
168       if (const auto *CI = dyn_cast<CallInst>(I)) {
169         if (CI->isMustTailCall() && Fn->isVarArg())
170           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
171       }
172
173       // Mark values used outside their block as exported, by allocating
174       // a virtual register for them.
175       if (isUsedOutsideOfDefiningBlock(I))
176         if (!isa<AllocaInst>(I) ||
177             !StaticAllocaMap.count(cast<AllocaInst>(I)))
178           InitializeRegForValue(I);
179
180       // Collect llvm.dbg.declare information. This is done now instead of
181       // during the initial isel pass through the IR so that it is done
182       // in a predictable order.
183       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
184         assert(DI->getVariable() && "Missing variable");
185         assert(DI->getDebugLoc() && "Missing location");
186         if (MMI.hasDebugInfo()) {
187           // Don't handle byval struct arguments or VLAs, for example.
188           // Non-byval arguments are handled here (they refer to the stack
189           // temporary alloca at this point).
190           const Value *Address = DI->getAddress();
191           if (Address) {
192             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
193               Address = BCI->getOperand(0);
194             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
195               DenseMap<const AllocaInst *, int>::iterator SI =
196                 StaticAllocaMap.find(AI);
197               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
198                 int FI = SI->second;
199                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
200                                        FI, DI->getDebugLoc());
201               }
202             }
203           }
204         }
205       }
206
207       // Decide the preferred extend type for a value.
208       PreferredExtendType[I] = getPreferredExtendForValue(I);
209     }
210
211   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
212   // also creates the initial PHI MachineInstrs, though none of the input
213   // operands are populated.
214   for (BB = Fn->begin(); BB != EB; ++BB) {
215     // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
216     // are really data, and no instructions can live here.
217     if (BB->isEHPad()) {
218       const Instruction *I = BB->getFirstNonPHI();
219       // FIXME: Don't mark SEH functions without __finally blocks as having
220       // funclets.
221       if (!isa<LandingPadInst>(I))
222         MMI.setHasEHFunclets(true);
223       if (isa<CatchEndPadInst>(I) || isa<CleanupEndPadInst>(I)) {
224         assert(&*BB->begin() == I &&
225                "WinEHPrepare failed to remove PHIs from imaginary BBs");
226         continue;
227       }
228       if (isa<CatchPadInst>(I) || isa<CleanupPadInst>(I))
229         assert(&*BB->begin() == I && "WinEHPrepare failed to demote PHIs");
230     }
231
232     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
233     MBBMap[BB] = MBB;
234     MF->push_back(MBB);
235
236     // Transfer the address-taken flag. This is necessary because there could
237     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
238     // the first one should be marked.
239     if (BB->hasAddressTaken())
240       MBB->setHasAddressTaken();
241
242     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
243     // appropriate.
244     for (BasicBlock::const_iterator I = BB->begin();
245          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
246       if (PN->use_empty()) continue;
247
248       // Skip empty types
249       if (PN->getType()->isEmptyTy())
250         continue;
251
252       DebugLoc DL = PN->getDebugLoc();
253       unsigned PHIReg = ValueMap[PN];
254       assert(PHIReg && "PHI node does not have an assigned virtual register!");
255
256       SmallVector<EVT, 4> ValueVTs;
257       ComputeValueVTs(*TLI, MF->getDataLayout(), PN->getType(), ValueVTs);
258       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
259         EVT VT = ValueVTs[vti];
260         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
261         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
262         for (unsigned i = 0; i != NumRegisters; ++i)
263           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
264         PHIReg += NumRegisters;
265       }
266     }
267   }
268
269   // Mark landing pad blocks.
270   SmallVector<const LandingPadInst *, 4> LPads;
271   for (BB = Fn->begin(); BB != EB; ++BB) {
272     const Instruction *FNP = BB->getFirstNonPHI();
273     if (BB->isEHPad() && MBBMap.count(BB))
274       MBBMap[BB]->setIsEHPad();
275     if (const auto *LPI = dyn_cast<LandingPadInst>(FNP))
276       LPads.push_back(LPI);
277   }
278
279   // If this personality uses funclets, we need to do a bit more work.
280   if (!Fn->hasPersonalityFn())
281     return;
282   EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
283   if (!isFuncletEHPersonality(Personality))
284     return;
285
286   // Calculate state numbers if we haven't already.
287   WinEHFuncInfo &EHInfo = MMI.getWinEHFuncInfo(&fn);
288   const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
289   if (Personality == EHPersonality::MSVC_CXX)
290     calculateWinCXXEHStateNumbers(WinEHParentFn, EHInfo);
291   else if (isAsynchronousEHPersonality(Personality))
292     calculateSEHStateNumbers(WinEHParentFn, EHInfo);
293   else if (Personality == EHPersonality::CoreCLR)
294     calculateClrEHStateNumbers(WinEHParentFn, EHInfo);
295
296   calculateCatchReturnSuccessorColors(WinEHParentFn, EHInfo);
297
298   // Map all BB references in the WinEH data to MBBs.
299   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
300     for (WinEHHandlerType &H : TBME.HandlerArray) {
301       if (H.CatchObjRecoverIdx == -2 && H.CatchObj.Alloca) {
302         assert(StaticAllocaMap.count(H.CatchObj.Alloca));
303         H.CatchObj.FrameIndex = StaticAllocaMap[H.CatchObj.Alloca];
304       } else {
305         H.CatchObj.FrameIndex = INT_MAX;
306       }
307       if (const auto *BB = dyn_cast<BasicBlock>(H.Handler.get<const Value *>()))
308         H.Handler = MBBMap[BB];
309     }
310   }
311   for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
312     if (UME.Cleanup)
313       if (const auto *BB = dyn_cast<BasicBlock>(UME.Cleanup.get<const Value *>()))
314         UME.Cleanup = MBBMap[BB];
315   for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
316     const BasicBlock *BB = UME.Handler.get<const BasicBlock *>();
317     UME.Handler = MBBMap[BB];
318   }
319   for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
320     const BasicBlock *BB = CME.Handler.get<const BasicBlock *>();
321     CME.Handler = MBBMap[BB];
322   }
323
324   // If there's an explicit EH registration node on the stack, record its
325   // frame index.
326   if (EHInfo.EHRegNode && EHInfo.EHRegNode->getParent()->getParent() == Fn) {
327     assert(StaticAllocaMap.count(EHInfo.EHRegNode));
328     EHInfo.EHRegNodeFrameIndex = StaticAllocaMap[EHInfo.EHRegNode];
329   }
330
331   // Copy the state numbers to LandingPadInfo for the current function, which
332   // could be a handler or the parent. This should happen for 32-bit SEH and
333   // C++ EH.
334   if (Personality == EHPersonality::MSVC_CXX ||
335       Personality == EHPersonality::MSVC_X86SEH) {
336     for (const LandingPadInst *LP : LPads) {
337       MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
338       MMI.addWinEHState(LPadMBB, EHInfo.EHPadStateMap[LP]);
339     }
340   }
341 }
342
343 /// clear - Clear out all the function-specific state. This returns this
344 /// FunctionLoweringInfo to an empty state, ready to be used for a
345 /// different function.
346 void FunctionLoweringInfo::clear() {
347   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
348          "Not all catch info was assigned to a landing pad!");
349
350   MBBMap.clear();
351   ValueMap.clear();
352   StaticAllocaMap.clear();
353 #ifndef NDEBUG
354   CatchInfoLost.clear();
355   CatchInfoFound.clear();
356 #endif
357   LiveOutRegInfo.clear();
358   VisitedBBs.clear();
359   ArgDbgValues.clear();
360   ByValArgFrameIndexMap.clear();
361   RegFixups.clear();
362   StatepointStackSlots.clear();
363   StatepointRelocatedValues.clear();
364   PreferredExtendType.clear();
365 }
366
367 /// CreateReg - Allocate a single virtual register for the given type.
368 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
369   return RegInfo->createVirtualRegister(
370       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
371 }
372
373 /// CreateRegs - Allocate the appropriate number of virtual registers of
374 /// the correctly promoted or expanded types.  Assign these registers
375 /// consecutive vreg numbers and return the first assigned number.
376 ///
377 /// In the case that the given value has struct or array type, this function
378 /// will assign registers for each member or element.
379 ///
380 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
381   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
382
383   SmallVector<EVT, 4> ValueVTs;
384   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
385
386   unsigned FirstReg = 0;
387   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
388     EVT ValueVT = ValueVTs[Value];
389     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
390
391     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
392     for (unsigned i = 0; i != NumRegs; ++i) {
393       unsigned R = CreateReg(RegisterVT);
394       if (!FirstReg) FirstReg = R;
395     }
396   }
397   return FirstReg;
398 }
399
400 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
401 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
402 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
403 /// the larger bit width by zero extension. The bit width must be no smaller
404 /// than the LiveOutInfo's existing bit width.
405 const FunctionLoweringInfo::LiveOutInfo *
406 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
407   if (!LiveOutRegInfo.inBounds(Reg))
408     return nullptr;
409
410   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
411   if (!LOI->IsValid)
412     return nullptr;
413
414   if (BitWidth > LOI->KnownZero.getBitWidth()) {
415     LOI->NumSignBits = 1;
416     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
417     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
418   }
419
420   return LOI;
421 }
422
423 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
424 /// register based on the LiveOutInfo of its operands.
425 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
426   Type *Ty = PN->getType();
427   if (!Ty->isIntegerTy() || Ty->isVectorTy())
428     return;
429
430   SmallVector<EVT, 1> ValueVTs;
431   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
432   assert(ValueVTs.size() == 1 &&
433          "PHIs with non-vector integer types should have a single VT.");
434   EVT IntVT = ValueVTs[0];
435
436   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
437     return;
438   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
439   unsigned BitWidth = IntVT.getSizeInBits();
440
441   unsigned DestReg = ValueMap[PN];
442   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
443     return;
444   LiveOutRegInfo.grow(DestReg);
445   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
446
447   Value *V = PN->getIncomingValue(0);
448   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
449     DestLOI.NumSignBits = 1;
450     APInt Zero(BitWidth, 0);
451     DestLOI.KnownZero = Zero;
452     DestLOI.KnownOne = Zero;
453     return;
454   }
455
456   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
457     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
458     DestLOI.NumSignBits = Val.getNumSignBits();
459     DestLOI.KnownZero = ~Val;
460     DestLOI.KnownOne = Val;
461   } else {
462     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
463                                 "CopyToReg node was created.");
464     unsigned SrcReg = ValueMap[V];
465     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
466       DestLOI.IsValid = false;
467       return;
468     }
469     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
470     if (!SrcLOI) {
471       DestLOI.IsValid = false;
472       return;
473     }
474     DestLOI = *SrcLOI;
475   }
476
477   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
478          DestLOI.KnownOne.getBitWidth() == BitWidth &&
479          "Masks should have the same bit width as the type.");
480
481   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
482     Value *V = PN->getIncomingValue(i);
483     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
484       DestLOI.NumSignBits = 1;
485       APInt Zero(BitWidth, 0);
486       DestLOI.KnownZero = Zero;
487       DestLOI.KnownOne = Zero;
488       return;
489     }
490
491     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
492       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
493       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
494       DestLOI.KnownZero &= ~Val;
495       DestLOI.KnownOne &= Val;
496       continue;
497     }
498
499     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
500                                 "its CopyToReg node was created.");
501     unsigned SrcReg = ValueMap[V];
502     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
503       DestLOI.IsValid = false;
504       return;
505     }
506     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
507     if (!SrcLOI) {
508       DestLOI.IsValid = false;
509       return;
510     }
511     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
512     DestLOI.KnownZero &= SrcLOI->KnownZero;
513     DestLOI.KnownOne &= SrcLOI->KnownOne;
514   }
515 }
516
517 /// setArgumentFrameIndex - Record frame index for the byval
518 /// argument. This overrides previous frame index entry for this argument,
519 /// if any.
520 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
521                                                  int FI) {
522   ByValArgFrameIndexMap[A] = FI;
523 }
524
525 /// getArgumentFrameIndex - Get frame index for the byval argument.
526 /// If the argument does not have any assigned frame index then 0 is
527 /// returned.
528 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
529   DenseMap<const Argument *, int>::iterator I =
530     ByValArgFrameIndexMap.find(A);
531   if (I != ByValArgFrameIndexMap.end())
532     return I->second;
533   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
534   return 0;
535 }
536
537 unsigned FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
538     const Value *CPI, const TargetRegisterClass *RC) {
539   MachineRegisterInfo &MRI = MF->getRegInfo();
540   auto I = CatchPadExceptionPointers.insert({CPI, 0});
541   unsigned &VReg = I.first->second;
542   if (I.second)
543     VReg = MRI.createVirtualRegister(RC);
544   assert(VReg && "null vreg in exception pointer table!");
545   return VReg;
546 }
547
548 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
549 /// being passed to this variadic function, and set the MachineModuleInfo's
550 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
551 /// reference to _fltused on Windows, which will link in MSVCRT's
552 /// floating-point support.
553 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
554                                       MachineModuleInfo *MMI)
555 {
556   FunctionType *FT = cast<FunctionType>(
557     I.getCalledValue()->getType()->getContainedType(0));
558   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
559     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
560       Type* T = I.getArgOperand(i)->getType();
561       for (auto i : post_order(T)) {
562         if (i->isFloatingPointTy()) {
563           MMI->setUsesVAFloatArgument(true);
564           return;
565         }
566       }
567     }
568   }
569 }
570
571 /// AddLandingPadInfo - Extract the exception handling information from the
572 /// landingpad instruction and add them to the specified machine module info.
573 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
574                              MachineBasicBlock *MBB) {
575   if (const auto *PF = dyn_cast<Function>(
576       I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
577     MMI.addPersonality(PF);
578
579   if (I.isCleanup())
580     MMI.addCleanup(MBB);
581
582   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
583   //        but we need to do it this way because of how the DWARF EH emitter
584   //        processes the clauses.
585   for (unsigned i = I.getNumClauses(); i != 0; --i) {
586     Value *Val = I.getClause(i - 1);
587     if (I.isCatch(i - 1)) {
588       MMI.addCatchTypeInfo(MBB,
589                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
590     } else {
591       // Add filters in a list.
592       Constant *CVal = cast<Constant>(Val);
593       SmallVector<const GlobalValue*, 4> FilterList;
594       for (User::op_iterator
595              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
596         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
597
598       MMI.addFilterTypeInfo(MBB, FilterList);
599     }
600   }
601 }