LLVM  mainline
FunctionLoweringInfo.cpp
Go to the documentation of this file.
00001 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements routines for translating functions from LLVM IR into
00011 // Machine IR.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00016 #include "llvm/ADT/PostOrderIterator.h"
00017 #include "llvm/CodeGen/Analysis.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineModuleInfo.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/WinEHFuncInfo.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/DebugInfo.h"
00026 #include "llvm/IR/DerivedTypes.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/LLVMContext.h"
00031 #include "llvm/IR/Module.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/MathExtras.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetFrameLowering.h"
00037 #include "llvm/Target/TargetInstrInfo.h"
00038 #include "llvm/Target/TargetLowering.h"
00039 #include "llvm/Target/TargetOptions.h"
00040 #include "llvm/Target/TargetRegisterInfo.h"
00041 #include "llvm/Target/TargetSubtargetInfo.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 #define DEBUG_TYPE "function-lowering-info"
00046 
00047 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
00048 /// PHI nodes or outside of the basic block that defines it, or used by a
00049 /// switch or atomic instruction, which may expand to multiple basic blocks.
00050 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
00051   if (I->use_empty()) return false;
00052   if (isa<PHINode>(I)) return true;
00053   const BasicBlock *BB = I->getParent();
00054   for (const User *U : I->users())
00055     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
00056       return true;
00057 
00058   return false;
00059 }
00060 
00061 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
00062   // For the users of the source value being used for compare instruction, if
00063   // the number of signed predicate is greater than unsigned predicate, we
00064   // prefer to use SIGN_EXTEND.
00065   //
00066   // With this optimization, we would be able to reduce some redundant sign or
00067   // zero extension instruction, and eventually more machine CSE opportunities
00068   // can be exposed.
00069   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
00070   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
00071   for (const User *U : V->users()) {
00072     if (const auto *CI = dyn_cast<CmpInst>(U)) {
00073       NumOfSigned += CI->isSigned();
00074       NumOfUnsigned += CI->isUnsigned();
00075     }
00076   }
00077   if (NumOfSigned > NumOfUnsigned)
00078     ExtendKind = ISD::SIGN_EXTEND;
00079 
00080   return ExtendKind;
00081 }
00082 
00083 namespace {
00084 struct WinEHNumbering {
00085   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
00086       CurrentBaseState(-1), NextState(0) {}
00087 
00088   WinEHFuncInfo &FuncInfo;
00089   int CurrentBaseState;
00090   int NextState;
00091 
00092   SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
00093   SmallPtrSet<const Function *, 4> VisitedHandlers;
00094 
00095   int currentEHNumber() const {
00096     return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
00097   }
00098 
00099   void createUnwindMapEntry(int ToState, ActionHandler *AH);
00100   void createTryBlockMapEntry(int TryLow, int TryHigh,
00101                               ArrayRef<CatchHandler *> Handlers);
00102   void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
00103                        ImmutableCallSite CS);
00104   void popUnmatchedActions(int FirstMismatch);
00105   void calculateStateNumbers(const Function &F);
00106   void findActionRootLPads(const Function &F);
00107 };
00108 }
00109 
00110 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
00111                                SelectionDAG *DAG) {
00112   Fn = &fn;
00113   MF = &mf;
00114   TLI = MF->getSubtarget().getTargetLowering();
00115   RegInfo = &MF->getRegInfo();
00116   MachineModuleInfo &MMI = MF->getMMI();
00117 
00118   // Check whether the function can return without sret-demotion.
00119   SmallVector<ISD::OutputArg, 4> Outs;
00120   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
00121   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
00122                                        Fn->isVarArg(), Outs, Fn->getContext());
00123 
00124   // Initialize the mapping of values to registers.  This is only set up for
00125   // instruction values that are used outside of the block that defines
00126   // them.
00127   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
00128   for (; BB != EB; ++BB)
00129     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
00130          I != E; ++I) {
00131       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00132         // Static allocas can be folded into the initial stack frame adjustment.
00133         if (AI->isStaticAlloca()) {
00134           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
00135           Type *Ty = AI->getAllocatedType();
00136           uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
00137           unsigned Align =
00138               std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
00139                        AI->getAlignment());
00140 
00141           TySize *= CUI->getZExtValue();   // Get total allocated size.
00142           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
00143 
00144           StaticAllocaMap[AI] =
00145             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
00146 
00147         } else {
00148           unsigned Align = std::max(
00149               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
00150                 AI->getAllocatedType()),
00151               AI->getAlignment());
00152           unsigned StackAlign =
00153               MF->getSubtarget().getFrameLowering()->getStackAlignment();
00154           if (Align <= StackAlign)
00155             Align = 0;
00156           // Inform the Frame Information that we have variable-sized objects.
00157           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
00158         }
00159       }
00160 
00161       // Look for inline asm that clobbers the SP register.
00162       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00163         ImmutableCallSite CS(I);
00164         if (isa<InlineAsm>(CS.getCalledValue())) {
00165           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
00166           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00167           std::vector<TargetLowering::AsmOperandInfo> Ops =
00168               TLI->ParseConstraints(TRI, CS);
00169           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
00170             TargetLowering::AsmOperandInfo &Op = Ops[I];
00171             if (Op.Type == InlineAsm::isClobber) {
00172               // Clobbers don't have SDValue operands, hence SDValue().
00173               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
00174               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
00175                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
00176                                                     Op.ConstraintVT);
00177               if (PhysReg.first == SP)
00178                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
00179             }
00180           }
00181         }
00182       }
00183 
00184       // Look for calls to the @llvm.va_start intrinsic. We can omit some
00185       // prologue boilerplate for variadic functions that don't examine their
00186       // arguments.
00187       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
00188         if (II->getIntrinsicID() == Intrinsic::vastart)
00189           MF->getFrameInfo()->setHasVAStart(true);
00190       }
00191 
00192       // If we have a musttail call in a variadic funciton, we need to ensure we
00193       // forward implicit register parameters.
00194       if (const auto *CI = dyn_cast<CallInst>(I)) {
00195         if (CI->isMustTailCall() && Fn->isVarArg())
00196           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
00197       }
00198 
00199       // Mark values used outside their block as exported, by allocating
00200       // a virtual register for them.
00201       if (isUsedOutsideOfDefiningBlock(I))
00202         if (!isa<AllocaInst>(I) ||
00203             !StaticAllocaMap.count(cast<AllocaInst>(I)))
00204           InitializeRegForValue(I);
00205 
00206       // Collect llvm.dbg.declare information. This is done now instead of
00207       // during the initial isel pass through the IR so that it is done
00208       // in a predictable order.
00209       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
00210         assert(DI->getVariable() && "Missing variable");
00211         assert(DI->getDebugLoc() && "Missing location");
00212         if (MMI.hasDebugInfo()) {
00213           // Don't handle byval struct arguments or VLAs, for example.
00214           // Non-byval arguments are handled here (they refer to the stack
00215           // temporary alloca at this point).
00216           const Value *Address = DI->getAddress();
00217           if (Address) {
00218             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
00219               Address = BCI->getOperand(0);
00220             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
00221               DenseMap<const AllocaInst *, int>::iterator SI =
00222                 StaticAllocaMap.find(AI);
00223               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
00224                 int FI = SI->second;
00225                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
00226                                        FI, DI->getDebugLoc());
00227               }
00228             }
00229           }
00230         }
00231       }
00232 
00233       // Decide the preferred extend type for a value.
00234       PreferredExtendType[I] = getPreferredExtendForValue(I);
00235     }
00236 
00237   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
00238   // also creates the initial PHI MachineInstrs, though none of the input
00239   // operands are populated.
00240   for (BB = Fn->begin(); BB != EB; ++BB) {
00241     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
00242     MBBMap[BB] = MBB;
00243     MF->push_back(MBB);
00244 
00245     // Transfer the address-taken flag. This is necessary because there could
00246     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
00247     // the first one should be marked.
00248     if (BB->hasAddressTaken())
00249       MBB->setHasAddressTaken();
00250 
00251     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
00252     // appropriate.
00253     for (BasicBlock::const_iterator I = BB->begin();
00254          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00255       if (PN->use_empty()) continue;
00256 
00257       // Skip empty types
00258       if (PN->getType()->isEmptyTy())
00259         continue;
00260 
00261       DebugLoc DL = PN->getDebugLoc();
00262       unsigned PHIReg = ValueMap[PN];
00263       assert(PHIReg && "PHI node does not have an assigned virtual register!");
00264 
00265       SmallVector<EVT, 4> ValueVTs;
00266       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
00267       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
00268         EVT VT = ValueVTs[vti];
00269         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
00270         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00271         for (unsigned i = 0; i != NumRegisters; ++i)
00272           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
00273         PHIReg += NumRegisters;
00274       }
00275     }
00276   }
00277 
00278   // Mark landing pad blocks.
00279   SmallVector<const LandingPadInst *, 4> LPads;
00280   for (BB = Fn->begin(); BB != EB; ++BB) {
00281     if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
00282       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
00283     if (BB->isLandingPad())
00284       LPads.push_back(BB->getLandingPadInst());
00285   }
00286 
00287   // If this is an MSVC EH personality, we need to do a bit more work.
00288   EHPersonality Personality = EHPersonality::Unknown;
00289   if (!LPads.empty())
00290     Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
00291   if (!isMSVCEHPersonality(Personality))
00292     return;
00293 
00294   WinEHFuncInfo *EHInfo = nullptr;
00295   if (Personality == EHPersonality::MSVC_Win64SEH) {
00296     addSEHHandlersForLPads(LPads);
00297   } else if (Personality == EHPersonality::MSVC_CXX) {
00298     const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
00299     EHInfo = &MMI.getWinEHFuncInfo(WinEHParentFn);
00300     if (EHInfo->LandingPadStateMap.empty()) {
00301       WinEHNumbering Num(*EHInfo);
00302       Num.findActionRootLPads(*WinEHParentFn);
00303       // The VisitedHandlers list is used by both findActionRootLPads and
00304       // calculateStateNumbers, but both functions need to visit all handlers.
00305       Num.VisitedHandlers.clear();
00306       Num.calculateStateNumbers(*WinEHParentFn);
00307       // Pop everything on the handler stack.
00308       // It may be necessary to call this more than once because a handler can
00309       // be pushed on the stack as a result of clearing the stack.
00310       while (!Num.HandlerStack.empty())
00311         Num.processCallSite(None, ImmutableCallSite());
00312     }
00313 
00314     // Copy the state numbers to LandingPadInfo for the current function, which
00315     // could be a handler or the parent.
00316     for (const LandingPadInst *LP : LPads) {
00317       MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
00318       MMI.addWinEHState(LPadMBB, EHInfo->LandingPadStateMap[LP]);
00319     }
00320   }
00321 }
00322 
00323 void FunctionLoweringInfo::addSEHHandlersForLPads(
00324     ArrayRef<const LandingPadInst *> LPads) {
00325   MachineModuleInfo &MMI = MF->getMMI();
00326 
00327   // Iterate over all landing pads with llvm.eh.actions calls.
00328   for (const LandingPadInst *LP : LPads) {
00329     const IntrinsicInst *ActionsCall =
00330         dyn_cast<IntrinsicInst>(LP->getNextNode());
00331     if (!ActionsCall ||
00332         ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
00333       continue;
00334 
00335     // Parse the llvm.eh.actions call we found.
00336     MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
00337     SmallVector<std::unique_ptr<ActionHandler>, 4> Actions;
00338     parseEHActions(ActionsCall, Actions);
00339 
00340     // Iterate EH actions from most to least precedence, which means
00341     // iterating in reverse.
00342     for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
00343       ActionHandler *Action = I->get();
00344       if (auto *CH = dyn_cast<CatchHandler>(Action)) {
00345         const auto *Filter =
00346             dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
00347         assert((Filter || CH->getSelector()->isNullValue()) &&
00348                "expected function or catch-all");
00349         const auto *RecoverBA =
00350             cast<BlockAddress>(CH->getHandlerBlockOrFunc());
00351         MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
00352       } else {
00353         assert(isa<CleanupHandler>(Action));
00354         const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
00355         MMI.addSEHCleanupHandler(LPadMBB, Fini);
00356       }
00357     }
00358   }
00359 }
00360 
00361 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
00362   WinEHUnwindMapEntry UME;
00363   UME.ToState = ToState;
00364   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
00365     UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
00366   else
00367     UME.Cleanup = nullptr;
00368   FuncInfo.UnwindMap.push_back(UME);
00369 }
00370 
00371 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
00372                                             ArrayRef<CatchHandler *> Handlers) {
00373   // See if we already have an entry for this set of handlers.
00374   // This is using iterators rather than a range-based for loop because
00375   // if we find the entry we're looking for we'll need the iterator to erase it.
00376   int NumHandlers = Handlers.size();
00377   auto I = FuncInfo.TryBlockMap.begin();
00378   auto E = FuncInfo.TryBlockMap.end();
00379   for ( ; I != E; ++I) {
00380     auto &Entry = *I;
00381     if (Entry.HandlerArray.size() != (size_t)NumHandlers)
00382       continue;
00383     int N;
00384     for (N = 0; N < NumHandlers; ++N) {
00385       if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
00386         break; // breaks out of inner loop
00387     }
00388     // If all the handlers match, this is what we were looking for.
00389     if (N == NumHandlers) {
00390       break;
00391     }
00392   }
00393 
00394   // If we found an existing entry for this set of handlers, extend the range
00395   // but move the entry to the end of the map vector.  The order of entries
00396   // in the map is critical to the way that the runtime finds handlers.
00397   // FIXME: Depending on what has happened with block ordering, this may
00398   //        incorrectly combine entries that should remain separate.
00399   if (I != E) {
00400     // Copy the existing entry.
00401     WinEHTryBlockMapEntry Entry = *I;
00402     Entry.TryLow = std::min(TryLow, Entry.TryLow);
00403     Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
00404     assert(Entry.TryLow <= Entry.TryHigh);
00405     // Erase the old entry and add this one to the back.
00406     FuncInfo.TryBlockMap.erase(I);
00407     FuncInfo.TryBlockMap.push_back(Entry);
00408     return;
00409   }
00410 
00411   // If we didn't find an entry, create a new one.
00412   WinEHTryBlockMapEntry TBME;
00413   TBME.TryLow = TryLow;
00414   TBME.TryHigh = TryHigh;
00415   assert(TBME.TryLow <= TBME.TryHigh);
00416   for (CatchHandler *CH : Handlers) {
00417     WinEHHandlerType HT;
00418     if (CH->getSelector()->isNullValue()) {
00419       HT.Adjectives = 0x40;
00420       HT.TypeDescriptor = nullptr;
00421     } else {
00422       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
00423       // Selectors are always pointers to GlobalVariables with 'struct' type.
00424       // The struct has two fields, adjectives and a type descriptor.
00425       auto *CS = cast<ConstantStruct>(GV->getInitializer());
00426       HT.Adjectives =
00427           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
00428       HT.TypeDescriptor =
00429           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
00430     }
00431     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
00432     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
00433     TBME.HandlerArray.push_back(HT);
00434   }
00435   FuncInfo.TryBlockMap.push_back(TBME);
00436 }
00437 
00438 static void print_name(const Value *V) {
00439 #ifndef NDEBUG
00440   if (!V) {
00441     DEBUG(dbgs() << "null");
00442     return;
00443   }
00444 
00445   if (const auto *F = dyn_cast<Function>(V))
00446     DEBUG(dbgs() << F->getName());
00447   else
00448     DEBUG(V->dump());
00449 #endif
00450 }
00451 
00452 void WinEHNumbering::processCallSite(
00453     MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
00454     ImmutableCallSite CS) {
00455   DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
00456                << ") for: ");
00457   print_name(CS ? CS.getCalledValue() : nullptr);
00458   DEBUG(dbgs() << '\n');
00459 
00460   DEBUG(dbgs() << "HandlerStack: \n");
00461   for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
00462     DEBUG(dbgs() << "  ");
00463     print_name(HandlerStack[I]->getHandlerBlockOrFunc());
00464     DEBUG(dbgs() << '\n');
00465   }
00466   DEBUG(dbgs() << "Actions: \n");
00467   for (int I = 0, E = Actions.size(); I < E; ++I) {
00468     DEBUG(dbgs() << "  ");
00469     print_name(Actions[I]->getHandlerBlockOrFunc());
00470     DEBUG(dbgs() << '\n');
00471   }
00472   int FirstMismatch = 0;
00473   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
00474        ++FirstMismatch) {
00475     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
00476         Actions[FirstMismatch]->getHandlerBlockOrFunc())
00477       break;
00478   }
00479 
00480   // Remove unmatched actions from the stack and process their EH states.
00481   popUnmatchedActions(FirstMismatch);
00482 
00483   DEBUG(dbgs() << "Pushing actions for CallSite: ");
00484   print_name(CS ? CS.getCalledValue() : nullptr);
00485   DEBUG(dbgs() << '\n');
00486 
00487   bool LastActionWasCatch = false;
00488   const LandingPadInst *LastRootLPad = nullptr;
00489   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
00490     // We can reuse eh states when pushing two catches for the same invoke.
00491     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
00492     auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
00493     // Various conditions can lead to a handler being popped from the
00494     // stack and re-pushed later.  That shouldn't create a new state.
00495     // FIXME: Can code optimization lead to re-used handlers?
00496     if (FuncInfo.HandlerEnclosedState.count(Handler)) {
00497       // If we already assigned the state enclosed by this handler re-use it.
00498       Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
00499       continue;
00500     }
00501     const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
00502     if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
00503       DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
00504       Actions[I]->setEHState(currentEHNumber());
00505     } else {
00506       DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
00507       print_name(Actions[I]->getHandlerBlockOrFunc());
00508       DEBUG(dbgs() << ") with EH state " << NextState << "\n");
00509       createUnwindMapEntry(currentEHNumber(), Actions[I].get());
00510       DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
00511       Actions[I]->setEHState(NextState);
00512       NextState++;
00513     }
00514     HandlerStack.push_back(std::move(Actions[I]));
00515     LastActionWasCatch = CurrActionIsCatch;
00516     LastRootLPad = RootLPad;
00517   }
00518 
00519   // This is used to defer numbering states for a handler until after the
00520   // last time it appears in an invoke action list.
00521   if (CS.isInvoke()) {
00522     for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
00523       auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
00524       if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
00525         continue;
00526       FuncInfo.LastInvokeVisited[Handler] = true;
00527       DEBUG(dbgs() << "Last invoke of ");
00528       print_name(Handler);
00529       DEBUG(dbgs() << " has been visited.\n");
00530     }
00531   }
00532 
00533   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
00534   print_name(CS ? CS.getCalledValue() : nullptr);
00535   DEBUG(dbgs() << '\n');
00536 }
00537 
00538 void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
00539   // Don't recurse while we are looping over the handler stack.  Instead, defer
00540   // the numbering of the catch handlers until we are done popping.
00541   SmallVector<CatchHandler *, 4> PoppedCatches;
00542   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
00543     std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
00544     if (isa<CatchHandler>(Handler.get()))
00545       PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
00546   }
00547 
00548   int TryHigh = NextState - 1;
00549   int LastTryLowIdx = 0;
00550   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
00551     CatchHandler *CH = PoppedCatches[I];
00552     DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
00553     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
00554       int TryLow = CH->getEHState();
00555       auto Handlers =
00556           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
00557       DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
00558       for (size_t J = 0; J < Handlers.size(); ++J) {
00559         DEBUG(dbgs() << ", ");
00560         print_name(Handlers[J]->getHandlerBlockOrFunc());
00561       }
00562       DEBUG(dbgs() << ")\n");
00563       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
00564       LastTryLowIdx = I + 1;
00565     }
00566   }
00567 
00568   for (CatchHandler *CH : PoppedCatches) {
00569     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
00570       if (FuncInfo.LastInvokeVisited[F]) {
00571         DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
00572         print_name(F);
00573         DEBUG(dbgs() << '\n');
00574         FuncInfo.HandlerBaseState[F] = NextState;
00575         DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() 
00576                      << ", null)\n");
00577         createUnwindMapEntry(currentEHNumber(), nullptr);
00578         ++NextState;
00579         calculateStateNumbers(*F);
00580       }
00581       else {
00582         DEBUG(dbgs() << "Deferring handling of ");
00583         print_name(F);
00584         DEBUG(dbgs() << " until last invoke visited.\n");
00585       }
00586     }
00587     delete CH;
00588   }
00589 }
00590 
00591 void WinEHNumbering::calculateStateNumbers(const Function &F) {
00592   auto I = VisitedHandlers.insert(&F);
00593   if (!I.second)
00594     return; // We've already visited this handler, don't renumber it.
00595 
00596   int OldBaseState = CurrentBaseState;
00597   if (FuncInfo.HandlerBaseState.count(&F)) {
00598     CurrentBaseState = FuncInfo.HandlerBaseState[&F];
00599   }
00600 
00601   size_t SavedHandlerStackSize = HandlerStack.size();
00602 
00603   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
00604   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
00605   for (const BasicBlock &BB : F) {
00606     for (const Instruction &I : BB) {
00607       const auto *CI = dyn_cast<CallInst>(&I);
00608       if (!CI || CI->doesNotThrow())
00609         continue;
00610       processCallSite(None, CI);
00611     }
00612     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
00613     if (!II)
00614       continue;
00615     const LandingPadInst *LPI = II->getLandingPadInst();
00616     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
00617     if (!ActionsCall)
00618       continue;
00619     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
00620     parseEHActions(ActionsCall, ActionList);
00621     if (ActionList.empty())
00622       continue;
00623     processCallSite(ActionList, II);
00624     ActionList.clear();
00625     FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
00626     DEBUG(dbgs() << "Assigning state " << currentEHNumber()
00627                   << " to landing pad at " << LPI->getParent()->getName()
00628                   << '\n');
00629   }
00630 
00631   // Pop any actions that were pushed on the stack for this function.
00632   popUnmatchedActions(SavedHandlerStackSize);
00633 
00634   DEBUG(dbgs() << "Assigning max state " << NextState - 1
00635                << " to " << F.getName() << '\n');
00636   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
00637 
00638   CurrentBaseState = OldBaseState;
00639 }
00640 
00641 // This function follows the same basic traversal as calculateStateNumbers
00642 // but it is necessary to identify the root landing pad associated
00643 // with each action before we start assigning state numbers.
00644 void WinEHNumbering::findActionRootLPads(const Function &F) {
00645   auto I = VisitedHandlers.insert(&F);
00646   if (!I.second)
00647     return; // We've already visited this handler, don't revisit it.
00648 
00649   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
00650   for (const BasicBlock &BB : F) {
00651     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
00652     if (!II)
00653       continue;
00654     const LandingPadInst *LPI = II->getLandingPadInst();
00655     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
00656     if (!ActionsCall)
00657       continue;
00658 
00659     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
00660     parseEHActions(ActionsCall, ActionList);
00661     if (ActionList.empty())
00662       continue;
00663     for (int I = 0, E = ActionList.size(); I < E; ++I) {
00664       if (auto *Handler
00665               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
00666         FuncInfo.LastInvoke[Handler] = II;
00667         // Don't replace the root landing pad if we previously saw this
00668         // handler in a different function.
00669         if (FuncInfo.RootLPad.count(Handler) &&
00670             FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
00671           continue;
00672         DEBUG(dbgs() << "Setting root lpad for ");
00673         print_name(Handler);
00674         DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
00675         FuncInfo.RootLPad[Handler] = LPI;
00676       }
00677     }
00678     // Walk the actions again and look for nested handlers.  This has to
00679     // happen after all of the actions have been processed in the current
00680     // function.
00681     for (int I = 0, E = ActionList.size(); I < E; ++I)
00682       if (auto *Handler
00683               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
00684         findActionRootLPads(*Handler);
00685     ActionList.clear();
00686   }
00687 }
00688 
00689 /// clear - Clear out all the function-specific state. This returns this
00690 /// FunctionLoweringInfo to an empty state, ready to be used for a
00691 /// different function.
00692 void FunctionLoweringInfo::clear() {
00693   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
00694          "Not all catch info was assigned to a landing pad!");
00695 
00696   MBBMap.clear();
00697   ValueMap.clear();
00698   StaticAllocaMap.clear();
00699 #ifndef NDEBUG
00700   CatchInfoLost.clear();
00701   CatchInfoFound.clear();
00702 #endif
00703   LiveOutRegInfo.clear();
00704   VisitedBBs.clear();
00705   ArgDbgValues.clear();
00706   ByValArgFrameIndexMap.clear();
00707   RegFixups.clear();
00708   StatepointStackSlots.clear();
00709   StatepointRelocatedValues.clear();
00710   PreferredExtendType.clear();
00711 }
00712 
00713 /// CreateReg - Allocate a single virtual register for the given type.
00714 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
00715   return RegInfo->createVirtualRegister(
00716       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
00717 }
00718 
00719 /// CreateRegs - Allocate the appropriate number of virtual registers of
00720 /// the correctly promoted or expanded types.  Assign these registers
00721 /// consecutive vreg numbers and return the first assigned number.
00722 ///
00723 /// In the case that the given value has struct or array type, this function
00724 /// will assign registers for each member or element.
00725 ///
00726 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
00727   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
00728 
00729   SmallVector<EVT, 4> ValueVTs;
00730   ComputeValueVTs(*TLI, Ty, ValueVTs);
00731 
00732   unsigned FirstReg = 0;
00733   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00734     EVT ValueVT = ValueVTs[Value];
00735     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
00736 
00737     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
00738     for (unsigned i = 0; i != NumRegs; ++i) {
00739       unsigned R = CreateReg(RegisterVT);
00740       if (!FirstReg) FirstReg = R;
00741     }
00742   }
00743   return FirstReg;
00744 }
00745 
00746 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
00747 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
00748 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
00749 /// the larger bit width by zero extension. The bit width must be no smaller
00750 /// than the LiveOutInfo's existing bit width.
00751 const FunctionLoweringInfo::LiveOutInfo *
00752 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
00753   if (!LiveOutRegInfo.inBounds(Reg))
00754     return nullptr;
00755 
00756   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
00757   if (!LOI->IsValid)
00758     return nullptr;
00759 
00760   if (BitWidth > LOI->KnownZero.getBitWidth()) {
00761     LOI->NumSignBits = 1;
00762     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
00763     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
00764   }
00765 
00766   return LOI;
00767 }
00768 
00769 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
00770 /// register based on the LiveOutInfo of its operands.
00771 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
00772   Type *Ty = PN->getType();
00773   if (!Ty->isIntegerTy() || Ty->isVectorTy())
00774     return;
00775 
00776   SmallVector<EVT, 1> ValueVTs;
00777   ComputeValueVTs(*TLI, Ty, ValueVTs);
00778   assert(ValueVTs.size() == 1 &&
00779          "PHIs with non-vector integer types should have a single VT.");
00780   EVT IntVT = ValueVTs[0];
00781 
00782   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
00783     return;
00784   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
00785   unsigned BitWidth = IntVT.getSizeInBits();
00786 
00787   unsigned DestReg = ValueMap[PN];
00788   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00789     return;
00790   LiveOutRegInfo.grow(DestReg);
00791   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
00792 
00793   Value *V = PN->getIncomingValue(0);
00794   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00795     DestLOI.NumSignBits = 1;
00796     APInt Zero(BitWidth, 0);
00797     DestLOI.KnownZero = Zero;
00798     DestLOI.KnownOne = Zero;
00799     return;
00800   }
00801 
00802   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00803     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00804     DestLOI.NumSignBits = Val.getNumSignBits();
00805     DestLOI.KnownZero = ~Val;
00806     DestLOI.KnownOne = Val;
00807   } else {
00808     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
00809                                 "CopyToReg node was created.");
00810     unsigned SrcReg = ValueMap[V];
00811     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00812       DestLOI.IsValid = false;
00813       return;
00814     }
00815     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00816     if (!SrcLOI) {
00817       DestLOI.IsValid = false;
00818       return;
00819     }
00820     DestLOI = *SrcLOI;
00821   }
00822 
00823   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
00824          DestLOI.KnownOne.getBitWidth() == BitWidth &&
00825          "Masks should have the same bit width as the type.");
00826 
00827   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
00828     Value *V = PN->getIncomingValue(i);
00829     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00830       DestLOI.NumSignBits = 1;
00831       APInt Zero(BitWidth, 0);
00832       DestLOI.KnownZero = Zero;
00833       DestLOI.KnownOne = Zero;
00834       return;
00835     }
00836 
00837     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00838       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00839       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
00840       DestLOI.KnownZero &= ~Val;
00841       DestLOI.KnownOne &= Val;
00842       continue;
00843     }
00844 
00845     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
00846                                 "its CopyToReg node was created.");
00847     unsigned SrcReg = ValueMap[V];
00848     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00849       DestLOI.IsValid = false;
00850       return;
00851     }
00852     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00853     if (!SrcLOI) {
00854       DestLOI.IsValid = false;
00855       return;
00856     }
00857     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
00858     DestLOI.KnownZero &= SrcLOI->KnownZero;
00859     DestLOI.KnownOne &= SrcLOI->KnownOne;
00860   }
00861 }
00862 
00863 /// setArgumentFrameIndex - Record frame index for the byval
00864 /// argument. This overrides previous frame index entry for this argument,
00865 /// if any.
00866 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
00867                                                  int FI) {
00868   ByValArgFrameIndexMap[A] = FI;
00869 }
00870 
00871 /// getArgumentFrameIndex - Get frame index for the byval argument.
00872 /// If the argument does not have any assigned frame index then 0 is
00873 /// returned.
00874 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
00875   DenseMap<const Argument *, int>::iterator I =
00876     ByValArgFrameIndexMap.find(A);
00877   if (I != ByValArgFrameIndexMap.end())
00878     return I->second;
00879   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
00880   return 0;
00881 }
00882 
00883 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
00884 /// being passed to this variadic function, and set the MachineModuleInfo's
00885 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
00886 /// reference to _fltused on Windows, which will link in MSVCRT's
00887 /// floating-point support.
00888 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
00889                                       MachineModuleInfo *MMI)
00890 {
00891   FunctionType *FT = cast<FunctionType>(
00892     I.getCalledValue()->getType()->getContainedType(0));
00893   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
00894     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
00895       Type* T = I.getArgOperand(i)->getType();
00896       for (auto i : post_order(T)) {
00897         if (i->isFloatingPointTy()) {
00898           MMI->setUsesVAFloatArgument(true);
00899           return;
00900         }
00901       }
00902     }
00903   }
00904 }
00905 
00906 /// AddLandingPadInfo - Extract the exception handling information from the
00907 /// landingpad instruction and add them to the specified machine module info.
00908 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
00909                              MachineBasicBlock *MBB) {
00910   MMI.addPersonality(MBB,
00911                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
00912 
00913   if (I.isCleanup())
00914     MMI.addCleanup(MBB);
00915 
00916   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
00917   //        but we need to do it this way because of how the DWARF EH emitter
00918   //        processes the clauses.
00919   for (unsigned i = I.getNumClauses(); i != 0; --i) {
00920     Value *Val = I.getClause(i - 1);
00921     if (I.isCatch(i - 1)) {
00922       MMI.addCatchTypeInfo(MBB,
00923                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
00924     } else {
00925       // Add filters in a list.
00926       Constant *CVal = cast<Constant>(Val);
00927       SmallVector<const GlobalValue*, 4> FilterList;
00928       for (User::op_iterator
00929              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
00930         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
00931 
00932       MMI.addFilterTypeInfo(MBB, FilterList);
00933     }
00934   }
00935 }