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