CodeGen: Stop using DIDescriptor::is*() and auto-casting
[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 namespace {
84 struct WinEHNumbering {
85   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
86
87   WinEHFuncInfo &FuncInfo;
88   int NextState;
89
90   SmallVector<ActionHandler *, 4> HandlerStack;
91   SmallPtrSet<const Function *, 4> VisitedHandlers;
92
93   int currentEHNumber() const {
94     return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
95   }
96
97   void createUnwindMapEntry(int ToState, ActionHandler *AH);
98   void createTryBlockMapEntry(int TryLow, int TryHigh,
99                               ArrayRef<CatchHandler *> Handlers);
100   void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
101   void calculateStateNumbers(const Function &F);
102 };
103 }
104
105 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
106                                SelectionDAG *DAG) {
107   Fn = &fn;
108   MF = &mf;
109   TLI = MF->getSubtarget().getTargetLowering();
110   RegInfo = &MF->getRegInfo();
111   MachineModuleInfo &MMI = MF->getMMI();
112
113   // Check whether the function can return without sret-demotion.
114   SmallVector<ISD::OutputArg, 4> Outs;
115   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
116   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
117                                        Fn->isVarArg(), Outs, Fn->getContext());
118
119   // Initialize the mapping of values to registers.  This is only set up for
120   // instruction values that are used outside of the block that defines
121   // them.
122   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
123   for (; BB != EB; ++BB)
124     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
125          I != E; ++I) {
126       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
127         // Static allocas can be folded into the initial stack frame adjustment.
128         if (AI->isStaticAlloca()) {
129           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
130           Type *Ty = AI->getAllocatedType();
131           uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
132           unsigned Align =
133               std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
134                        AI->getAlignment());
135
136           TySize *= CUI->getZExtValue();   // Get total allocated size.
137           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
138
139           StaticAllocaMap[AI] =
140             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
141
142         } else {
143           unsigned Align = std::max(
144               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
145                 AI->getAllocatedType()),
146               AI->getAlignment());
147           unsigned StackAlign =
148               MF->getSubtarget().getFrameLowering()->getStackAlignment();
149           if (Align <= StackAlign)
150             Align = 0;
151           // Inform the Frame Information that we have variable-sized objects.
152           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
153         }
154       }
155
156       // Look for inline asm that clobbers the SP register.
157       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
158         ImmutableCallSite CS(I);
159         if (isa<InlineAsm>(CS.getCalledValue())) {
160           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
161           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
162           std::vector<TargetLowering::AsmOperandInfo> Ops =
163               TLI->ParseConstraints(TRI, CS);
164           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
165             TargetLowering::AsmOperandInfo &Op = Ops[I];
166             if (Op.Type == InlineAsm::isClobber) {
167               // Clobbers don't have SDValue operands, hence SDValue().
168               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
169               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
170                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
171                                                     Op.ConstraintVT);
172               if (PhysReg.first == SP)
173                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
174             }
175           }
176         }
177       }
178
179       // Look for calls to the @llvm.va_start intrinsic. We can omit some
180       // prologue boilerplate for variadic functions that don't examine their
181       // arguments.
182       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
183         if (II->getIntrinsicID() == Intrinsic::vastart)
184           MF->getFrameInfo()->setHasVAStart(true);
185       }
186
187       // If we have a musttail call in a variadic funciton, we need to ensure we
188       // forward implicit register parameters.
189       if (const auto *CI = dyn_cast<CallInst>(I)) {
190         if (CI->isMustTailCall() && Fn->isVarArg())
191           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
192       }
193
194       // Mark values used outside their block as exported, by allocating
195       // a virtual register for them.
196       if (isUsedOutsideOfDefiningBlock(I))
197         if (!isa<AllocaInst>(I) ||
198             !StaticAllocaMap.count(cast<AllocaInst>(I)))
199           InitializeRegForValue(I);
200
201       // Collect llvm.dbg.declare information. This is done now instead of
202       // during the initial isel pass through the IR so that it is done
203       // in a predictable order.
204       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
205         DIVariable DIVar = DI->getVariable();
206         if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
207           // Don't handle byval struct arguments or VLAs, for example.
208           // Non-byval arguments are handled here (they refer to the stack
209           // temporary alloca at this point).
210           const Value *Address = DI->getAddress();
211           if (Address) {
212             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
213               Address = BCI->getOperand(0);
214             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
215               DenseMap<const AllocaInst *, int>::iterator SI =
216                 StaticAllocaMap.find(AI);
217               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
218                 int FI = SI->second;
219                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
220                                        FI, DI->getDebugLoc());
221               }
222             }
223           }
224         }
225       }
226
227       // Decide the preferred extend type for a value.
228       PreferredExtendType[I] = getPreferredExtendForValue(I);
229     }
230
231   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
232   // also creates the initial PHI MachineInstrs, though none of the input
233   // operands are populated.
234   for (BB = Fn->begin(); BB != EB; ++BB) {
235     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
236     MBBMap[BB] = MBB;
237     MF->push_back(MBB);
238
239     // Transfer the address-taken flag. This is necessary because there could
240     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
241     // the first one should be marked.
242     if (BB->hasAddressTaken())
243       MBB->setHasAddressTaken();
244
245     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
246     // appropriate.
247     for (BasicBlock::const_iterator I = BB->begin();
248          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
249       if (PN->use_empty()) continue;
250
251       // Skip empty types
252       if (PN->getType()->isEmptyTy())
253         continue;
254
255       DebugLoc DL = PN->getDebugLoc();
256       unsigned PHIReg = ValueMap[PN];
257       assert(PHIReg && "PHI node does not have an assigned virtual register!");
258
259       SmallVector<EVT, 4> ValueVTs;
260       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
261       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
262         EVT VT = ValueVTs[vti];
263         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
264         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
265         for (unsigned i = 0; i != NumRegisters; ++i)
266           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
267         PHIReg += NumRegisters;
268       }
269     }
270   }
271
272   // Mark landing pad blocks.
273   for (BB = Fn->begin(); BB != EB; ++BB)
274     if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
275       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
276
277   // Calculate EH numbers for WinEH.
278   if (fn.getFnAttribute("wineh-parent").getValueAsString() == fn.getName()) {
279     WinEHNumbering Num(MMI.getWinEHFuncInfo(&fn));
280     Num.calculateStateNumbers(fn);
281     // Pop everything on the handler stack.
282     Num.processCallSite(None, ImmutableCallSite());
283   }
284 }
285
286 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
287   WinEHUnwindMapEntry UME;
288   UME.ToState = ToState;
289   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
290     UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
291   else
292     UME.Cleanup = nullptr;
293   FuncInfo.UnwindMap.push_back(UME);
294 }
295
296 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
297                                             ArrayRef<CatchHandler *> Handlers) {
298   WinEHTryBlockMapEntry TBME;
299   TBME.TryLow = TryLow;
300   TBME.TryHigh = TryHigh;
301   assert(TBME.TryLow <= TBME.TryHigh);
302   for (CatchHandler *CH : Handlers) {
303     WinEHHandlerType HT;
304     if (CH->getSelector()->isNullValue()) {
305       HT.Adjectives = 0x40;
306       HT.TypeDescriptor = nullptr;
307     } else {
308       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
309       // Selectors are always pointers to GlobalVariables with 'struct' type.
310       // The struct has two fields, adjectives and a type descriptor.
311       auto *CS = cast<ConstantStruct>(GV->getInitializer());
312       HT.Adjectives =
313           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
314       HT.TypeDescriptor =
315           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
316     }
317     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
318     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
319     TBME.HandlerArray.push_back(HT);
320   }
321   FuncInfo.TryBlockMap.push_back(TBME);
322 }
323
324 static void print_name(const Value *V) {
325 #ifndef NDEBUG
326   if (!V) {
327     DEBUG(dbgs() << "null");
328     return;
329   }
330
331   if (const auto *F = dyn_cast<Function>(V))
332     DEBUG(dbgs() << F->getName());
333   else
334     DEBUG(V->dump());
335 #endif
336 }
337
338 void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
339                                      ImmutableCallSite CS) {
340   int FirstMismatch = 0;
341   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
342        ++FirstMismatch) {
343     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
344         Actions[FirstMismatch]->getHandlerBlockOrFunc())
345       break;
346     delete Actions[FirstMismatch];
347   }
348
349   bool EnteringScope = (int)Actions.size() > FirstMismatch;
350
351   // Don't recurse while we are looping over the handler stack.  Instead, defer
352   // the numbering of the catch handlers until we are done popping.
353   SmallVector<CatchHandler *, 4> PoppedCatches;
354   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
355     if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
356       PoppedCatches.push_back(CH);
357     } else {
358       // Delete cleanup handlers
359       delete HandlerStack.back();
360     }
361     HandlerStack.pop_back();
362   }
363
364   // We need to create a new state number if we are exiting a try scope and we
365   // will not push any more actions.
366   int TryHigh = NextState - 1;
367   if (!EnteringScope && !PoppedCatches.empty()) {
368     createUnwindMapEntry(currentEHNumber(), nullptr);
369     ++NextState;
370   }
371
372   int LastTryLowIdx = 0;
373   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
374     CatchHandler *CH = PoppedCatches[I];
375     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
376       int TryLow = CH->getEHState();
377       auto Handlers =
378           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
379       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
380       LastTryLowIdx = I + 1;
381     }
382   }
383
384   for (CatchHandler *CH : PoppedCatches) {
385     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
386       calculateStateNumbers(*F);
387     delete CH;
388   }
389
390   bool LastActionWasCatch = false;
391   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
392     // We can reuse eh states when pushing two catches for the same invoke.
393     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
394     // FIXME: Reenable this optimization!
395     if (CurrActionIsCatch && LastActionWasCatch && false) {
396       Actions[I]->setEHState(currentEHNumber());
397     } else {
398       createUnwindMapEntry(currentEHNumber(), Actions[I]);
399       Actions[I]->setEHState(NextState);
400       NextState++;
401       DEBUG(dbgs() << "Creating unwind map entry for: (");
402       print_name(Actions[I]->getHandlerBlockOrFunc());
403       DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
404     }
405     HandlerStack.push_back(Actions[I]);
406     LastActionWasCatch = CurrActionIsCatch;
407   }
408
409   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
410   print_name(CS ? CS.getCalledValue() : nullptr);
411   DEBUG(dbgs() << '\n');
412 }
413
414 void WinEHNumbering::calculateStateNumbers(const Function &F) {
415   auto I = VisitedHandlers.insert(&F);
416   if (!I.second)
417     return; // We've already visited this handler, don't renumber it.
418
419   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
420   SmallVector<ActionHandler *, 4> ActionList;
421   for (const BasicBlock &BB : F) {
422     for (const Instruction &I : BB) {
423       const auto *CI = dyn_cast<CallInst>(&I);
424       if (!CI || CI->doesNotThrow())
425         continue;
426       processCallSite(None, CI);
427     }
428     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
429     if (!II)
430       continue;
431     const LandingPadInst *LPI = II->getLandingPadInst();
432     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
433     if (!ActionsCall)
434       continue;
435     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
436     parseEHActions(ActionsCall, ActionList);
437     processCallSite(ActionList, II);
438     ActionList.clear();
439     FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
440   }
441
442   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
443 }
444
445 /// clear - Clear out all the function-specific state. This returns this
446 /// FunctionLoweringInfo to an empty state, ready to be used for a
447 /// different function.
448 void FunctionLoweringInfo::clear() {
449   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
450          "Not all catch info was assigned to a landing pad!");
451
452   MBBMap.clear();
453   ValueMap.clear();
454   StaticAllocaMap.clear();
455 #ifndef NDEBUG
456   CatchInfoLost.clear();
457   CatchInfoFound.clear();
458 #endif
459   LiveOutRegInfo.clear();
460   VisitedBBs.clear();
461   ArgDbgValues.clear();
462   ByValArgFrameIndexMap.clear();
463   RegFixups.clear();
464   StatepointStackSlots.clear();
465   PreferredExtendType.clear();
466 }
467
468 /// CreateReg - Allocate a single virtual register for the given type.
469 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
470   return RegInfo->createVirtualRegister(
471       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
472 }
473
474 /// CreateRegs - Allocate the appropriate number of virtual registers of
475 /// the correctly promoted or expanded types.  Assign these registers
476 /// consecutive vreg numbers and return the first assigned number.
477 ///
478 /// In the case that the given value has struct or array type, this function
479 /// will assign registers for each member or element.
480 ///
481 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
482   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
483
484   SmallVector<EVT, 4> ValueVTs;
485   ComputeValueVTs(*TLI, Ty, ValueVTs);
486
487   unsigned FirstReg = 0;
488   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
489     EVT ValueVT = ValueVTs[Value];
490     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
491
492     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
493     for (unsigned i = 0; i != NumRegs; ++i) {
494       unsigned R = CreateReg(RegisterVT);
495       if (!FirstReg) FirstReg = R;
496     }
497   }
498   return FirstReg;
499 }
500
501 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
502 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
503 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
504 /// the larger bit width by zero extension. The bit width must be no smaller
505 /// than the LiveOutInfo's existing bit width.
506 const FunctionLoweringInfo::LiveOutInfo *
507 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
508   if (!LiveOutRegInfo.inBounds(Reg))
509     return nullptr;
510
511   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
512   if (!LOI->IsValid)
513     return nullptr;
514
515   if (BitWidth > LOI->KnownZero.getBitWidth()) {
516     LOI->NumSignBits = 1;
517     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
518     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
519   }
520
521   return LOI;
522 }
523
524 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
525 /// register based on the LiveOutInfo of its operands.
526 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
527   Type *Ty = PN->getType();
528   if (!Ty->isIntegerTy() || Ty->isVectorTy())
529     return;
530
531   SmallVector<EVT, 1> ValueVTs;
532   ComputeValueVTs(*TLI, Ty, ValueVTs);
533   assert(ValueVTs.size() == 1 &&
534          "PHIs with non-vector integer types should have a single VT.");
535   EVT IntVT = ValueVTs[0];
536
537   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
538     return;
539   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
540   unsigned BitWidth = IntVT.getSizeInBits();
541
542   unsigned DestReg = ValueMap[PN];
543   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
544     return;
545   LiveOutRegInfo.grow(DestReg);
546   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
547
548   Value *V = PN->getIncomingValue(0);
549   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
550     DestLOI.NumSignBits = 1;
551     APInt Zero(BitWidth, 0);
552     DestLOI.KnownZero = Zero;
553     DestLOI.KnownOne = Zero;
554     return;
555   }
556
557   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
558     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
559     DestLOI.NumSignBits = Val.getNumSignBits();
560     DestLOI.KnownZero = ~Val;
561     DestLOI.KnownOne = Val;
562   } else {
563     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
564                                 "CopyToReg node was created.");
565     unsigned SrcReg = ValueMap[V];
566     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
567       DestLOI.IsValid = false;
568       return;
569     }
570     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
571     if (!SrcLOI) {
572       DestLOI.IsValid = false;
573       return;
574     }
575     DestLOI = *SrcLOI;
576   }
577
578   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
579          DestLOI.KnownOne.getBitWidth() == BitWidth &&
580          "Masks should have the same bit width as the type.");
581
582   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
583     Value *V = PN->getIncomingValue(i);
584     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
585       DestLOI.NumSignBits = 1;
586       APInt Zero(BitWidth, 0);
587       DestLOI.KnownZero = Zero;
588       DestLOI.KnownOne = Zero;
589       return;
590     }
591
592     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
593       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
594       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
595       DestLOI.KnownZero &= ~Val;
596       DestLOI.KnownOne &= Val;
597       continue;
598     }
599
600     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
601                                 "its CopyToReg node was created.");
602     unsigned SrcReg = ValueMap[V];
603     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
604       DestLOI.IsValid = false;
605       return;
606     }
607     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
608     if (!SrcLOI) {
609       DestLOI.IsValid = false;
610       return;
611     }
612     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
613     DestLOI.KnownZero &= SrcLOI->KnownZero;
614     DestLOI.KnownOne &= SrcLOI->KnownOne;
615   }
616 }
617
618 /// setArgumentFrameIndex - Record frame index for the byval
619 /// argument. This overrides previous frame index entry for this argument,
620 /// if any.
621 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
622                                                  int FI) {
623   ByValArgFrameIndexMap[A] = FI;
624 }
625
626 /// getArgumentFrameIndex - Get frame index for the byval argument.
627 /// If the argument does not have any assigned frame index then 0 is
628 /// returned.
629 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
630   DenseMap<const Argument *, int>::iterator I =
631     ByValArgFrameIndexMap.find(A);
632   if (I != ByValArgFrameIndexMap.end())
633     return I->second;
634   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
635   return 0;
636 }
637
638 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
639 /// being passed to this variadic function, and set the MachineModuleInfo's
640 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
641 /// reference to _fltused on Windows, which will link in MSVCRT's
642 /// floating-point support.
643 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
644                                       MachineModuleInfo *MMI)
645 {
646   FunctionType *FT = cast<FunctionType>(
647     I.getCalledValue()->getType()->getContainedType(0));
648   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
649     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
650       Type* T = I.getArgOperand(i)->getType();
651       for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
652            i != e; ++i) {
653         if (i->isFloatingPointTy()) {
654           MMI->setUsesVAFloatArgument(true);
655           return;
656         }
657       }
658     }
659   }
660 }
661
662 /// AddLandingPadInfo - Extract the exception handling information from the
663 /// landingpad instruction and add them to the specified machine module info.
664 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
665                              MachineBasicBlock *MBB) {
666   MMI.addPersonality(MBB,
667                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
668
669   if (I.isCleanup())
670     MMI.addCleanup(MBB);
671
672   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
673   //        but we need to do it this way because of how the DWARF EH emitter
674   //        processes the clauses.
675   for (unsigned i = I.getNumClauses(); i != 0; --i) {
676     Value *Val = I.getClause(i - 1);
677     if (I.isCatch(i - 1)) {
678       MMI.addCatchTypeInfo(MBB,
679                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
680     } else {
681       // Add filters in a list.
682       Constant *CVal = cast<Constant>(Val);
683       SmallVector<const GlobalValue*, 4> FilterList;
684       for (User::op_iterator
685              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
686         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
687
688       MMI.addFilterTypeInfo(MBB, FilterList);
689     }
690   }
691 }