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