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