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