LLVM  mainline
SelectionDAGISel.cpp
Go to the documentation of this file.
00001 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
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 the SelectionDAGISel class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/GCStrategy.h"
00015 #include "ScheduleDAGSDNodes.h"
00016 #include "SelectionDAGBuilder.h"
00017 #include "llvm/ADT/PostOrderIterator.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/BranchProbabilityInfo.h"
00021 #include "llvm/Analysis/CFG.h"
00022 #include "llvm/Analysis/TargetLibraryInfo.h"
00023 #include "llvm/CodeGen/Analysis.h"
00024 #include "llvm/CodeGen/FastISel.h"
00025 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00026 #include "llvm/CodeGen/GCMetadata.h"
00027 #include "llvm/CodeGen/MachineFrameInfo.h"
00028 #include "llvm/CodeGen/MachineFunction.h"
00029 #include "llvm/CodeGen/MachineInstrBuilder.h"
00030 #include "llvm/CodeGen/MachineModuleInfo.h"
00031 #include "llvm/CodeGen/MachineRegisterInfo.h"
00032 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00033 #include "llvm/CodeGen/SchedulerRegistry.h"
00034 #include "llvm/CodeGen/SelectionDAG.h"
00035 #include "llvm/CodeGen/SelectionDAGISel.h"
00036 #include "llvm/CodeGen/WinEHFuncInfo.h"
00037 #include "llvm/IR/Constants.h"
00038 #include "llvm/IR/DebugInfo.h"
00039 #include "llvm/IR/Function.h"
00040 #include "llvm/IR/InlineAsm.h"
00041 #include "llvm/IR/Instructions.h"
00042 #include "llvm/IR/IntrinsicInst.h"
00043 #include "llvm/IR/Intrinsics.h"
00044 #include "llvm/IR/LLVMContext.h"
00045 #include "llvm/IR/Module.h"
00046 #include "llvm/MC/MCAsmInfo.h"
00047 #include "llvm/Support/Compiler.h"
00048 #include "llvm/Support/Debug.h"
00049 #include "llvm/Support/ErrorHandling.h"
00050 #include "llvm/Support/Timer.h"
00051 #include "llvm/Support/raw_ostream.h"
00052 #include "llvm/Target/TargetInstrInfo.h"
00053 #include "llvm/Target/TargetIntrinsicInfo.h"
00054 #include "llvm/Target/TargetLowering.h"
00055 #include "llvm/Target/TargetMachine.h"
00056 #include "llvm/Target/TargetOptions.h"
00057 #include "llvm/Target/TargetRegisterInfo.h"
00058 #include "llvm/Target/TargetSubtargetInfo.h"
00059 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00060 #include <algorithm>
00061 using namespace llvm;
00062 
00063 #define DEBUG_TYPE "isel"
00064 
00065 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
00066 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
00067 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
00068 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
00069 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
00070 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
00071 STATISTIC(NumFastIselFailLowerArguments,
00072           "Number of entry blocks where fast isel failed to lower arguments");
00073 
00074 #ifndef NDEBUG
00075 static cl::opt<bool>
00076 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
00077           cl::desc("Enable extra verbose messages in the \"fast\" "
00078                    "instruction selector"));
00079 
00080   // Terminators
00081 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
00082 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
00083 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
00084 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
00085 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
00086 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
00087 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
00088 
00089   // Standard binary operators...
00090 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
00091 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
00092 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
00093 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
00094 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
00095 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
00096 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
00097 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
00098 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
00099 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
00100 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
00101 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
00102 
00103   // Logical operators...
00104 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
00105 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
00106 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
00107 
00108   // Memory instructions...
00109 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
00110 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
00111 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
00112 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
00113 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
00114 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
00115 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
00116 
00117   // Convert instructions...
00118 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
00119 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
00120 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
00121 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
00122 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
00123 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
00124 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
00125 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
00126 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
00127 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
00128 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
00129 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
00130 
00131   // Other instructions...
00132 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
00133 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
00134 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
00135 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
00136 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
00137 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
00138 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
00139 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
00140 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
00141 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
00142 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
00143 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
00144 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
00145 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
00146 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
00147 
00148 // Intrinsic instructions...
00149 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call");
00150 STATISTIC(NumFastIselFailSAddWithOverflow,
00151           "Fast isel fails on sadd.with.overflow");
00152 STATISTIC(NumFastIselFailUAddWithOverflow,
00153           "Fast isel fails on uadd.with.overflow");
00154 STATISTIC(NumFastIselFailSSubWithOverflow,
00155           "Fast isel fails on ssub.with.overflow");
00156 STATISTIC(NumFastIselFailUSubWithOverflow,
00157           "Fast isel fails on usub.with.overflow");
00158 STATISTIC(NumFastIselFailSMulWithOverflow,
00159           "Fast isel fails on smul.with.overflow");
00160 STATISTIC(NumFastIselFailUMulWithOverflow,
00161           "Fast isel fails on umul.with.overflow");
00162 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress");
00163 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call");
00164 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call");
00165 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call");
00166 #endif
00167 
00168 static cl::opt<bool>
00169 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
00170           cl::desc("Enable verbose messages in the \"fast\" "
00171                    "instruction selector"));
00172 static cl::opt<int> EnableFastISelAbort(
00173     "fast-isel-abort", cl::Hidden,
00174     cl::desc("Enable abort calls when \"fast\" instruction selection "
00175              "fails to lower an instruction: 0 disable the abort, 1 will "
00176              "abort but for args, calls and terminators, 2 will also "
00177              "abort for argument lowering, and 3 will never fallback "
00178              "to SelectionDAG."));
00179 
00180 static cl::opt<bool>
00181 UseMBPI("use-mbpi",
00182         cl::desc("use Machine Branch Probability Info"),
00183         cl::init(true), cl::Hidden);
00184 
00185 #ifndef NDEBUG
00186 static cl::opt<std::string>
00187 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
00188                         cl::desc("Only display the basic block whose name "
00189                                  "matches this for all view-*-dags options"));
00190 static cl::opt<bool>
00191 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
00192           cl::desc("Pop up a window to show dags before the first "
00193                    "dag combine pass"));
00194 static cl::opt<bool>
00195 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
00196           cl::desc("Pop up a window to show dags before legalize types"));
00197 static cl::opt<bool>
00198 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
00199           cl::desc("Pop up a window to show dags before legalize"));
00200 static cl::opt<bool>
00201 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
00202           cl::desc("Pop up a window to show dags before the second "
00203                    "dag combine pass"));
00204 static cl::opt<bool>
00205 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
00206           cl::desc("Pop up a window to show dags before the post legalize types"
00207                    " dag combine pass"));
00208 static cl::opt<bool>
00209 ViewISelDAGs("view-isel-dags", cl::Hidden,
00210           cl::desc("Pop up a window to show isel dags as they are selected"));
00211 static cl::opt<bool>
00212 ViewSchedDAGs("view-sched-dags", cl::Hidden,
00213           cl::desc("Pop up a window to show sched dags as they are processed"));
00214 static cl::opt<bool>
00215 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
00216       cl::desc("Pop up a window to show SUnit dags after they are processed"));
00217 #else
00218 static const bool ViewDAGCombine1 = false,
00219                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
00220                   ViewDAGCombine2 = false,
00221                   ViewDAGCombineLT = false,
00222                   ViewISelDAGs = false, ViewSchedDAGs = false,
00223                   ViewSUnitDAGs = false;
00224 #endif
00225 
00226 //===---------------------------------------------------------------------===//
00227 ///
00228 /// RegisterScheduler class - Track the registration of instruction schedulers.
00229 ///
00230 //===---------------------------------------------------------------------===//
00231 MachinePassRegistry RegisterScheduler::Registry;
00232 
00233 //===---------------------------------------------------------------------===//
00234 ///
00235 /// ISHeuristic command line option for instruction schedulers.
00236 ///
00237 //===---------------------------------------------------------------------===//
00238 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
00239                RegisterPassParser<RegisterScheduler> >
00240 ISHeuristic("pre-RA-sched",
00241             cl::init(&createDefaultScheduler), cl::Hidden,
00242             cl::desc("Instruction schedulers available (before register"
00243                      " allocation):"));
00244 
00245 static RegisterScheduler
00246 defaultListDAGScheduler("default", "Best scheduler for the target",
00247                         createDefaultScheduler);
00248 
00249 namespace llvm {
00250   //===--------------------------------------------------------------------===//
00251   /// \brief This class is used by SelectionDAGISel to temporarily override
00252   /// the optimization level on a per-function basis.
00253   class OptLevelChanger {
00254     SelectionDAGISel &IS;
00255     CodeGenOpt::Level SavedOptLevel;
00256     bool SavedFastISel;
00257 
00258   public:
00259     OptLevelChanger(SelectionDAGISel &ISel,
00260                     CodeGenOpt::Level NewOptLevel) : IS(ISel) {
00261       SavedOptLevel = IS.OptLevel;
00262       if (NewOptLevel == SavedOptLevel)
00263         return;
00264       IS.OptLevel = NewOptLevel;
00265       IS.TM.setOptLevel(NewOptLevel);
00266       SavedFastISel = IS.TM.Options.EnableFastISel;
00267       if (NewOptLevel == CodeGenOpt::None)
00268         IS.TM.setFastISel(true);
00269       DEBUG(dbgs() << "\nChanging optimization level for Function "
00270             << IS.MF->getFunction()->getName() << "\n");
00271       DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
00272             << " ; After: -O" << NewOptLevel << "\n");
00273     }
00274 
00275     ~OptLevelChanger() {
00276       if (IS.OptLevel == SavedOptLevel)
00277         return;
00278       DEBUG(dbgs() << "\nRestoring optimization level for Function "
00279             << IS.MF->getFunction()->getName() << "\n");
00280       DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
00281             << " ; After: -O" << SavedOptLevel << "\n");
00282       IS.OptLevel = SavedOptLevel;
00283       IS.TM.setOptLevel(SavedOptLevel);
00284       IS.TM.setFastISel(SavedFastISel);
00285     }
00286   };
00287 
00288   //===--------------------------------------------------------------------===//
00289   /// createDefaultScheduler - This creates an instruction scheduler appropriate
00290   /// for the target.
00291   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
00292                                              CodeGenOpt::Level OptLevel) {
00293     const TargetLowering *TLI = IS->TLI;
00294     const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
00295 
00296     if (OptLevel == CodeGenOpt::None ||
00297         (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
00298         TLI->getSchedulingPreference() == Sched::Source)
00299       return createSourceListDAGScheduler(IS, OptLevel);
00300     if (TLI->getSchedulingPreference() == Sched::RegPressure)
00301       return createBURRListDAGScheduler(IS, OptLevel);
00302     if (TLI->getSchedulingPreference() == Sched::Hybrid)
00303       return createHybridListDAGScheduler(IS, OptLevel);
00304     if (TLI->getSchedulingPreference() == Sched::VLIW)
00305       return createVLIWDAGScheduler(IS, OptLevel);
00306     assert(TLI->getSchedulingPreference() == Sched::ILP &&
00307            "Unknown sched type!");
00308     return createILPListDAGScheduler(IS, OptLevel);
00309   }
00310 }
00311 
00312 // EmitInstrWithCustomInserter - This method should be implemented by targets
00313 // that mark instructions with the 'usesCustomInserter' flag.  These
00314 // instructions are special in various ways, which require special support to
00315 // insert.  The specified MachineInstr is created but not inserted into any
00316 // basic blocks, and this method is called to expand it into a sequence of
00317 // instructions, potentially also creating new basic blocks and control flow.
00318 // When new basic blocks are inserted and the edges from MBB to its successors
00319 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
00320 // DenseMap.
00321 MachineBasicBlock *
00322 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00323                                             MachineBasicBlock *MBB) const {
00324 #ifndef NDEBUG
00325   dbgs() << "If a target marks an instruction with "
00326           "'usesCustomInserter', it must implement "
00327           "TargetLowering::EmitInstrWithCustomInserter!";
00328 #endif
00329   llvm_unreachable(nullptr);
00330 }
00331 
00332 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
00333                                                    SDNode *Node) const {
00334   assert(!MI->hasPostISelHook() &&
00335          "If a target marks an instruction with 'hasPostISelHook', "
00336          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
00337 }
00338 
00339 //===----------------------------------------------------------------------===//
00340 // SelectionDAGISel code
00341 //===----------------------------------------------------------------------===//
00342 
00343 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
00344                                    CodeGenOpt::Level OL) :
00345   MachineFunctionPass(ID), TM(tm),
00346   FuncInfo(new FunctionLoweringInfo()),
00347   CurDAG(new SelectionDAG(tm, OL)),
00348   SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
00349   GFI(),
00350   OptLevel(OL),
00351   DAGSize(0) {
00352     initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
00353     initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
00354     initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
00355     initializeTargetLibraryInfoWrapperPassPass(
00356         *PassRegistry::getPassRegistry());
00357   }
00358 
00359 SelectionDAGISel::~SelectionDAGISel() {
00360   delete SDB;
00361   delete CurDAG;
00362   delete FuncInfo;
00363 }
00364 
00365 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
00366   AU.addRequired<AliasAnalysis>();
00367   AU.addPreserved<AliasAnalysis>();
00368   AU.addRequired<GCModuleInfo>();
00369   AU.addPreserved<GCModuleInfo>();
00370   AU.addRequired<TargetLibraryInfoWrapperPass>();
00371   if (UseMBPI && OptLevel != CodeGenOpt::None)
00372     AU.addRequired<BranchProbabilityInfo>();
00373   MachineFunctionPass::getAnalysisUsage(AU);
00374 }
00375 
00376 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
00377 /// may trap on it.  In this case we have to split the edge so that the path
00378 /// through the predecessor block that doesn't go to the phi block doesn't
00379 /// execute the possibly trapping instruction.
00380 ///
00381 /// This is required for correctness, so it must be done at -O0.
00382 ///
00383 static void SplitCriticalSideEffectEdges(Function &Fn, AliasAnalysis *AA) {
00384   // Loop for blocks with phi nodes.
00385   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00386     PHINode *PN = dyn_cast<PHINode>(BB->begin());
00387     if (!PN) continue;
00388 
00389   ReprocessBlock:
00390     // For each block with a PHI node, check to see if any of the input values
00391     // are potentially trapping constant expressions.  Constant expressions are
00392     // the only potentially trapping value that can occur as the argument to a
00393     // PHI.
00394     for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
00395       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00396         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
00397         if (!CE || !CE->canTrap()) continue;
00398 
00399         // The only case we have to worry about is when the edge is critical.
00400         // Since this block has a PHI Node, we assume it has multiple input
00401         // edges: check to see if the pred has multiple successors.
00402         BasicBlock *Pred = PN->getIncomingBlock(i);
00403         if (Pred->getTerminator()->getNumSuccessors() == 1)
00404           continue;
00405 
00406         // Okay, we have to split this edge.
00407         SplitCriticalEdge(
00408             Pred->getTerminator(), GetSuccessorNumber(Pred, BB),
00409             CriticalEdgeSplittingOptions(AA).setMergeIdenticalEdges());
00410         goto ReprocessBlock;
00411       }
00412   }
00413 }
00414 
00415 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
00416   // Do some sanity-checking on the command-line options.
00417   assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
00418          "-fast-isel-verbose requires -fast-isel");
00419   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
00420          "-fast-isel-abort > 0 requires -fast-isel");
00421 
00422   const Function &Fn = *mf.getFunction();
00423   MF = &mf;
00424 
00425   // Reset the target options before resetting the optimization
00426   // level below.
00427   // FIXME: This is a horrible hack and should be processed via
00428   // codegen looking at the optimization level explicitly when
00429   // it wants to look at it.
00430   TM.resetTargetOptions(Fn);
00431   // Reset OptLevel to None for optnone functions.
00432   CodeGenOpt::Level NewOptLevel = OptLevel;
00433   if (Fn.hasFnAttribute(Attribute::OptimizeNone))
00434     NewOptLevel = CodeGenOpt::None;
00435   OptLevelChanger OLC(*this, NewOptLevel);
00436 
00437   TII = MF->getSubtarget().getInstrInfo();
00438   TLI = MF->getSubtarget().getTargetLowering();
00439   RegInfo = &MF->getRegInfo();
00440   AA = &getAnalysis<AliasAnalysis>();
00441   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00442   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
00443 
00444   DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
00445 
00446   SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), AA);
00447 
00448   CurDAG->init(*MF);
00449   FuncInfo->set(Fn, *MF, CurDAG);
00450 
00451   if (UseMBPI && OptLevel != CodeGenOpt::None)
00452     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
00453   else
00454     FuncInfo->BPI = nullptr;
00455 
00456   SDB->init(GFI, *AA, LibInfo);
00457 
00458   MF->setHasInlineAsm(false);
00459 
00460   SelectAllBasicBlocks(Fn);
00461 
00462   // If the first basic block in the function has live ins that need to be
00463   // copied into vregs, emit the copies into the top of the block before
00464   // emitting the code for the block.
00465   MachineBasicBlock *EntryMBB = MF->begin();
00466   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
00467   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
00468 
00469   DenseMap<unsigned, unsigned> LiveInMap;
00470   if (!FuncInfo->ArgDbgValues.empty())
00471     for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
00472            E = RegInfo->livein_end(); LI != E; ++LI)
00473       if (LI->second)
00474         LiveInMap.insert(std::make_pair(LI->first, LI->second));
00475 
00476   // Insert DBG_VALUE instructions for function arguments to the entry block.
00477   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
00478     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
00479     bool hasFI = MI->getOperand(0).isFI();
00480     unsigned Reg =
00481         hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
00482     if (TargetRegisterInfo::isPhysicalRegister(Reg))
00483       EntryMBB->insert(EntryMBB->begin(), MI);
00484     else {
00485       MachineInstr *Def = RegInfo->getVRegDef(Reg);
00486       if (Def) {
00487         MachineBasicBlock::iterator InsertPos = Def;
00488         // FIXME: VR def may not be in entry block.
00489         Def->getParent()->insert(std::next(InsertPos), MI);
00490       } else
00491         DEBUG(dbgs() << "Dropping debug info for dead vreg"
00492               << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
00493     }
00494 
00495     // If Reg is live-in then update debug info to track its copy in a vreg.
00496     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
00497     if (LDI != LiveInMap.end()) {
00498       assert(!hasFI && "There's no handling of frame pointer updating here yet "
00499                        "- add if needed");
00500       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
00501       MachineBasicBlock::iterator InsertPos = Def;
00502       const MDNode *Variable = MI->getDebugVariable();
00503       const MDNode *Expr = MI->getDebugExpression();
00504       DebugLoc DL = MI->getDebugLoc();
00505       bool IsIndirect = MI->isIndirectDebugValue();
00506       unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
00507       assert(cast<MDLocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
00508              "Expected inlined-at fields to agree");
00509       // Def is never a terminator here, so it is ok to increment InsertPos.
00510       BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
00511               IsIndirect, LDI->second, Offset, Variable, Expr);
00512 
00513       // If this vreg is directly copied into an exported register then
00514       // that COPY instructions also need DBG_VALUE, if it is the only
00515       // user of LDI->second.
00516       MachineInstr *CopyUseMI = nullptr;
00517       for (MachineRegisterInfo::use_instr_iterator
00518            UI = RegInfo->use_instr_begin(LDI->second),
00519            E = RegInfo->use_instr_end(); UI != E; ) {
00520         MachineInstr *UseMI = &*(UI++);
00521         if (UseMI->isDebugValue()) continue;
00522         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
00523           CopyUseMI = UseMI; continue;
00524         }
00525         // Otherwise this is another use or second copy use.
00526         CopyUseMI = nullptr; break;
00527       }
00528       if (CopyUseMI) {
00529         // Use MI's debug location, which describes where Variable was
00530         // declared, rather than whatever is attached to CopyUseMI.
00531         MachineInstr *NewMI =
00532             BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
00533                     CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
00534         MachineBasicBlock::iterator Pos = CopyUseMI;
00535         EntryMBB->insertAfter(Pos, NewMI);
00536       }
00537     }
00538   }
00539 
00540   // Determine if there are any calls in this machine function.
00541   MachineFrameInfo *MFI = MF->getFrameInfo();
00542   for (const auto &MBB : *MF) {
00543     if (MFI->hasCalls() && MF->hasInlineAsm())
00544       break;
00545 
00546     for (const auto &MI : MBB) {
00547       const MCInstrDesc &MCID = TII->get(MI.getOpcode());
00548       if ((MCID.isCall() && !MCID.isReturn()) ||
00549           MI.isStackAligningInlineAsm()) {
00550         MFI->setHasCalls(true);
00551       }
00552       if (MI.isInlineAsm()) {
00553         MF->setHasInlineAsm(true);
00554       }
00555     }
00556   }
00557 
00558   // Determine if there is a call to setjmp in the machine function.
00559   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
00560 
00561   // Replace forward-declared registers with the registers containing
00562   // the desired value.
00563   MachineRegisterInfo &MRI = MF->getRegInfo();
00564   for (DenseMap<unsigned, unsigned>::iterator
00565        I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
00566        I != E; ++I) {
00567     unsigned From = I->first;
00568     unsigned To = I->second;
00569     // If To is also scheduled to be replaced, find what its ultimate
00570     // replacement is.
00571     for (;;) {
00572       DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
00573       if (J == E) break;
00574       To = J->second;
00575     }
00576     // Make sure the new register has a sufficiently constrained register class.
00577     if (TargetRegisterInfo::isVirtualRegister(From) &&
00578         TargetRegisterInfo::isVirtualRegister(To))
00579       MRI.constrainRegClass(To, MRI.getRegClass(From));
00580     // Replace it.
00581     MRI.replaceRegWith(From, To);
00582   }
00583 
00584   // Freeze the set of reserved registers now that MachineFrameInfo has been
00585   // set up. All the information required by getReservedRegs() should be
00586   // available now.
00587   MRI.freezeReservedRegs(*MF);
00588 
00589   // Release function-specific state. SDB and CurDAG are already cleared
00590   // at this point.
00591   FuncInfo->clear();
00592 
00593   DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
00594   DEBUG(MF->print(dbgs()));
00595 
00596   return true;
00597 }
00598 
00599 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
00600                                         BasicBlock::const_iterator End,
00601                                         bool &HadTailCall) {
00602   // Lower the instructions. If a call is emitted as a tail call, cease emitting
00603   // nodes for this block.
00604   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
00605     SDB->visit(*I);
00606 
00607   // Make sure the root of the DAG is up-to-date.
00608   CurDAG->setRoot(SDB->getControlRoot());
00609   HadTailCall = SDB->HasTailCall;
00610   SDB->clear();
00611 
00612   // Final step, emit the lowered DAG as machine code.
00613   CodeGenAndEmitDAG();
00614 }
00615 
00616 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
00617   SmallPtrSet<SDNode*, 128> VisitedNodes;
00618   SmallVector<SDNode*, 128> Worklist;
00619 
00620   Worklist.push_back(CurDAG->getRoot().getNode());
00621 
00622   APInt KnownZero;
00623   APInt KnownOne;
00624 
00625   do {
00626     SDNode *N = Worklist.pop_back_val();
00627 
00628     // If we've already seen this node, ignore it.
00629     if (!VisitedNodes.insert(N).second)
00630       continue;
00631 
00632     // Otherwise, add all chain operands to the worklist.
00633     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00634       if (N->getOperand(i).getValueType() == MVT::Other)
00635         Worklist.push_back(N->getOperand(i).getNode());
00636 
00637     // If this is a CopyToReg with a vreg dest, process it.
00638     if (N->getOpcode() != ISD::CopyToReg)
00639       continue;
00640 
00641     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
00642     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00643       continue;
00644 
00645     // Ignore non-scalar or non-integer values.
00646     SDValue Src = N->getOperand(2);
00647     EVT SrcVT = Src.getValueType();
00648     if (!SrcVT.isInteger() || SrcVT.isVector())
00649       continue;
00650 
00651     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
00652     CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
00653     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
00654   } while (!Worklist.empty());
00655 }
00656 
00657 void SelectionDAGISel::CodeGenAndEmitDAG() {
00658   std::string GroupName;
00659   if (TimePassesIsEnabled)
00660     GroupName = "Instruction Selection and Scheduling";
00661   std::string BlockName;
00662   int BlockNumber = -1;
00663   (void)BlockNumber;
00664   bool MatchFilterBB = false; (void)MatchFilterBB;
00665 #ifndef NDEBUG
00666   MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
00667                    FilterDAGBasicBlockName ==
00668                        FuncInfo->MBB->getBasicBlock()->getName().str());
00669 #endif
00670 #ifdef NDEBUG
00671   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
00672       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
00673       ViewSUnitDAGs)
00674 #endif
00675   {
00676     BlockNumber = FuncInfo->MBB->getNumber();
00677     BlockName =
00678         (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
00679   }
00680   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
00681         << " '" << BlockName << "'\n"; CurDAG->dump());
00682 
00683   if (ViewDAGCombine1 && MatchFilterBB)
00684     CurDAG->viewGraph("dag-combine1 input for " + BlockName);
00685 
00686   // Run the DAG combiner in pre-legalize mode.
00687   {
00688     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
00689     CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
00690   }
00691 
00692   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
00693         << " '" << BlockName << "'\n"; CurDAG->dump());
00694 
00695   // Second step, hack on the DAG until it only uses operations and types that
00696   // the target supports.
00697   if (ViewLegalizeTypesDAGs && MatchFilterBB)
00698     CurDAG->viewGraph("legalize-types input for " + BlockName);
00699 
00700   bool Changed;
00701   {
00702     NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
00703     Changed = CurDAG->LegalizeTypes();
00704   }
00705 
00706   DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
00707         << " '" << BlockName << "'\n"; CurDAG->dump());
00708 
00709   CurDAG->NewNodesMustHaveLegalTypes = true;
00710 
00711   if (Changed) {
00712     if (ViewDAGCombineLT && MatchFilterBB)
00713       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
00714 
00715     // Run the DAG combiner in post-type-legalize mode.
00716     {
00717       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
00718                          TimePassesIsEnabled);
00719       CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
00720     }
00721 
00722     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
00723           << " '" << BlockName << "'\n"; CurDAG->dump());
00724 
00725   }
00726 
00727   {
00728     NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
00729     Changed = CurDAG->LegalizeVectors();
00730   }
00731 
00732   if (Changed) {
00733     {
00734       NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
00735       CurDAG->LegalizeTypes();
00736     }
00737 
00738     if (ViewDAGCombineLT && MatchFilterBB)
00739       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
00740 
00741     // Run the DAG combiner in post-type-legalize mode.
00742     {
00743       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
00744                          TimePassesIsEnabled);
00745       CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
00746     }
00747 
00748     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
00749           << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
00750   }
00751 
00752   if (ViewLegalizeDAGs && MatchFilterBB)
00753     CurDAG->viewGraph("legalize input for " + BlockName);
00754 
00755   {
00756     NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
00757     CurDAG->Legalize();
00758   }
00759 
00760   DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
00761         << " '" << BlockName << "'\n"; CurDAG->dump());
00762 
00763   if (ViewDAGCombine2 && MatchFilterBB)
00764     CurDAG->viewGraph("dag-combine2 input for " + BlockName);
00765 
00766   // Run the DAG combiner in post-legalize mode.
00767   {
00768     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
00769     CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
00770   }
00771 
00772   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
00773         << " '" << BlockName << "'\n"; CurDAG->dump());
00774 
00775   if (OptLevel != CodeGenOpt::None)
00776     ComputeLiveOutVRegInfo();
00777 
00778   if (ViewISelDAGs && MatchFilterBB)
00779     CurDAG->viewGraph("isel input for " + BlockName);
00780 
00781   // Third, instruction select all of the operations to machine code, adding the
00782   // code to the MachineBasicBlock.
00783   {
00784     NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
00785     DoInstructionSelection();
00786   }
00787 
00788   DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
00789         << " '" << BlockName << "'\n"; CurDAG->dump());
00790 
00791   if (ViewSchedDAGs && MatchFilterBB)
00792     CurDAG->viewGraph("scheduler input for " + BlockName);
00793 
00794   // Schedule machine code.
00795   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
00796   {
00797     NamedRegionTimer T("Instruction Scheduling", GroupName,
00798                        TimePassesIsEnabled);
00799     Scheduler->Run(CurDAG, FuncInfo->MBB);
00800   }
00801 
00802   if (ViewSUnitDAGs && MatchFilterBB) Scheduler->viewGraph();
00803 
00804   // Emit machine code to BB.  This can change 'BB' to the last block being
00805   // inserted into.
00806   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
00807   {
00808     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
00809 
00810     // FuncInfo->InsertPt is passed by reference and set to the end of the
00811     // scheduled instructions.
00812     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
00813   }
00814 
00815   // If the block was split, make sure we update any references that are used to
00816   // update PHI nodes later on.
00817   if (FirstMBB != LastMBB)
00818     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
00819 
00820   // Free the scheduler state.
00821   {
00822     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
00823                        TimePassesIsEnabled);
00824     delete Scheduler;
00825   }
00826 
00827   // Free the SelectionDAG state, now that we're finished with it.
00828   CurDAG->clear();
00829 }
00830 
00831 namespace {
00832 /// ISelUpdater - helper class to handle updates of the instruction selection
00833 /// graph.
00834 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
00835   SelectionDAG::allnodes_iterator &ISelPosition;
00836 public:
00837   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
00838     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
00839 
00840   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
00841   /// deleted is the current ISelPosition node, update ISelPosition.
00842   ///
00843   void NodeDeleted(SDNode *N, SDNode *E) override {
00844     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
00845       ++ISelPosition;
00846   }
00847 };
00848 } // end anonymous namespace
00849 
00850 void SelectionDAGISel::DoInstructionSelection() {
00851   DEBUG(dbgs() << "===== Instruction selection begins: BB#"
00852         << FuncInfo->MBB->getNumber()
00853         << " '" << FuncInfo->MBB->getName() << "'\n");
00854 
00855   PreprocessISelDAG();
00856 
00857   // Select target instructions for the DAG.
00858   {
00859     // Number all nodes with a topological order and set DAGSize.
00860     DAGSize = CurDAG->AssignTopologicalOrder();
00861 
00862     // Create a dummy node (which is not added to allnodes), that adds
00863     // a reference to the root node, preventing it from being deleted,
00864     // and tracking any changes of the root.
00865     HandleSDNode Dummy(CurDAG->getRoot());
00866     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
00867     ++ISelPosition;
00868 
00869     // Make sure that ISelPosition gets properly updated when nodes are deleted
00870     // in calls made from this function.
00871     ISelUpdater ISU(*CurDAG, ISelPosition);
00872 
00873     // The AllNodes list is now topological-sorted. Visit the
00874     // nodes by starting at the end of the list (the root of the
00875     // graph) and preceding back toward the beginning (the entry
00876     // node).
00877     while (ISelPosition != CurDAG->allnodes_begin()) {
00878       SDNode *Node = --ISelPosition;
00879       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
00880       // but there are currently some corner cases that it misses. Also, this
00881       // makes it theoretically possible to disable the DAGCombiner.
00882       if (Node->use_empty())
00883         continue;
00884 
00885       SDNode *ResNode = Select(Node);
00886 
00887       // FIXME: This is pretty gross.  'Select' should be changed to not return
00888       // anything at all and this code should be nuked with a tactical strike.
00889 
00890       // If node should not be replaced, continue with the next one.
00891       if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
00892         continue;
00893       // Replace node.
00894       if (ResNode) {
00895         ReplaceUses(Node, ResNode);
00896       }
00897 
00898       // If after the replacement this node is not used any more,
00899       // remove this dead node.
00900       if (Node->use_empty()) // Don't delete EntryToken, etc.
00901         CurDAG->RemoveDeadNode(Node);
00902     }
00903 
00904     CurDAG->setRoot(Dummy.getValue());
00905   }
00906 
00907   DEBUG(dbgs() << "===== Instruction selection ends:\n");
00908 
00909   PostprocessISelDAG();
00910 }
00911 
00912 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
00913 /// do other setup for EH landing-pad blocks.
00914 bool SelectionDAGISel::PrepareEHLandingPad() {
00915   MachineBasicBlock *MBB = FuncInfo->MBB;
00916 
00917   const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
00918 
00919   // Add a label to mark the beginning of the landing pad.  Deletion of the
00920   // landing pad can thus be detected via the MachineModuleInfo.
00921   MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
00922 
00923   // Assign the call site to the landing pad's begin label.
00924   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
00925 
00926   const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
00927   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
00928     .addSym(Label);
00929 
00930   // If this is an MSVC-style personality function, we need to split the landing
00931   // pad into several BBs.
00932   const BasicBlock *LLVMBB = MBB->getBasicBlock();
00933   const LandingPadInst *LPadInst = LLVMBB->getLandingPadInst();
00934   MF->getMMI().addPersonality(
00935       MBB, cast<Function>(LPadInst->getPersonalityFn()->stripPointerCasts()));
00936   EHPersonality Personality = MF->getMMI().getPersonalityType();
00937 
00938   if (isMSVCEHPersonality(Personality)) {
00939     SmallVector<MachineBasicBlock *, 4> ClauseBBs;
00940     const IntrinsicInst *ActionsCall =
00941         dyn_cast<IntrinsicInst>(LLVMBB->getFirstInsertionPt());
00942     // Get all invoke BBs that unwind to this landingpad.
00943     SmallVector<MachineBasicBlock *, 4> InvokeBBs(MBB->pred_begin(),
00944                                                   MBB->pred_end());
00945     if (!ActionsCall || ActionsCall->getIntrinsicID() != Intrinsic::eh_actions) {
00946       assert(isa<UnreachableInst>(LLVMBB->getFirstInsertionPt()) &&
00947              "found landingpad without unreachable or llvm.eh.actions");
00948       return false;
00949     }
00950 
00951     // If this is a call to llvm.eh.actions followed by indirectbr, then we've
00952     // run WinEHPrepare, and we should remove this block from the machine CFG.
00953     // Mark the targets of the indirectbr as landingpads instead.
00954     for (const BasicBlock *LLVMSucc : successors(LLVMBB)) {
00955       MachineBasicBlock *ClauseBB = FuncInfo->MBBMap[LLVMSucc];
00956       // Add the edge from the invoke to the clause.
00957       for (MachineBasicBlock *InvokeBB : InvokeBBs)
00958         InvokeBB->addSuccessor(ClauseBB);
00959 
00960       // Mark the clause as a landing pad or MI passes will delete it.
00961       ClauseBB->setIsLandingPad();
00962     }
00963 
00964     // Remove the edge from the invoke to the lpad.
00965     for (MachineBasicBlock *InvokeBB : InvokeBBs)
00966       InvokeBB->removeSuccessor(MBB);
00967 
00968     // Restore FuncInfo back to its previous state and select the main landing
00969     // pad block.
00970     FuncInfo->MBB = MBB;
00971     FuncInfo->InsertPt = MBB->end();
00972 
00973     // Transfer EH state number assigned to the IR block to the MBB.
00974     if (Personality == EHPersonality::MSVC_CXX) {
00975       WinEHFuncInfo &FI = MF->getMMI().getWinEHFuncInfo(MF->getFunction());
00976       MF->getMMI().addWinEHState(MBB, FI.LandingPadStateMap[LPadInst]);
00977     }
00978 
00979     // Don't select instructions for landing pads using llvm.eh.actions.
00980     return false;
00981   }
00982 
00983   // Mark exception register as live in.
00984   if (unsigned Reg = TLI->getExceptionPointerRegister())
00985     FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
00986 
00987   // Mark exception selector register as live in.
00988   if (unsigned Reg = TLI->getExceptionSelectorRegister())
00989     FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
00990 
00991   return true;
00992 }
00993 
00994 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
00995 /// side-effect free and is either dead or folded into a generated instruction.
00996 /// Return false if it needs to be emitted.
00997 static bool isFoldedOrDeadInstruction(const Instruction *I,
00998                                       FunctionLoweringInfo *FuncInfo) {
00999   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
01000          !isa<TerminatorInst>(I) && // Terminators aren't folded.
01001          !isa<DbgInfoIntrinsic>(I) &&  // Debug instructions aren't folded.
01002          !isa<LandingPadInst>(I) &&    // Landingpad instructions aren't folded.
01003          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
01004 }
01005 
01006 #ifndef NDEBUG
01007 // Collect per Instruction statistics for fast-isel misses.  Only those
01008 // instructions that cause the bail are accounted for.  It does not account for
01009 // instructions higher in the block.  Thus, summing the per instructions stats
01010 // will not add up to what is reported by NumFastIselFailures.
01011 static void collectFailStats(const Instruction *I) {
01012   switch (I->getOpcode()) {
01013   default: assert (0 && "<Invalid operator> ");
01014 
01015   // Terminators
01016   case Instruction::Ret:         NumFastIselFailRet++; return;
01017   case Instruction::Br:          NumFastIselFailBr++; return;
01018   case Instruction::Switch:      NumFastIselFailSwitch++; return;
01019   case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
01020   case Instruction::Invoke:      NumFastIselFailInvoke++; return;
01021   case Instruction::Resume:      NumFastIselFailResume++; return;
01022   case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
01023 
01024   // Standard binary operators...
01025   case Instruction::Add:  NumFastIselFailAdd++; return;
01026   case Instruction::FAdd: NumFastIselFailFAdd++; return;
01027   case Instruction::Sub:  NumFastIselFailSub++; return;
01028   case Instruction::FSub: NumFastIselFailFSub++; return;
01029   case Instruction::Mul:  NumFastIselFailMul++; return;
01030   case Instruction::FMul: NumFastIselFailFMul++; return;
01031   case Instruction::UDiv: NumFastIselFailUDiv++; return;
01032   case Instruction::SDiv: NumFastIselFailSDiv++; return;
01033   case Instruction::FDiv: NumFastIselFailFDiv++; return;
01034   case Instruction::URem: NumFastIselFailURem++; return;
01035   case Instruction::SRem: NumFastIselFailSRem++; return;
01036   case Instruction::FRem: NumFastIselFailFRem++; return;
01037 
01038   // Logical operators...
01039   case Instruction::And: NumFastIselFailAnd++; return;
01040   case Instruction::Or:  NumFastIselFailOr++; return;
01041   case Instruction::Xor: NumFastIselFailXor++; return;
01042 
01043   // Memory instructions...
01044   case Instruction::Alloca:        NumFastIselFailAlloca++; return;
01045   case Instruction::Load:          NumFastIselFailLoad++; return;
01046   case Instruction::Store:         NumFastIselFailStore++; return;
01047   case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
01048   case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
01049   case Instruction::Fence:         NumFastIselFailFence++; return;
01050   case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
01051 
01052   // Convert instructions...
01053   case Instruction::Trunc:    NumFastIselFailTrunc++; return;
01054   case Instruction::ZExt:     NumFastIselFailZExt++; return;
01055   case Instruction::SExt:     NumFastIselFailSExt++; return;
01056   case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
01057   case Instruction::FPExt:    NumFastIselFailFPExt++; return;
01058   case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
01059   case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
01060   case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
01061   case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
01062   case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
01063   case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
01064   case Instruction::BitCast:  NumFastIselFailBitCast++; return;
01065 
01066   // Other instructions...
01067   case Instruction::ICmp:           NumFastIselFailICmp++; return;
01068   case Instruction::FCmp:           NumFastIselFailFCmp++; return;
01069   case Instruction::PHI:            NumFastIselFailPHI++; return;
01070   case Instruction::Select:         NumFastIselFailSelect++; return;
01071   case Instruction::Call: {
01072     if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
01073       switch (Intrinsic->getIntrinsicID()) {
01074       default:
01075         NumFastIselFailIntrinsicCall++; return;
01076       case Intrinsic::sadd_with_overflow:
01077         NumFastIselFailSAddWithOverflow++; return;
01078       case Intrinsic::uadd_with_overflow:
01079         NumFastIselFailUAddWithOverflow++; return;
01080       case Intrinsic::ssub_with_overflow:
01081         NumFastIselFailSSubWithOverflow++; return;
01082       case Intrinsic::usub_with_overflow:
01083         NumFastIselFailUSubWithOverflow++; return;
01084       case Intrinsic::smul_with_overflow:
01085         NumFastIselFailSMulWithOverflow++; return;
01086       case Intrinsic::umul_with_overflow:
01087         NumFastIselFailUMulWithOverflow++; return;
01088       case Intrinsic::frameaddress:
01089         NumFastIselFailFrameaddress++; return;
01090       case Intrinsic::sqrt:
01091           NumFastIselFailSqrt++; return;
01092       case Intrinsic::experimental_stackmap:
01093         NumFastIselFailStackMap++; return;
01094       case Intrinsic::experimental_patchpoint_void: // fall-through
01095       case Intrinsic::experimental_patchpoint_i64:
01096         NumFastIselFailPatchPoint++; return;
01097       }
01098     }
01099     NumFastIselFailCall++;
01100     return;
01101   }
01102   case Instruction::Shl:            NumFastIselFailShl++; return;
01103   case Instruction::LShr:           NumFastIselFailLShr++; return;
01104   case Instruction::AShr:           NumFastIselFailAShr++; return;
01105   case Instruction::VAArg:          NumFastIselFailVAArg++; return;
01106   case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
01107   case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
01108   case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
01109   case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
01110   case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
01111   case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
01112   }
01113 }
01114 #endif
01115 
01116 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
01117   // Initialize the Fast-ISel state, if needed.
01118   FastISel *FastIS = nullptr;
01119   if (TM.Options.EnableFastISel)
01120     FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
01121 
01122   // Iterate over all basic blocks in the function.
01123   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
01124   for (ReversePostOrderTraversal<const Function*>::rpo_iterator
01125        I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
01126     const BasicBlock *LLVMBB = *I;
01127 
01128     if (OptLevel != CodeGenOpt::None) {
01129       bool AllPredsVisited = true;
01130       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
01131            PI != PE; ++PI) {
01132         if (!FuncInfo->VisitedBBs.count(*PI)) {
01133           AllPredsVisited = false;
01134           break;
01135         }
01136       }
01137 
01138       if (AllPredsVisited) {
01139         for (BasicBlock::const_iterator I = LLVMBB->begin();
01140              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01141           FuncInfo->ComputePHILiveOutRegInfo(PN);
01142       } else {
01143         for (BasicBlock::const_iterator I = LLVMBB->begin();
01144              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01145           FuncInfo->InvalidatePHILiveOutRegInfo(PN);
01146       }
01147 
01148       FuncInfo->VisitedBBs.insert(LLVMBB);
01149     }
01150 
01151     BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
01152     BasicBlock::const_iterator const End = LLVMBB->end();
01153     BasicBlock::const_iterator BI = End;
01154 
01155     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
01156     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
01157 
01158     // Setup an EH landing-pad block.
01159     FuncInfo->ExceptionPointerVirtReg = 0;
01160     FuncInfo->ExceptionSelectorVirtReg = 0;
01161     if (LLVMBB->isLandingPad())
01162       if (!PrepareEHLandingPad())
01163         continue;
01164 
01165     // Before doing SelectionDAG ISel, see if FastISel has been requested.
01166     if (FastIS) {
01167       FastIS->startNewBlock();
01168 
01169       // Emit code for any incoming arguments. This must happen before
01170       // beginning FastISel on the entry block.
01171       if (LLVMBB == &Fn.getEntryBlock()) {
01172         ++NumEntryBlocks;
01173 
01174         // Lower any arguments needed in this block if this is the entry block.
01175         if (!FastIS->lowerArguments()) {
01176           // Fast isel failed to lower these arguments
01177           ++NumFastIselFailLowerArguments;
01178           if (EnableFastISelAbort > 1)
01179             report_fatal_error("FastISel didn't lower all arguments");
01180 
01181           // Use SelectionDAG argument lowering
01182           LowerArguments(Fn);
01183           CurDAG->setRoot(SDB->getControlRoot());
01184           SDB->clear();
01185           CodeGenAndEmitDAG();
01186         }
01187 
01188         // If we inserted any instructions at the beginning, make a note of
01189         // where they are, so we can be sure to emit subsequent instructions
01190         // after them.
01191         if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
01192           FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
01193         else
01194           FastIS->setLastLocalValue(nullptr);
01195       }
01196 
01197       unsigned NumFastIselRemaining = std::distance(Begin, End);
01198       // Do FastISel on as many instructions as possible.
01199       for (; BI != Begin; --BI) {
01200         const Instruction *Inst = std::prev(BI);
01201 
01202         // If we no longer require this instruction, skip it.
01203         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
01204           --NumFastIselRemaining;
01205           continue;
01206         }
01207 
01208         // Bottom-up: reset the insert pos at the top, after any local-value
01209         // instructions.
01210         FastIS->recomputeInsertPt();
01211 
01212         // Try to select the instruction with FastISel.
01213         if (FastIS->selectInstruction(Inst)) {
01214           --NumFastIselRemaining;
01215           ++NumFastIselSuccess;
01216           // If fast isel succeeded, skip over all the folded instructions, and
01217           // then see if there is a load right before the selected instructions.
01218           // Try to fold the load if so.
01219           const Instruction *BeforeInst = Inst;
01220           while (BeforeInst != Begin) {
01221             BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
01222             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
01223               break;
01224           }
01225           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
01226               BeforeInst->hasOneUse() &&
01227               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
01228             // If we succeeded, don't re-select the load.
01229             BI = std::next(BasicBlock::const_iterator(BeforeInst));
01230             --NumFastIselRemaining;
01231             ++NumFastIselSuccess;
01232           }
01233           continue;
01234         }
01235 
01236 #ifndef NDEBUG
01237         if (EnableFastISelVerbose2)
01238           collectFailStats(Inst);
01239 #endif
01240 
01241         // Then handle certain instructions as single-LLVM-Instruction blocks.
01242         if (isa<CallInst>(Inst)) {
01243 
01244           if (EnableFastISelVerbose || EnableFastISelAbort) {
01245             dbgs() << "FastISel missed call: ";
01246             Inst->dump();
01247           }
01248           if (EnableFastISelAbort > 2)
01249             // FastISel selector couldn't handle something and bailed.
01250             // For the purpose of debugging, just abort.
01251             report_fatal_error("FastISel didn't select the entire block");
01252 
01253           if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
01254             unsigned &R = FuncInfo->ValueMap[Inst];
01255             if (!R)
01256               R = FuncInfo->CreateRegs(Inst->getType());
01257           }
01258 
01259           bool HadTailCall = false;
01260           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
01261           SelectBasicBlock(Inst, BI, HadTailCall);
01262 
01263           // If the call was emitted as a tail call, we're done with the block.
01264           // We also need to delete any previously emitted instructions.
01265           if (HadTailCall) {
01266             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
01267             --BI;
01268             break;
01269           }
01270 
01271           // Recompute NumFastIselRemaining as Selection DAG instruction
01272           // selection may have handled the call, input args, etc.
01273           unsigned RemainingNow = std::distance(Begin, BI);
01274           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
01275           NumFastIselRemaining = RemainingNow;
01276           continue;
01277         }
01278 
01279         bool ShouldAbort = EnableFastISelAbort;
01280         if (EnableFastISelVerbose || EnableFastISelAbort) {
01281           if (isa<TerminatorInst>(Inst)) {
01282             // Use a different message for terminator misses.
01283             dbgs() << "FastISel missed terminator: ";
01284             // Don't abort unless for terminator unless the level is really high
01285             ShouldAbort = (EnableFastISelAbort > 2);
01286           } else {
01287             dbgs() << "FastISel miss: ";
01288           }
01289           Inst->dump();
01290         }
01291         if (ShouldAbort)
01292           // FastISel selector couldn't handle something and bailed.
01293           // For the purpose of debugging, just abort.
01294           report_fatal_error("FastISel didn't select the entire block");
01295 
01296         NumFastIselFailures += NumFastIselRemaining;
01297         break;
01298       }
01299 
01300       FastIS->recomputeInsertPt();
01301     } else {
01302       // Lower any arguments needed in this block if this is the entry block.
01303       if (LLVMBB == &Fn.getEntryBlock()) {
01304         ++NumEntryBlocks;
01305         LowerArguments(Fn);
01306       }
01307     }
01308 
01309     if (Begin != BI)
01310       ++NumDAGBlocks;
01311     else
01312       ++NumFastIselBlocks;
01313 
01314     if (Begin != BI) {
01315       // Run SelectionDAG instruction selection on the remainder of the block
01316       // not handled by FastISel. If FastISel is not run, this is the entire
01317       // block.
01318       bool HadTailCall;
01319       SelectBasicBlock(Begin, BI, HadTailCall);
01320     }
01321 
01322     FinishBasicBlock();
01323     FuncInfo->PHINodesToUpdate.clear();
01324   }
01325 
01326   delete FastIS;
01327   SDB->clearDanglingDebugInfo();
01328   SDB->SPDescriptor.resetPerFunctionState();
01329 }
01330 
01331 /// Given that the input MI is before a partial terminator sequence TSeq, return
01332 /// true if M + TSeq also a partial terminator sequence.
01333 ///
01334 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
01335 /// lowering copy vregs into physical registers, which are then passed into
01336 /// terminator instructors so we can satisfy ABI constraints. A partial
01337 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
01338 /// may be the whole terminator sequence).
01339 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
01340   // If we do not have a copy or an implicit def, we return true if and only if
01341   // MI is a debug value.
01342   if (!MI->isCopy() && !MI->isImplicitDef())
01343     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
01344     // physical registers if there is debug info associated with the terminator
01345     // of our mbb. We want to include said debug info in our terminator
01346     // sequence, so we return true in that case.
01347     return MI->isDebugValue();
01348 
01349   // We have left the terminator sequence if we are not doing one of the
01350   // following:
01351   //
01352   // 1. Copying a vreg into a physical register.
01353   // 2. Copying a vreg into a vreg.
01354   // 3. Defining a register via an implicit def.
01355 
01356   // OPI should always be a register definition...
01357   MachineInstr::const_mop_iterator OPI = MI->operands_begin();
01358   if (!OPI->isReg() || !OPI->isDef())
01359     return false;
01360 
01361   // Defining any register via an implicit def is always ok.
01362   if (MI->isImplicitDef())
01363     return true;
01364 
01365   // Grab the copy source...
01366   MachineInstr::const_mop_iterator OPI2 = OPI;
01367   ++OPI2;
01368   assert(OPI2 != MI->operands_end()
01369          && "Should have a copy implying we should have 2 arguments.");
01370 
01371   // Make sure that the copy dest is not a vreg when the copy source is a
01372   // physical register.
01373   if (!OPI2->isReg() ||
01374       (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
01375        TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
01376     return false;
01377 
01378   return true;
01379 }
01380 
01381 /// Find the split point at which to splice the end of BB into its success stack
01382 /// protector check machine basic block.
01383 ///
01384 /// On many platforms, due to ABI constraints, terminators, even before register
01385 /// allocation, use physical registers. This creates an issue for us since
01386 /// physical registers at this point can not travel across basic
01387 /// blocks. Luckily, selectiondag always moves physical registers into vregs
01388 /// when they enter functions and moves them through a sequence of copies back
01389 /// into the physical registers right before the terminator creating a
01390 /// ``Terminator Sequence''. This function is searching for the beginning of the
01391 /// terminator sequence so that we can ensure that we splice off not just the
01392 /// terminator, but additionally the copies that move the vregs into the
01393 /// physical registers.
01394 static MachineBasicBlock::iterator
01395 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
01396   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
01397   //
01398   if (SplitPoint == BB->begin())
01399     return SplitPoint;
01400 
01401   MachineBasicBlock::iterator Start = BB->begin();
01402   MachineBasicBlock::iterator Previous = SplitPoint;
01403   --Previous;
01404 
01405   while (MIIsInTerminatorSequence(Previous)) {
01406     SplitPoint = Previous;
01407     if (Previous == Start)
01408       break;
01409     --Previous;
01410   }
01411 
01412   return SplitPoint;
01413 }
01414 
01415 void
01416 SelectionDAGISel::FinishBasicBlock() {
01417 
01418   DEBUG(dbgs() << "Total amount of phi nodes to update: "
01419                << FuncInfo->PHINodesToUpdate.size() << "\n";
01420         for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
01421           dbgs() << "Node " << i << " : ("
01422                  << FuncInfo->PHINodesToUpdate[i].first
01423                  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
01424 
01425   const bool MustUpdatePHINodes = SDB->SwitchCases.empty() &&
01426                                   SDB->JTCases.empty() &&
01427                                   SDB->BitTestCases.empty();
01428 
01429   // Next, now that we know what the last MBB the LLVM BB expanded is, update
01430   // PHI nodes in successors.
01431   if (MustUpdatePHINodes) {
01432     for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01433       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01434       assert(PHI->isPHI() &&
01435              "This is not a machine PHI node that we are updating!");
01436       if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
01437         continue;
01438       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01439     }
01440   }
01441 
01442   // Handle stack protector.
01443   if (SDB->SPDescriptor.shouldEmitStackProtector()) {
01444     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
01445     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
01446 
01447     // Find the split point to split the parent mbb. At the same time copy all
01448     // physical registers used in the tail of parent mbb into virtual registers
01449     // before the split point and back into physical registers after the split
01450     // point. This prevents us needing to deal with Live-ins and many other
01451     // register allocation issues caused by us splitting the parent mbb. The
01452     // register allocator will clean up said virtual copies later on.
01453     MachineBasicBlock::iterator SplitPoint =
01454       FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
01455 
01456     // Splice the terminator of ParentMBB into SuccessMBB.
01457     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
01458                        SplitPoint,
01459                        ParentMBB->end());
01460 
01461     // Add compare/jump on neq/jump to the parent BB.
01462     FuncInfo->MBB = ParentMBB;
01463     FuncInfo->InsertPt = ParentMBB->end();
01464     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
01465     CurDAG->setRoot(SDB->getRoot());
01466     SDB->clear();
01467     CodeGenAndEmitDAG();
01468 
01469     // CodeGen Failure MBB if we have not codegened it yet.
01470     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
01471     if (!FailureMBB->size()) {
01472       FuncInfo->MBB = FailureMBB;
01473       FuncInfo->InsertPt = FailureMBB->end();
01474       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
01475       CurDAG->setRoot(SDB->getRoot());
01476       SDB->clear();
01477       CodeGenAndEmitDAG();
01478     }
01479 
01480     // Clear the Per-BB State.
01481     SDB->SPDescriptor.resetPerBBState();
01482   }
01483 
01484   // If we updated PHI Nodes, return early.
01485   if (MustUpdatePHINodes)
01486     return;
01487 
01488   for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
01489     // Lower header first, if it wasn't already lowered
01490     if (!SDB->BitTestCases[i].Emitted) {
01491       // Set the current basic block to the mbb we wish to insert the code into
01492       FuncInfo->MBB = SDB->BitTestCases[i].Parent;
01493       FuncInfo->InsertPt = FuncInfo->MBB->end();
01494       // Emit the code
01495       SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
01496       CurDAG->setRoot(SDB->getRoot());
01497       SDB->clear();
01498       CodeGenAndEmitDAG();
01499     }
01500 
01501     uint32_t UnhandledWeight = 0;
01502     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
01503       UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
01504 
01505     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
01506       UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
01507       // Set the current basic block to the mbb we wish to insert the code into
01508       FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01509       FuncInfo->InsertPt = FuncInfo->MBB->end();
01510       // Emit the code
01511       if (j+1 != ej)
01512         SDB->visitBitTestCase(SDB->BitTestCases[i],
01513                               SDB->BitTestCases[i].Cases[j+1].ThisBB,
01514                               UnhandledWeight,
01515                               SDB->BitTestCases[i].Reg,
01516                               SDB->BitTestCases[i].Cases[j],
01517                               FuncInfo->MBB);
01518       else
01519         SDB->visitBitTestCase(SDB->BitTestCases[i],
01520                               SDB->BitTestCases[i].Default,
01521                               UnhandledWeight,
01522                               SDB->BitTestCases[i].Reg,
01523                               SDB->BitTestCases[i].Cases[j],
01524                               FuncInfo->MBB);
01525 
01526 
01527       CurDAG->setRoot(SDB->getRoot());
01528       SDB->clear();
01529       CodeGenAndEmitDAG();
01530     }
01531 
01532     // Update PHI Nodes
01533     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01534          pi != pe; ++pi) {
01535       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01536       MachineBasicBlock *PHIBB = PHI->getParent();
01537       assert(PHI->isPHI() &&
01538              "This is not a machine PHI node that we are updating!");
01539       // This is "default" BB. We have two jumps to it. From "header" BB and
01540       // from last "case" BB.
01541       if (PHIBB == SDB->BitTestCases[i].Default)
01542         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01543            .addMBB(SDB->BitTestCases[i].Parent)
01544            .addReg(FuncInfo->PHINodesToUpdate[pi].second)
01545            .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
01546       // One of "cases" BB.
01547       for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
01548            j != ej; ++j) {
01549         MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01550         if (cBB->isSuccessor(PHIBB))
01551           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
01552       }
01553     }
01554   }
01555   SDB->BitTestCases.clear();
01556 
01557   // If the JumpTable record is filled in, then we need to emit a jump table.
01558   // Updating the PHI nodes is tricky in this case, since we need to determine
01559   // whether the PHI is a successor of the range check MBB or the jump table MBB
01560   for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
01561     // Lower header first, if it wasn't already lowered
01562     if (!SDB->JTCases[i].first.Emitted) {
01563       // Set the current basic block to the mbb we wish to insert the code into
01564       FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
01565       FuncInfo->InsertPt = FuncInfo->MBB->end();
01566       // Emit the code
01567       SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
01568                                 FuncInfo->MBB);
01569       CurDAG->setRoot(SDB->getRoot());
01570       SDB->clear();
01571       CodeGenAndEmitDAG();
01572     }
01573 
01574     // Set the current basic block to the mbb we wish to insert the code into
01575     FuncInfo->MBB = SDB->JTCases[i].second.MBB;
01576     FuncInfo->InsertPt = FuncInfo->MBB->end();
01577     // Emit the code
01578     SDB->visitJumpTable(SDB->JTCases[i].second);
01579     CurDAG->setRoot(SDB->getRoot());
01580     SDB->clear();
01581     CodeGenAndEmitDAG();
01582 
01583     // Update PHI Nodes
01584     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01585          pi != pe; ++pi) {
01586       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01587       MachineBasicBlock *PHIBB = PHI->getParent();
01588       assert(PHI->isPHI() &&
01589              "This is not a machine PHI node that we are updating!");
01590       // "default" BB. We can go there only from header BB.
01591       if (PHIBB == SDB->JTCases[i].second.Default)
01592         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01593            .addMBB(SDB->JTCases[i].first.HeaderBB);
01594       // JT BB. Just iterate over successors here
01595       if (FuncInfo->MBB->isSuccessor(PHIBB))
01596         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
01597     }
01598   }
01599   SDB->JTCases.clear();
01600 
01601   // If the switch block involved a branch to one of the actual successors, we
01602   // need to update PHI nodes in that block.
01603   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01604     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01605     assert(PHI->isPHI() &&
01606            "This is not a machine PHI node that we are updating!");
01607     if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
01608       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01609   }
01610 
01611   // If we generated any switch lowering information, build and codegen any
01612   // additional DAGs necessary.
01613   for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
01614     // Set the current basic block to the mbb we wish to insert the code into
01615     FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
01616     FuncInfo->InsertPt = FuncInfo->MBB->end();
01617 
01618     // Determine the unique successors.
01619     SmallVector<MachineBasicBlock *, 2> Succs;
01620     Succs.push_back(SDB->SwitchCases[i].TrueBB);
01621     if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
01622       Succs.push_back(SDB->SwitchCases[i].FalseBB);
01623 
01624     // Emit the code. Note that this could result in FuncInfo->MBB being split.
01625     SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
01626     CurDAG->setRoot(SDB->getRoot());
01627     SDB->clear();
01628     CodeGenAndEmitDAG();
01629 
01630     // Remember the last block, now that any splitting is done, for use in
01631     // populating PHI nodes in successors.
01632     MachineBasicBlock *ThisBB = FuncInfo->MBB;
01633 
01634     // Handle any PHI nodes in successors of this chunk, as if we were coming
01635     // from the original BB before switch expansion.  Note that PHI nodes can
01636     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
01637     // handle them the right number of times.
01638     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
01639       FuncInfo->MBB = Succs[i];
01640       FuncInfo->InsertPt = FuncInfo->MBB->end();
01641       // FuncInfo->MBB may have been removed from the CFG if a branch was
01642       // constant folded.
01643       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
01644         for (MachineBasicBlock::iterator
01645              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
01646              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
01647           MachineInstrBuilder PHI(*MF, MBBI);
01648           // This value for this PHI node is recorded in PHINodesToUpdate.
01649           for (unsigned pn = 0; ; ++pn) {
01650             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
01651                    "Didn't find PHI entry!");
01652             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
01653               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
01654               break;
01655             }
01656           }
01657         }
01658       }
01659     }
01660   }
01661   SDB->SwitchCases.clear();
01662 }
01663 
01664 
01665 /// Create the scheduler. If a specific scheduler was specified
01666 /// via the SchedulerRegistry, use it, otherwise select the
01667 /// one preferred by the target.
01668 ///
01669 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
01670   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
01671 
01672   if (!Ctor) {
01673     Ctor = ISHeuristic;
01674     RegisterScheduler::setDefault(Ctor);
01675   }
01676 
01677   return Ctor(this, OptLevel);
01678 }
01679 
01680 //===----------------------------------------------------------------------===//
01681 // Helper functions used by the generated instruction selector.
01682 //===----------------------------------------------------------------------===//
01683 // Calls to these methods are generated by tblgen.
01684 
01685 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
01686 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01687 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
01688 /// specified in the .td file (e.g. 255).
01689 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
01690                                     int64_t DesiredMaskS) const {
01691   const APInt &ActualMask = RHS->getAPIntValue();
01692   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01693 
01694   // If the actual mask exactly matches, success!
01695   if (ActualMask == DesiredMask)
01696     return true;
01697 
01698   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01699   if (ActualMask.intersects(~DesiredMask))
01700     return false;
01701 
01702   // Otherwise, the DAG Combiner may have proven that the value coming in is
01703   // either already zero or is not demanded.  Check for known zero input bits.
01704   APInt NeededMask = DesiredMask & ~ActualMask;
01705   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
01706     return true;
01707 
01708   // TODO: check to see if missing bits are just not demanded.
01709 
01710   // Otherwise, this pattern doesn't match.
01711   return false;
01712 }
01713 
01714 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
01715 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01716 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
01717 /// specified in the .td file (e.g. 255).
01718 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
01719                                    int64_t DesiredMaskS) const {
01720   const APInt &ActualMask = RHS->getAPIntValue();
01721   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01722 
01723   // If the actual mask exactly matches, success!
01724   if (ActualMask == DesiredMask)
01725     return true;
01726 
01727   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01728   if (ActualMask.intersects(~DesiredMask))
01729     return false;
01730 
01731   // Otherwise, the DAG Combiner may have proven that the value coming in is
01732   // either already zero or is not demanded.  Check for known zero input bits.
01733   APInt NeededMask = DesiredMask & ~ActualMask;
01734 
01735   APInt KnownZero, KnownOne;
01736   CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
01737 
01738   // If all the missing bits in the or are already known to be set, match!
01739   if ((NeededMask & KnownOne) == NeededMask)
01740     return true;
01741 
01742   // TODO: check to see if missing bits are just not demanded.
01743 
01744   // Otherwise, this pattern doesn't match.
01745   return false;
01746 }
01747 
01748 
01749 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
01750 /// by tblgen.  Others should not call it.
01751 void SelectionDAGISel::
01752 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
01753   std::vector<SDValue> InOps;
01754   std::swap(InOps, Ops);
01755 
01756   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
01757   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
01758   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
01759   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
01760 
01761   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
01762   if (InOps[e-1].getValueType() == MVT::Glue)
01763     --e;  // Don't process a glue operand if it is here.
01764 
01765   while (i != e) {
01766     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
01767     if (!InlineAsm::isMemKind(Flags)) {
01768       // Just skip over this operand, copying the operands verbatim.
01769       Ops.insert(Ops.end(), InOps.begin()+i,
01770                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
01771       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
01772     } else {
01773       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
01774              "Memory operand with multiple values?");
01775 
01776       unsigned TiedToOperand;
01777       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
01778         // We need the constraint ID from the operand this is tied to.
01779         unsigned CurOp = InlineAsm::Op_FirstOperand;
01780         Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
01781         for (; TiedToOperand; --TiedToOperand) {
01782           CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
01783           Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
01784         }
01785       }
01786 
01787       // Otherwise, this is a memory operand.  Ask the target to select it.
01788       std::vector<SDValue> SelOps;
01789       if (SelectInlineAsmMemoryOperand(InOps[i+1],
01790                                        InlineAsm::getMemoryConstraintID(Flags),
01791                                        SelOps))
01792         report_fatal_error("Could not match memory address.  Inline asm"
01793                            " failure!");
01794 
01795       // Add this to the output node.
01796       unsigned NewFlags =
01797         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
01798       Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
01799       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
01800       i += 2;
01801     }
01802   }
01803 
01804   // Add the glue input back if present.
01805   if (e != InOps.size())
01806     Ops.push_back(InOps.back());
01807 }
01808 
01809 /// findGlueUse - Return use of MVT::Glue value produced by the specified
01810 /// SDNode.
01811 ///
01812 static SDNode *findGlueUse(SDNode *N) {
01813   unsigned FlagResNo = N->getNumValues()-1;
01814   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
01815     SDUse &Use = I.getUse();
01816     if (Use.getResNo() == FlagResNo)
01817       return Use.getUser();
01818   }
01819   return nullptr;
01820 }
01821 
01822 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
01823 /// This function recursively traverses up the operand chain, ignoring
01824 /// certain nodes.
01825 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
01826                           SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
01827                           bool IgnoreChains) {
01828   // The NodeID's are given uniques ID's where a node ID is guaranteed to be
01829   // greater than all of its (recursive) operands.  If we scan to a point where
01830   // 'use' is smaller than the node we're scanning for, then we know we will
01831   // never find it.
01832   //
01833   // The Use may be -1 (unassigned) if it is a newly allocated node.  This can
01834   // happen because we scan down to newly selected nodes in the case of glue
01835   // uses.
01836   if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
01837     return false;
01838 
01839   // Don't revisit nodes if we already scanned it and didn't fail, we know we
01840   // won't fail if we scan it again.
01841   if (!Visited.insert(Use).second)
01842     return false;
01843 
01844   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
01845     // Ignore chain uses, they are validated by HandleMergeInputChains.
01846     if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
01847       continue;
01848 
01849     SDNode *N = Use->getOperand(i).getNode();
01850     if (N == Def) {
01851       if (Use == ImmedUse || Use == Root)
01852         continue;  // We are not looking for immediate use.
01853       assert(N != Root);
01854       return true;
01855     }
01856 
01857     // Traverse up the operand chain.
01858     if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
01859       return true;
01860   }
01861   return false;
01862 }
01863 
01864 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
01865 /// operand node N of U during instruction selection that starts at Root.
01866 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
01867                                           SDNode *Root) const {
01868   if (OptLevel == CodeGenOpt::None) return false;
01869   return N.hasOneUse();
01870 }
01871 
01872 /// IsLegalToFold - Returns true if the specific operand node N of
01873 /// U can be folded during instruction selection that starts at Root.
01874 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
01875                                      CodeGenOpt::Level OptLevel,
01876                                      bool IgnoreChains) {
01877   if (OptLevel == CodeGenOpt::None) return false;
01878 
01879   // If Root use can somehow reach N through a path that that doesn't contain
01880   // U then folding N would create a cycle. e.g. In the following
01881   // diagram, Root can reach N through X. If N is folded into into Root, then
01882   // X is both a predecessor and a successor of U.
01883   //
01884   //          [N*]           //
01885   //         ^   ^           //
01886   //        /     \          //
01887   //      [U*]    [X]?       //
01888   //        ^     ^          //
01889   //         \   /           //
01890   //          \ /            //
01891   //         [Root*]         //
01892   //
01893   // * indicates nodes to be folded together.
01894   //
01895   // If Root produces glue, then it gets (even more) interesting. Since it
01896   // will be "glued" together with its glue use in the scheduler, we need to
01897   // check if it might reach N.
01898   //
01899   //          [N*]           //
01900   //         ^   ^           //
01901   //        /     \          //
01902   //      [U*]    [X]?       //
01903   //        ^       ^        //
01904   //         \       \       //
01905   //          \      |       //
01906   //         [Root*] |       //
01907   //          ^      |       //
01908   //          f      |       //
01909   //          |      /       //
01910   //         [Y]    /        //
01911   //           ^   /         //
01912   //           f  /          //
01913   //           | /           //
01914   //          [GU]           //
01915   //
01916   // If GU (glue use) indirectly reaches N (the load), and Root folds N
01917   // (call it Fold), then X is a predecessor of GU and a successor of
01918   // Fold. But since Fold and GU are glued together, this will create
01919   // a cycle in the scheduling graph.
01920 
01921   // If the node has glue, walk down the graph to the "lowest" node in the
01922   // glueged set.
01923   EVT VT = Root->getValueType(Root->getNumValues()-1);
01924   while (VT == MVT::Glue) {
01925     SDNode *GU = findGlueUse(Root);
01926     if (!GU)
01927       break;
01928     Root = GU;
01929     VT = Root->getValueType(Root->getNumValues()-1);
01930 
01931     // If our query node has a glue result with a use, we've walked up it.  If
01932     // the user (which has already been selected) has a chain or indirectly uses
01933     // the chain, our WalkChainUsers predicate will not consider it.  Because of
01934     // this, we cannot ignore chains in this predicate.
01935     IgnoreChains = false;
01936   }
01937 
01938 
01939   SmallPtrSet<SDNode*, 16> Visited;
01940   return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
01941 }
01942 
01943 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
01944   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
01945   SelectInlineAsmMemoryOperands(Ops);
01946 
01947   const EVT VTs[] = {MVT::Other, MVT::Glue};
01948   SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N), VTs, Ops);
01949   New->setNodeId(-1);
01950   return New.getNode();
01951 }
01952 
01953 SDNode
01954 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
01955   SDLoc dl(Op);
01956   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(0));
01957   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01958   unsigned Reg =
01959       TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0));
01960   SDValue New = CurDAG->getCopyFromReg(
01961                         CurDAG->getEntryNode(), dl, Reg, Op->getValueType(0));
01962   New->setNodeId(-1);
01963   return New.getNode();
01964 }
01965 
01966 SDNode
01967 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
01968   SDLoc dl(Op);
01969   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
01970   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01971   unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
01972                                         Op->getOperand(2).getValueType());
01973   SDValue New = CurDAG->getCopyToReg(
01974                         CurDAG->getEntryNode(), dl, Reg, Op->getOperand(2));
01975   New->setNodeId(-1);
01976   return New.getNode();
01977 }
01978 
01979 
01980 
01981 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
01982   return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
01983 }
01984 
01985 /// GetVBR - decode a vbr encoding whose top bit is set.
01986 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
01987 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
01988   assert(Val >= 128 && "Not a VBR");
01989   Val &= 127;  // Remove first vbr bit.
01990 
01991   unsigned Shift = 7;
01992   uint64_t NextBits;
01993   do {
01994     NextBits = MatcherTable[Idx++];
01995     Val |= (NextBits&127) << Shift;
01996     Shift += 7;
01997   } while (NextBits & 128);
01998 
01999   return Val;
02000 }
02001 
02002 
02003 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
02004 /// interior glue and chain results to use the new glue and chain results.
02005 void SelectionDAGISel::
02006 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
02007                     const SmallVectorImpl<SDNode*> &ChainNodesMatched,
02008                     SDValue InputGlue,
02009                     const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
02010                     bool isMorphNodeTo) {
02011   SmallVector<SDNode*, 4> NowDeadNodes;
02012 
02013   // Now that all the normal results are replaced, we replace the chain and
02014   // glue results if present.
02015   if (!ChainNodesMatched.empty()) {
02016     assert(InputChain.getNode() &&
02017            "Matched input chains but didn't produce a chain");
02018     // Loop over all of the nodes we matched that produced a chain result.
02019     // Replace all the chain results with the final chain we ended up with.
02020     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02021       SDNode *ChainNode = ChainNodesMatched[i];
02022 
02023       // If this node was already deleted, don't look at it.
02024       if (ChainNode->getOpcode() == ISD::DELETED_NODE)
02025         continue;
02026 
02027       // Don't replace the results of the root node if we're doing a
02028       // MorphNodeTo.
02029       if (ChainNode == NodeToMatch && isMorphNodeTo)
02030         continue;
02031 
02032       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
02033       if (ChainVal.getValueType() == MVT::Glue)
02034         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
02035       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
02036       CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
02037 
02038       // If the node became dead and we haven't already seen it, delete it.
02039       if (ChainNode->use_empty() &&
02040           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
02041         NowDeadNodes.push_back(ChainNode);
02042     }
02043   }
02044 
02045   // If the result produces glue, update any glue results in the matched
02046   // pattern with the glue result.
02047   if (InputGlue.getNode()) {
02048     // Handle any interior nodes explicitly marked.
02049     for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
02050       SDNode *FRN = GlueResultNodesMatched[i];
02051 
02052       // If this node was already deleted, don't look at it.
02053       if (FRN->getOpcode() == ISD::DELETED_NODE)
02054         continue;
02055 
02056       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
02057              "Doesn't have a glue result");
02058       CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
02059                                         InputGlue);
02060 
02061       // If the node became dead and we haven't already seen it, delete it.
02062       if (FRN->use_empty() &&
02063           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
02064         NowDeadNodes.push_back(FRN);
02065     }
02066   }
02067 
02068   if (!NowDeadNodes.empty())
02069     CurDAG->RemoveDeadNodes(NowDeadNodes);
02070 
02071   DEBUG(dbgs() << "ISEL: Match complete!\n");
02072 }
02073 
02074 enum ChainResult {
02075   CR_Simple,
02076   CR_InducesCycle,
02077   CR_LeadsToInteriorNode
02078 };
02079 
02080 /// WalkChainUsers - Walk down the users of the specified chained node that is
02081 /// part of the pattern we're matching, looking at all of the users we find.
02082 /// This determines whether something is an interior node, whether we have a
02083 /// non-pattern node in between two pattern nodes (which prevent folding because
02084 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
02085 /// between pattern nodes (in which case the TF becomes part of the pattern).
02086 ///
02087 /// The walk we do here is guaranteed to be small because we quickly get down to
02088 /// already selected nodes "below" us.
02089 static ChainResult
02090 WalkChainUsers(const SDNode *ChainedNode,
02091                SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
02092                SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
02093   ChainResult Result = CR_Simple;
02094 
02095   for (SDNode::use_iterator UI = ChainedNode->use_begin(),
02096          E = ChainedNode->use_end(); UI != E; ++UI) {
02097     // Make sure the use is of the chain, not some other value we produce.
02098     if (UI.getUse().getValueType() != MVT::Other) continue;
02099 
02100     SDNode *User = *UI;
02101 
02102     if (User->getOpcode() == ISD::HANDLENODE)  // Root of the graph.
02103       continue;
02104 
02105     // If we see an already-selected machine node, then we've gone beyond the
02106     // pattern that we're selecting down into the already selected chunk of the
02107     // DAG.
02108     unsigned UserOpcode = User->getOpcode();
02109     if (User->isMachineOpcode() ||
02110         UserOpcode == ISD::CopyToReg ||
02111         UserOpcode == ISD::CopyFromReg ||
02112         UserOpcode == ISD::INLINEASM ||
02113         UserOpcode == ISD::EH_LABEL ||
02114         UserOpcode == ISD::LIFETIME_START ||
02115         UserOpcode == ISD::LIFETIME_END) {
02116       // If their node ID got reset to -1 then they've already been selected.
02117       // Treat them like a MachineOpcode.
02118       if (User->getNodeId() == -1)
02119         continue;
02120     }
02121 
02122     // If we have a TokenFactor, we handle it specially.
02123     if (User->getOpcode() != ISD::TokenFactor) {
02124       // If the node isn't a token factor and isn't part of our pattern, then it
02125       // must be a random chained node in between two nodes we're selecting.
02126       // This happens when we have something like:
02127       //   x = load ptr
02128       //   call
02129       //   y = x+4
02130       //   store y -> ptr
02131       // Because we structurally match the load/store as a read/modify/write,
02132       // but the call is chained between them.  We cannot fold in this case
02133       // because it would induce a cycle in the graph.
02134       if (!std::count(ChainedNodesInPattern.begin(),
02135                       ChainedNodesInPattern.end(), User))
02136         return CR_InducesCycle;
02137 
02138       // Otherwise we found a node that is part of our pattern.  For example in:
02139       //   x = load ptr
02140       //   y = x+4
02141       //   store y -> ptr
02142       // This would happen when we're scanning down from the load and see the
02143       // store as a user.  Record that there is a use of ChainedNode that is
02144       // part of the pattern and keep scanning uses.
02145       Result = CR_LeadsToInteriorNode;
02146       InteriorChainedNodes.push_back(User);
02147       continue;
02148     }
02149 
02150     // If we found a TokenFactor, there are two cases to consider: first if the
02151     // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
02152     // uses of the TF are in our pattern) we just want to ignore it.  Second,
02153     // the TokenFactor can be sandwiched in between two chained nodes, like so:
02154     //     [Load chain]
02155     //         ^
02156     //         |
02157     //       [Load]
02158     //       ^    ^
02159     //       |    \                    DAG's like cheese
02160     //      /       \                       do you?
02161     //     /         |
02162     // [TokenFactor] [Op]
02163     //     ^          ^
02164     //     |          |
02165     //      \        /
02166     //       \      /
02167     //       [Store]
02168     //
02169     // In this case, the TokenFactor becomes part of our match and we rewrite it
02170     // as a new TokenFactor.
02171     //
02172     // To distinguish these two cases, do a recursive walk down the uses.
02173     switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
02174     case CR_Simple:
02175       // If the uses of the TokenFactor are just already-selected nodes, ignore
02176       // it, it is "below" our pattern.
02177       continue;
02178     case CR_InducesCycle:
02179       // If the uses of the TokenFactor lead to nodes that are not part of our
02180       // pattern that are not selected, folding would turn this into a cycle,
02181       // bail out now.
02182       return CR_InducesCycle;
02183     case CR_LeadsToInteriorNode:
02184       break;  // Otherwise, keep processing.
02185     }
02186 
02187     // Okay, we know we're in the interesting interior case.  The TokenFactor
02188     // is now going to be considered part of the pattern so that we rewrite its
02189     // uses (it may have uses that are not part of the pattern) with the
02190     // ultimate chain result of the generated code.  We will also add its chain
02191     // inputs as inputs to the ultimate TokenFactor we create.
02192     Result = CR_LeadsToInteriorNode;
02193     ChainedNodesInPattern.push_back(User);
02194     InteriorChainedNodes.push_back(User);
02195     continue;
02196   }
02197 
02198   return Result;
02199 }
02200 
02201 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
02202 /// operation for when the pattern matched at least one node with a chains.  The
02203 /// input vector contains a list of all of the chained nodes that we match.  We
02204 /// must determine if this is a valid thing to cover (i.e. matching it won't
02205 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
02206 /// be used as the input node chain for the generated nodes.
02207 static SDValue
02208 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
02209                        SelectionDAG *CurDAG) {
02210   // Walk all of the chained nodes we've matched, recursively scanning down the
02211   // users of the chain result. This adds any TokenFactor nodes that are caught
02212   // in between chained nodes to the chained and interior nodes list.
02213   SmallVector<SDNode*, 3> InteriorChainedNodes;
02214   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02215     if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
02216                        InteriorChainedNodes) == CR_InducesCycle)
02217       return SDValue(); // Would induce a cycle.
02218   }
02219 
02220   // Okay, we have walked all the matched nodes and collected TokenFactor nodes
02221   // that we are interested in.  Form our input TokenFactor node.
02222   SmallVector<SDValue, 3> InputChains;
02223   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02224     // Add the input chain of this node to the InputChains list (which will be
02225     // the operands of the generated TokenFactor) if it's not an interior node.
02226     SDNode *N = ChainNodesMatched[i];
02227     if (N->getOpcode() != ISD::TokenFactor) {
02228       if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
02229         continue;
02230 
02231       // Otherwise, add the input chain.
02232       SDValue InChain = ChainNodesMatched[i]->getOperand(0);
02233       assert(InChain.getValueType() == MVT::Other && "Not a chain");
02234       InputChains.push_back(InChain);
02235       continue;
02236     }
02237 
02238     // If we have a token factor, we want to add all inputs of the token factor
02239     // that are not part of the pattern we're matching.
02240     for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
02241       if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
02242                       N->getOperand(op).getNode()))
02243         InputChains.push_back(N->getOperand(op));
02244     }
02245   }
02246 
02247   if (InputChains.size() == 1)
02248     return InputChains[0];
02249   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
02250                          MVT::Other, InputChains);
02251 }
02252 
02253 /// MorphNode - Handle morphing a node in place for the selector.
02254 SDNode *SelectionDAGISel::
02255 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
02256           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
02257   // It is possible we're using MorphNodeTo to replace a node with no
02258   // normal results with one that has a normal result (or we could be
02259   // adding a chain) and the input could have glue and chains as well.
02260   // In this case we need to shift the operands down.
02261   // FIXME: This is a horrible hack and broken in obscure cases, no worse
02262   // than the old isel though.
02263   int OldGlueResultNo = -1, OldChainResultNo = -1;
02264 
02265   unsigned NTMNumResults = Node->getNumValues();
02266   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
02267     OldGlueResultNo = NTMNumResults-1;
02268     if (NTMNumResults != 1 &&
02269         Node->getValueType(NTMNumResults-2) == MVT::Other)
02270       OldChainResultNo = NTMNumResults-2;
02271   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
02272     OldChainResultNo = NTMNumResults-1;
02273 
02274   // Call the underlying SelectionDAG routine to do the transmogrification. Note
02275   // that this deletes operands of the old node that become dead.
02276   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
02277 
02278   // MorphNodeTo can operate in two ways: if an existing node with the
02279   // specified operands exists, it can just return it.  Otherwise, it
02280   // updates the node in place to have the requested operands.
02281   if (Res == Node) {
02282     // If we updated the node in place, reset the node ID.  To the isel,
02283     // this should be just like a newly allocated machine node.
02284     Res->setNodeId(-1);
02285   }
02286 
02287   unsigned ResNumResults = Res->getNumValues();
02288   // Move the glue if needed.
02289   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
02290       (unsigned)OldGlueResultNo != ResNumResults-1)
02291     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
02292                                       SDValue(Res, ResNumResults-1));
02293 
02294   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
02295     --ResNumResults;
02296 
02297   // Move the chain reference if needed.
02298   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
02299       (unsigned)OldChainResultNo != ResNumResults-1)
02300     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
02301                                       SDValue(Res, ResNumResults-1));
02302 
02303   // Otherwise, no replacement happened because the node already exists. Replace
02304   // Uses of the old node with the new one.
02305   if (Res != Node)
02306     CurDAG->ReplaceAllUsesWith(Node, Res);
02307 
02308   return Res;
02309 }
02310 
02311 /// CheckSame - Implements OP_CheckSame.
02312 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02313 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02314           SDValue N,
02315           const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02316   // Accept if it is exactly the same as a previously recorded node.
02317   unsigned RecNo = MatcherTable[MatcherIndex++];
02318   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
02319   return N == RecordedNodes[RecNo].first;
02320 }
02321 
02322 /// CheckChildSame - Implements OP_CheckChildXSame.
02323 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02324 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02325              SDValue N,
02326              const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
02327              unsigned ChildNo) {
02328   if (ChildNo >= N.getNumOperands())
02329     return false;  // Match fails if out of range child #.
02330   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
02331                      RecordedNodes);
02332 }
02333 
02334 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
02335 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02336 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02337                       const SelectionDAGISel &SDISel) {
02338   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
02339 }
02340 
02341 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
02342 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02343 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02344                    const SelectionDAGISel &SDISel, SDNode *N) {
02345   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
02346 }
02347 
02348 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02349 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02350             SDNode *N) {
02351   uint16_t Opc = MatcherTable[MatcherIndex++];
02352   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
02353   return N->getOpcode() == Opc;
02354 }
02355 
02356 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02357 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02358           SDValue N, const TargetLowering *TLI) {
02359   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02360   if (N.getValueType() == VT) return true;
02361 
02362   // Handle the case when VT is iPTR.
02363   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
02364 }
02365 
02366 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02367 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02368                SDValue N, const TargetLowering *TLI, unsigned ChildNo) {
02369   if (ChildNo >= N.getNumOperands())
02370     return false;  // Match fails if out of range child #.
02371   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
02372 }
02373 
02374 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02375 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02376               SDValue N) {
02377   return cast<CondCodeSDNode>(N)->get() ==
02378       (ISD::CondCode)MatcherTable[MatcherIndex++];
02379 }
02380 
02381 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02382 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02383                SDValue N, const TargetLowering *TLI) {
02384   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02385   if (cast<VTSDNode>(N)->getVT() == VT)
02386     return true;
02387 
02388   // Handle the case when VT is iPTR.
02389   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
02390 }
02391 
02392 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02393 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02394              SDValue N) {
02395   int64_t Val = MatcherTable[MatcherIndex++];
02396   if (Val & 128)
02397     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02398 
02399   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
02400   return C && C->getSExtValue() == Val;
02401 }
02402 
02403 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02404 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02405                   SDValue N, unsigned ChildNo) {
02406   if (ChildNo >= N.getNumOperands())
02407     return false;  // Match fails if out of range child #.
02408   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
02409 }
02410 
02411 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02412 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02413             SDValue N, const SelectionDAGISel &SDISel) {
02414   int64_t Val = MatcherTable[MatcherIndex++];
02415   if (Val & 128)
02416     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02417 
02418   if (N->getOpcode() != ISD::AND) return false;
02419 
02420   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02421   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
02422 }
02423 
02424 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02425 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02426            SDValue N, const SelectionDAGISel &SDISel) {
02427   int64_t Val = MatcherTable[MatcherIndex++];
02428   if (Val & 128)
02429     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02430 
02431   if (N->getOpcode() != ISD::OR) return false;
02432 
02433   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02434   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
02435 }
02436 
02437 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
02438 /// scope, evaluate the current node.  If the current predicate is known to
02439 /// fail, set Result=true and return anything.  If the current predicate is
02440 /// known to pass, set Result=false and return the MatcherIndex to continue
02441 /// with.  If the current predicate is unknown, set Result=false and return the
02442 /// MatcherIndex to continue with.
02443 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
02444                                        unsigned Index, SDValue N,
02445                                        bool &Result,
02446                                        const SelectionDAGISel &SDISel,
02447                  SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02448   switch (Table[Index++]) {
02449   default:
02450     Result = false;
02451     return Index-1;  // Could not evaluate this predicate.
02452   case SelectionDAGISel::OPC_CheckSame:
02453     Result = !::CheckSame(Table, Index, N, RecordedNodes);
02454     return Index;
02455   case SelectionDAGISel::OPC_CheckChild0Same:
02456   case SelectionDAGISel::OPC_CheckChild1Same:
02457   case SelectionDAGISel::OPC_CheckChild2Same:
02458   case SelectionDAGISel::OPC_CheckChild3Same:
02459     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
02460                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
02461     return Index;
02462   case SelectionDAGISel::OPC_CheckPatternPredicate:
02463     Result = !::CheckPatternPredicate(Table, Index, SDISel);
02464     return Index;
02465   case SelectionDAGISel::OPC_CheckPredicate:
02466     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
02467     return Index;
02468   case SelectionDAGISel::OPC_CheckOpcode:
02469     Result = !::CheckOpcode(Table, Index, N.getNode());
02470     return Index;
02471   case SelectionDAGISel::OPC_CheckType:
02472     Result = !::CheckType(Table, Index, N, SDISel.TLI);
02473     return Index;
02474   case SelectionDAGISel::OPC_CheckChild0Type:
02475   case SelectionDAGISel::OPC_CheckChild1Type:
02476   case SelectionDAGISel::OPC_CheckChild2Type:
02477   case SelectionDAGISel::OPC_CheckChild3Type:
02478   case SelectionDAGISel::OPC_CheckChild4Type:
02479   case SelectionDAGISel::OPC_CheckChild5Type:
02480   case SelectionDAGISel::OPC_CheckChild6Type:
02481   case SelectionDAGISel::OPC_CheckChild7Type:
02482     Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
02483                                Table[Index - 1] -
02484                                    SelectionDAGISel::OPC_CheckChild0Type);
02485     return Index;
02486   case SelectionDAGISel::OPC_CheckCondCode:
02487     Result = !::CheckCondCode(Table, Index, N);
02488     return Index;
02489   case SelectionDAGISel::OPC_CheckValueType:
02490     Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
02491     return Index;
02492   case SelectionDAGISel::OPC_CheckInteger:
02493     Result = !::CheckInteger(Table, Index, N);
02494     return Index;
02495   case SelectionDAGISel::OPC_CheckChild0Integer:
02496   case SelectionDAGISel::OPC_CheckChild1Integer:
02497   case SelectionDAGISel::OPC_CheckChild2Integer:
02498   case SelectionDAGISel::OPC_CheckChild3Integer:
02499   case SelectionDAGISel::OPC_CheckChild4Integer:
02500     Result = !::CheckChildInteger(Table, Index, N,
02501                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
02502     return Index;
02503   case SelectionDAGISel::OPC_CheckAndImm:
02504     Result = !::CheckAndImm(Table, Index, N, SDISel);
02505     return Index;
02506   case SelectionDAGISel::OPC_CheckOrImm:
02507     Result = !::CheckOrImm(Table, Index, N, SDISel);
02508     return Index;
02509   }
02510 }
02511 
02512 namespace {
02513 
02514 struct MatchScope {
02515   /// FailIndex - If this match fails, this is the index to continue with.
02516   unsigned FailIndex;
02517 
02518   /// NodeStack - The node stack when the scope was formed.
02519   SmallVector<SDValue, 4> NodeStack;
02520 
02521   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
02522   unsigned NumRecordedNodes;
02523 
02524   /// NumMatchedMemRefs - The number of matched memref entries.
02525   unsigned NumMatchedMemRefs;
02526 
02527   /// InputChain/InputGlue - The current chain/glue
02528   SDValue InputChain, InputGlue;
02529 
02530   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
02531   bool HasChainNodesMatched, HasGlueResultNodesMatched;
02532 };
02533 
02534 /// \\brief A DAG update listener to keep the matching state
02535 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
02536 /// change the DAG while matching.  X86 addressing mode matcher is an example
02537 /// for this.
02538 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
02539 {
02540       SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes;
02541       SmallVectorImpl<MatchScope> &MatchScopes;
02542 public:
02543   MatchStateUpdater(SelectionDAG &DAG,
02544                     SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN,
02545                     SmallVectorImpl<MatchScope> &MS) :
02546     SelectionDAG::DAGUpdateListener(DAG),
02547     RecordedNodes(RN), MatchScopes(MS) { }
02548 
02549   void NodeDeleted(SDNode *N, SDNode *E) override {
02550     // Some early-returns here to avoid the search if we deleted the node or
02551     // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
02552     // do, so it's unnecessary to update matching state at that point).
02553     // Neither of these can occur currently because we only install this
02554     // update listener during matching a complex patterns.
02555     if (!E || E->isMachineOpcode())
02556       return;
02557     // Performing linear search here does not matter because we almost never
02558     // run this code.  You'd have to have a CSE during complex pattern
02559     // matching.
02560     for (auto &I : RecordedNodes)
02561       if (I.first.getNode() == N)
02562         I.first.setNode(E);
02563 
02564     for (auto &I : MatchScopes)
02565       for (auto &J : I.NodeStack)
02566         if (J.getNode() == N)
02567           J.setNode(E);
02568   }
02569 };
02570 }
02571 
02572 SDNode *SelectionDAGISel::
02573 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
02574                  unsigned TableSize) {
02575   // FIXME: Should these even be selected?  Handle these cases in the caller?
02576   switch (NodeToMatch->getOpcode()) {
02577   default:
02578     break;
02579   case ISD::EntryToken:       // These nodes remain the same.
02580   case ISD::BasicBlock:
02581   case ISD::Register:
02582   case ISD::RegisterMask:
02583   case ISD::HANDLENODE:
02584   case ISD::MDNODE_SDNODE:
02585   case ISD::TargetConstant:
02586   case ISD::TargetConstantFP:
02587   case ISD::TargetConstantPool:
02588   case ISD::TargetFrameIndex:
02589   case ISD::TargetExternalSymbol:
02590   case ISD::TargetBlockAddress:
02591   case ISD::TargetJumpTable:
02592   case ISD::TargetGlobalTLSAddress:
02593   case ISD::TargetGlobalAddress:
02594   case ISD::TokenFactor:
02595   case ISD::CopyFromReg:
02596   case ISD::CopyToReg:
02597   case ISD::EH_LABEL:
02598   case ISD::LIFETIME_START:
02599   case ISD::LIFETIME_END:
02600     NodeToMatch->setNodeId(-1); // Mark selected.
02601     return nullptr;
02602   case ISD::AssertSext:
02603   case ISD::AssertZext:
02604     CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
02605                                       NodeToMatch->getOperand(0));
02606     return nullptr;
02607   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
02608   case ISD::READ_REGISTER: return Select_READ_REGISTER(NodeToMatch);
02609   case ISD::WRITE_REGISTER: return Select_WRITE_REGISTER(NodeToMatch);
02610   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
02611   }
02612 
02613   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
02614 
02615   // Set up the node stack with NodeToMatch as the only node on the stack.
02616   SmallVector<SDValue, 8> NodeStack;
02617   SDValue N = SDValue(NodeToMatch, 0);
02618   NodeStack.push_back(N);
02619 
02620   // MatchScopes - Scopes used when matching, if a match failure happens, this
02621   // indicates where to continue checking.
02622   SmallVector<MatchScope, 8> MatchScopes;
02623 
02624   // RecordedNodes - This is the set of nodes that have been recorded by the
02625   // state machine.  The second value is the parent of the node, or null if the
02626   // root is recorded.
02627   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
02628 
02629   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
02630   // pattern.
02631   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
02632 
02633   // These are the current input chain and glue for use when generating nodes.
02634   // Various Emit operations change these.  For example, emitting a copytoreg
02635   // uses and updates these.
02636   SDValue InputChain, InputGlue;
02637 
02638   // ChainNodesMatched - If a pattern matches nodes that have input/output
02639   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
02640   // which ones they are.  The result is captured into this list so that we can
02641   // update the chain results when the pattern is complete.
02642   SmallVector<SDNode*, 3> ChainNodesMatched;
02643   SmallVector<SDNode*, 3> GlueResultNodesMatched;
02644 
02645   DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
02646         NodeToMatch->dump(CurDAG);
02647         dbgs() << '\n');
02648 
02649   // Determine where to start the interpreter.  Normally we start at opcode #0,
02650   // but if the state machine starts with an OPC_SwitchOpcode, then we
02651   // accelerate the first lookup (which is guaranteed to be hot) with the
02652   // OpcodeOffset table.
02653   unsigned MatcherIndex = 0;
02654 
02655   if (!OpcodeOffset.empty()) {
02656     // Already computed the OpcodeOffset table, just index into it.
02657     if (N.getOpcode() < OpcodeOffset.size())
02658       MatcherIndex = OpcodeOffset[N.getOpcode()];
02659     DEBUG(dbgs() << "  Initial Opcode index to " << MatcherIndex << "\n");
02660 
02661   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
02662     // Otherwise, the table isn't computed, but the state machine does start
02663     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
02664     // is the first time we're selecting an instruction.
02665     unsigned Idx = 1;
02666     while (1) {
02667       // Get the size of this case.
02668       unsigned CaseSize = MatcherTable[Idx++];
02669       if (CaseSize & 128)
02670         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
02671       if (CaseSize == 0) break;
02672 
02673       // Get the opcode, add the index to the table.
02674       uint16_t Opc = MatcherTable[Idx++];
02675       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
02676       if (Opc >= OpcodeOffset.size())
02677         OpcodeOffset.resize((Opc+1)*2);
02678       OpcodeOffset[Opc] = Idx;
02679       Idx += CaseSize;
02680     }
02681 
02682     // Okay, do the lookup for the first opcode.
02683     if (N.getOpcode() < OpcodeOffset.size())
02684       MatcherIndex = OpcodeOffset[N.getOpcode()];
02685   }
02686 
02687   while (1) {
02688     assert(MatcherIndex < TableSize && "Invalid index");
02689 #ifndef NDEBUG
02690     unsigned CurrentOpcodeIndex = MatcherIndex;
02691 #endif
02692     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
02693     switch (Opcode) {
02694     case OPC_Scope: {
02695       // Okay, the semantics of this operation are that we should push a scope
02696       // then evaluate the first child.  However, pushing a scope only to have
02697       // the first check fail (which then pops it) is inefficient.  If we can
02698       // determine immediately that the first check (or first several) will
02699       // immediately fail, don't even bother pushing a scope for them.
02700       unsigned FailIndex;
02701 
02702       while (1) {
02703         unsigned NumToSkip = MatcherTable[MatcherIndex++];
02704         if (NumToSkip & 128)
02705           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
02706         // Found the end of the scope with no match.
02707         if (NumToSkip == 0) {
02708           FailIndex = 0;
02709           break;
02710         }
02711 
02712         FailIndex = MatcherIndex+NumToSkip;
02713 
02714         unsigned MatcherIndexOfPredicate = MatcherIndex;
02715         (void)MatcherIndexOfPredicate; // silence warning.
02716 
02717         // If we can't evaluate this predicate without pushing a scope (e.g. if
02718         // it is a 'MoveParent') or if the predicate succeeds on this node, we
02719         // push the scope and evaluate the full predicate chain.
02720         bool Result;
02721         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
02722                                               Result, *this, RecordedNodes);
02723         if (!Result)
02724           break;
02725 
02726         DEBUG(dbgs() << "  Skipped scope entry (due to false predicate) at "
02727                      << "index " << MatcherIndexOfPredicate
02728                      << ", continuing at " << FailIndex << "\n");
02729         ++NumDAGIselRetries;
02730 
02731         // Otherwise, we know that this case of the Scope is guaranteed to fail,
02732         // move to the next case.
02733         MatcherIndex = FailIndex;
02734       }
02735 
02736       // If the whole scope failed to match, bail.
02737       if (FailIndex == 0) break;
02738 
02739       // Push a MatchScope which indicates where to go if the first child fails
02740       // to match.
02741       MatchScope NewEntry;
02742       NewEntry.FailIndex = FailIndex;
02743       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
02744       NewEntry.NumRecordedNodes = RecordedNodes.size();
02745       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
02746       NewEntry.InputChain = InputChain;
02747       NewEntry.InputGlue = InputGlue;
02748       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
02749       NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
02750       MatchScopes.push_back(NewEntry);
02751       continue;
02752     }
02753     case OPC_RecordNode: {
02754       // Remember this node, it may end up being an operand in the pattern.
02755       SDNode *Parent = nullptr;
02756       if (NodeStack.size() > 1)
02757         Parent = NodeStack[NodeStack.size()-2].getNode();
02758       RecordedNodes.push_back(std::make_pair(N, Parent));
02759       continue;
02760     }
02761 
02762     case OPC_RecordChild0: case OPC_RecordChild1:
02763     case OPC_RecordChild2: case OPC_RecordChild3:
02764     case OPC_RecordChild4: case OPC_RecordChild5:
02765     case OPC_RecordChild6: case OPC_RecordChild7: {
02766       unsigned ChildNo = Opcode-OPC_RecordChild0;
02767       if (ChildNo >= N.getNumOperands())
02768         break;  // Match fails if out of range child #.
02769 
02770       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
02771                                              N.getNode()));
02772       continue;
02773     }
02774     case OPC_RecordMemRef:
02775       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
02776       continue;
02777 
02778     case OPC_CaptureGlueInput:
02779       // If the current node has an input glue, capture it in InputGlue.
02780       if (N->getNumOperands() != 0 &&
02781           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
02782         InputGlue = N->getOperand(N->getNumOperands()-1);
02783       continue;
02784 
02785     case OPC_MoveChild: {
02786       unsigned ChildNo = MatcherTable[MatcherIndex++];
02787       if (ChildNo >= N.getNumOperands())
02788         break;  // Match fails if out of range child #.
02789       N = N.getOperand(ChildNo);
02790       NodeStack.push_back(N);
02791       continue;
02792     }
02793 
02794     case OPC_MoveParent:
02795       // Pop the current node off the NodeStack.
02796       NodeStack.pop_back();
02797       assert(!NodeStack.empty() && "Node stack imbalance!");
02798       N = NodeStack.back();
02799       continue;
02800 
02801     case OPC_CheckSame:
02802       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
02803       continue;
02804 
02805     case OPC_CheckChild0Same: case OPC_CheckChild1Same:
02806     case OPC_CheckChild2Same: case OPC_CheckChild3Same:
02807       if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
02808                             Opcode-OPC_CheckChild0Same))
02809         break;
02810       continue;
02811 
02812     case OPC_CheckPatternPredicate:
02813       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
02814       continue;
02815     case OPC_CheckPredicate:
02816       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
02817                                 N.getNode()))
02818         break;
02819       continue;
02820     case OPC_CheckComplexPat: {
02821       unsigned CPNum = MatcherTable[MatcherIndex++];
02822       unsigned RecNo = MatcherTable[MatcherIndex++];
02823       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
02824 
02825       // If target can modify DAG during matching, keep the matching state
02826       // consistent.
02827       std::unique_ptr<MatchStateUpdater> MSU;
02828       if (ComplexPatternFuncMutatesDAG())
02829         MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes,
02830                                         MatchScopes));
02831 
02832       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
02833                                RecordedNodes[RecNo].first, CPNum,
02834                                RecordedNodes))
02835         break;
02836       continue;
02837     }
02838     case OPC_CheckOpcode:
02839       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
02840       continue;
02841 
02842     case OPC_CheckType:
02843       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI))
02844         break;
02845       continue;
02846 
02847     case OPC_SwitchOpcode: {
02848       unsigned CurNodeOpcode = N.getOpcode();
02849       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
02850       unsigned CaseSize;
02851       while (1) {
02852         // Get the size of this case.
02853         CaseSize = MatcherTable[MatcherIndex++];
02854         if (CaseSize & 128)
02855           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
02856         if (CaseSize == 0) break;
02857 
02858         uint16_t Opc = MatcherTable[MatcherIndex++];
02859         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
02860 
02861         // If the opcode matches, then we will execute this case.
02862         if (CurNodeOpcode == Opc)
02863           break;
02864 
02865         // Otherwise, skip over this case.
02866         MatcherIndex += CaseSize;
02867       }
02868 
02869       // If no cases matched, bail out.
02870       if (CaseSize == 0) break;
02871 
02872       // Otherwise, execute the case we found.
02873       DEBUG(dbgs() << "  OpcodeSwitch from " << SwitchStart
02874                    << " to " << MatcherIndex << "\n");
02875       continue;
02876     }
02877 
02878     case OPC_SwitchType: {
02879       MVT CurNodeVT = N.getSimpleValueType();
02880       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
02881       unsigned CaseSize;
02882       while (1) {
02883         // Get the size of this case.
02884         CaseSize = MatcherTable[MatcherIndex++];
02885         if (CaseSize & 128)
02886           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
02887         if (CaseSize == 0) break;
02888 
02889         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02890         if (CaseVT == MVT::iPTR)
02891           CaseVT = TLI->getPointerTy();
02892 
02893         // If the VT matches, then we will execute this case.
02894         if (CurNodeVT == CaseVT)
02895           break;
02896 
02897         // Otherwise, skip over this case.
02898         MatcherIndex += CaseSize;
02899       }
02900 
02901       // If no cases matched, bail out.
02902       if (CaseSize == 0) break;
02903 
02904       // Otherwise, execute the case we found.
02905       DEBUG(dbgs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
02906                    << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
02907       continue;
02908     }
02909     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
02910     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
02911     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
02912     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
02913       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
02914                             Opcode-OPC_CheckChild0Type))
02915         break;
02916       continue;
02917     case OPC_CheckCondCode:
02918       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
02919       continue;
02920     case OPC_CheckValueType:
02921       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI))
02922         break;
02923       continue;
02924     case OPC_CheckInteger:
02925       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
02926       continue;
02927     case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
02928     case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
02929     case OPC_CheckChild4Integer:
02930       if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
02931                                Opcode-OPC_CheckChild0Integer)) break;
02932       continue;
02933     case OPC_CheckAndImm:
02934       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
02935       continue;
02936     case OPC_CheckOrImm:
02937       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
02938       continue;
02939 
02940     case OPC_CheckFoldableChainNode: {
02941       assert(NodeStack.size() != 1 && "No parent node");
02942       // Verify that all intermediate nodes between the root and this one have
02943       // a single use.
02944       bool HasMultipleUses = false;
02945       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
02946         if (!NodeStack[i].hasOneUse()) {
02947           HasMultipleUses = true;
02948           break;
02949         }
02950       if (HasMultipleUses) break;
02951 
02952       // Check to see that the target thinks this is profitable to fold and that
02953       // we can fold it without inducing cycles in the graph.
02954       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
02955                               NodeToMatch) ||
02956           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
02957                          NodeToMatch, OptLevel,
02958                          true/*We validate our own chains*/))
02959         break;
02960 
02961       continue;
02962     }
02963     case OPC_EmitInteger: {
02964       MVT::SimpleValueType VT =
02965         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02966       int64_t Val = MatcherTable[MatcherIndex++];
02967       if (Val & 128)
02968         Val = GetVBR(Val, MatcherTable, MatcherIndex);
02969       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02970                               CurDAG->getTargetConstant(Val, VT), nullptr));
02971       continue;
02972     }
02973     case OPC_EmitRegister: {
02974       MVT::SimpleValueType VT =
02975         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02976       unsigned RegNo = MatcherTable[MatcherIndex++];
02977       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02978                               CurDAG->getRegister(RegNo, VT), nullptr));
02979       continue;
02980     }
02981     case OPC_EmitRegister2: {
02982       // For targets w/ more than 256 register names, the register enum
02983       // values are stored in two bytes in the matcher table (just like
02984       // opcodes).
02985       MVT::SimpleValueType VT =
02986         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02987       unsigned RegNo = MatcherTable[MatcherIndex++];
02988       RegNo |= MatcherTable[MatcherIndex++] << 8;
02989       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02990                               CurDAG->getRegister(RegNo, VT), nullptr));
02991       continue;
02992     }
02993 
02994     case OPC_EmitConvertToTarget:  {
02995       // Convert from IMM/FPIMM to target version.
02996       unsigned RecNo = MatcherTable[MatcherIndex++];
02997       assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
02998       SDValue Imm = RecordedNodes[RecNo].first;
02999 
03000       if (Imm->getOpcode() == ISD::Constant) {
03001         const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
03002         Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
03003       } else if (Imm->getOpcode() == ISD::ConstantFP) {
03004         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
03005         Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
03006       }
03007 
03008       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
03009       continue;
03010     }
03011 
03012     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
03013     case OPC_EmitMergeInputChains1_1: {  // OPC_EmitMergeInputChains, 1, 1
03014       // These are space-optimized forms of OPC_EmitMergeInputChains.
03015       assert(!InputChain.getNode() &&
03016              "EmitMergeInputChains should be the first chain producing node");
03017       assert(ChainNodesMatched.empty() &&
03018              "Should only have one EmitMergeInputChains per match");
03019 
03020       // Read all of the chained nodes.
03021       unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
03022       assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
03023       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
03024 
03025       // FIXME: What if other value results of the node have uses not matched
03026       // by this pattern?
03027       if (ChainNodesMatched.back() != NodeToMatch &&
03028           !RecordedNodes[RecNo].first.hasOneUse()) {
03029         ChainNodesMatched.clear();
03030         break;
03031       }
03032 
03033       // Merge the input chains if they are not intra-pattern references.
03034       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
03035 
03036       if (!InputChain.getNode())
03037         break;  // Failed to merge.
03038       continue;
03039     }
03040 
03041     case OPC_EmitMergeInputChains: {
03042       assert(!InputChain.getNode() &&
03043              "EmitMergeInputChains should be the first chain producing node");
03044       // This node gets a list of nodes we matched in the input that have
03045       // chains.  We want to token factor all of the input chains to these nodes
03046       // together.  However, if any of the input chains is actually one of the
03047       // nodes matched in this pattern, then we have an intra-match reference.
03048       // Ignore these because the newly token factored chain should not refer to
03049       // the old nodes.
03050       unsigned NumChains = MatcherTable[MatcherIndex++];
03051       assert(NumChains != 0 && "Can't TF zero chains");
03052 
03053       assert(ChainNodesMatched.empty() &&
03054              "Should only have one EmitMergeInputChains per match");
03055 
03056       // Read all of the chained nodes.
03057       for (unsigned i = 0; i != NumChains; ++i) {
03058         unsigned RecNo = MatcherTable[MatcherIndex++];
03059         assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
03060         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
03061 
03062         // FIXME: What if other value results of the node have uses not matched
03063         // by this pattern?
03064         if (ChainNodesMatched.back() != NodeToMatch &&
03065             !RecordedNodes[RecNo].first.hasOneUse()) {
03066           ChainNodesMatched.clear();
03067           break;
03068         }
03069       }
03070 
03071       // If the inner loop broke out, the match fails.
03072       if (ChainNodesMatched.empty())
03073         break;
03074 
03075       // Merge the input chains if they are not intra-pattern references.
03076       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
03077 
03078       if (!InputChain.getNode())
03079         break;  // Failed to merge.
03080 
03081       continue;
03082     }
03083 
03084     case OPC_EmitCopyToReg: {
03085       unsigned RecNo = MatcherTable[MatcherIndex++];
03086       assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
03087       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
03088 
03089       if (!InputChain.getNode())
03090         InputChain = CurDAG->getEntryNode();
03091 
03092       InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
03093                                         DestPhysReg, RecordedNodes[RecNo].first,
03094                                         InputGlue);
03095 
03096       InputGlue = InputChain.getValue(1);
03097       continue;
03098     }
03099 
03100     case OPC_EmitNodeXForm: {
03101       unsigned XFormNo = MatcherTable[MatcherIndex++];
03102       unsigned RecNo = MatcherTable[MatcherIndex++];
03103       assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
03104       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
03105       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
03106       continue;
03107     }
03108 
03109     case OPC_EmitNode:
03110     case OPC_MorphNodeTo: {
03111       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
03112       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
03113       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
03114       // Get the result VT list.
03115       unsigned NumVTs = MatcherTable[MatcherIndex++];
03116       SmallVector<EVT, 4> VTs;
03117       for (unsigned i = 0; i != NumVTs; ++i) {
03118         MVT::SimpleValueType VT =
03119           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
03120         if (VT == MVT::iPTR)
03121           VT = TLI->getPointerTy().SimpleTy;
03122         VTs.push_back(VT);
03123       }
03124 
03125       if (EmitNodeInfo & OPFL_Chain)
03126         VTs.push_back(MVT::Other);
03127       if (EmitNodeInfo & OPFL_GlueOutput)
03128         VTs.push_back(MVT::Glue);
03129 
03130       // This is hot code, so optimize the two most common cases of 1 and 2
03131       // results.
03132       SDVTList VTList;
03133       if (VTs.size() == 1)
03134         VTList = CurDAG->getVTList(VTs[0]);
03135       else if (VTs.size() == 2)
03136         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
03137       else
03138         VTList = CurDAG->getVTList(VTs);
03139 
03140       // Get the operand list.
03141       unsigned NumOps = MatcherTable[MatcherIndex++];
03142       SmallVector<SDValue, 8> Ops;
03143       for (unsigned i = 0; i != NumOps; ++i) {
03144         unsigned RecNo = MatcherTable[MatcherIndex++];
03145         if (RecNo & 128)
03146           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
03147 
03148         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
03149         Ops.push_back(RecordedNodes[RecNo].first);
03150       }
03151 
03152       // If there are variadic operands to add, handle them now.
03153       if (EmitNodeInfo & OPFL_VariadicInfo) {
03154         // Determine the start index to copy from.
03155         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
03156         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
03157         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
03158                "Invalid variadic node");
03159         // Copy all of the variadic operands, not including a potential glue
03160         // input.
03161         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
03162              i != e; ++i) {
03163           SDValue V = NodeToMatch->getOperand(i);
03164           if (V.getValueType() == MVT::Glue) break;
03165           Ops.push_back(V);
03166         }
03167       }
03168 
03169       // If this has chain/glue inputs, add them.
03170       if (EmitNodeInfo & OPFL_Chain)
03171         Ops.push_back(InputChain);
03172       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
03173         Ops.push_back(InputGlue);
03174 
03175       // Create the node.
03176       SDNode *Res = nullptr;
03177       if (Opcode != OPC_MorphNodeTo) {
03178         // If this is a normal EmitNode command, just create the new node and
03179         // add the results to the RecordedNodes list.
03180         Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
03181                                      VTList, Ops);
03182 
03183         // Add all the non-glue/non-chain results to the RecordedNodes list.
03184         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
03185           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
03186           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
03187                                                              nullptr));
03188         }
03189 
03190       } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
03191         Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
03192       } else {
03193         // NodeToMatch was eliminated by CSE when the target changed the DAG.
03194         // We will visit the equivalent node later.
03195         DEBUG(dbgs() << "Node was eliminated by CSE\n");
03196         return nullptr;
03197       }
03198 
03199       // If the node had chain/glue results, update our notion of the current
03200       // chain and glue.
03201       if (EmitNodeInfo & OPFL_GlueOutput) {
03202         InputGlue = SDValue(Res, VTs.size()-1);
03203         if (EmitNodeInfo & OPFL_Chain)
03204           InputChain = SDValue(Res, VTs.size()-2);
03205       } else if (EmitNodeInfo & OPFL_Chain)
03206         InputChain = SDValue(Res, VTs.size()-1);
03207 
03208       // If the OPFL_MemRefs glue is set on this node, slap all of the
03209       // accumulated memrefs onto it.
03210       //
03211       // FIXME: This is vastly incorrect for patterns with multiple outputs
03212       // instructions that access memory and for ComplexPatterns that match
03213       // loads.
03214       if (EmitNodeInfo & OPFL_MemRefs) {
03215         // Only attach load or store memory operands if the generated
03216         // instruction may load or store.
03217         const MCInstrDesc &MCID = TII->get(TargetOpc);
03218         bool mayLoad = MCID.mayLoad();
03219         bool mayStore = MCID.mayStore();
03220 
03221         unsigned NumMemRefs = 0;
03222         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03223                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03224           if ((*I)->isLoad()) {
03225             if (mayLoad)
03226               ++NumMemRefs;
03227           } else if ((*I)->isStore()) {
03228             if (mayStore)
03229               ++NumMemRefs;
03230           } else {
03231             ++NumMemRefs;
03232           }
03233         }
03234 
03235         MachineSDNode::mmo_iterator MemRefs =
03236           MF->allocateMemRefsArray(NumMemRefs);
03237 
03238         MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
03239         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03240                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03241           if ((*I)->isLoad()) {
03242             if (mayLoad)
03243               *MemRefsPos++ = *I;
03244           } else if ((*I)->isStore()) {
03245             if (mayStore)
03246               *MemRefsPos++ = *I;
03247           } else {
03248             *MemRefsPos++ = *I;
03249           }
03250         }
03251 
03252         cast<MachineSDNode>(Res)
03253           ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
03254       }
03255 
03256       DEBUG(dbgs() << "  "
03257                    << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
03258                    << " node: "; Res->dump(CurDAG); dbgs() << "\n");
03259 
03260       // If this was a MorphNodeTo then we're completely done!
03261       if (Opcode == OPC_MorphNodeTo) {
03262         // Update chain and glue uses.
03263         UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03264                             InputGlue, GlueResultNodesMatched, true);
03265         return Res;
03266       }
03267 
03268       continue;
03269     }
03270 
03271     case OPC_MarkGlueResults: {
03272       unsigned NumNodes = MatcherTable[MatcherIndex++];
03273 
03274       // Read and remember all the glue-result nodes.
03275       for (unsigned i = 0; i != NumNodes; ++i) {
03276         unsigned RecNo = MatcherTable[MatcherIndex++];
03277         if (RecNo & 128)
03278           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
03279 
03280         assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
03281         GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
03282       }
03283       continue;
03284     }
03285 
03286     case OPC_CompleteMatch: {
03287       // The match has been completed, and any new nodes (if any) have been
03288       // created.  Patch up references to the matched dag to use the newly
03289       // created nodes.
03290       unsigned NumResults = MatcherTable[MatcherIndex++];
03291 
03292       for (unsigned i = 0; i != NumResults; ++i) {
03293         unsigned ResSlot = MatcherTable[MatcherIndex++];
03294         if (ResSlot & 128)
03295           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
03296 
03297         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
03298         SDValue Res = RecordedNodes[ResSlot].first;
03299 
03300         assert(i < NodeToMatch->getNumValues() &&
03301                NodeToMatch->getValueType(i) != MVT::Other &&
03302                NodeToMatch->getValueType(i) != MVT::Glue &&
03303                "Invalid number of results to complete!");
03304         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
03305                 NodeToMatch->getValueType(i) == MVT::iPTR ||
03306                 Res.getValueType() == MVT::iPTR ||
03307                 NodeToMatch->getValueType(i).getSizeInBits() ==
03308                     Res.getValueType().getSizeInBits()) &&
03309                "invalid replacement");
03310         CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
03311       }
03312 
03313       // If the root node defines glue, add it to the glue nodes to update list.
03314       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
03315         GlueResultNodesMatched.push_back(NodeToMatch);
03316 
03317       // Update chain and glue uses.
03318       UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03319                           InputGlue, GlueResultNodesMatched, false);
03320 
03321       assert(NodeToMatch->use_empty() &&
03322              "Didn't replace all uses of the node?");
03323 
03324       // FIXME: We just return here, which interacts correctly with SelectRoot
03325       // above.  We should fix this to not return an SDNode* anymore.
03326       return nullptr;
03327     }
03328     }
03329 
03330     // If the code reached this point, then the match failed.  See if there is
03331     // another child to try in the current 'Scope', otherwise pop it until we
03332     // find a case to check.
03333     DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex << "\n");
03334     ++NumDAGIselRetries;
03335     while (1) {
03336       if (MatchScopes.empty()) {
03337         CannotYetSelect(NodeToMatch);
03338         return nullptr;
03339       }
03340 
03341       // Restore the interpreter state back to the point where the scope was
03342       // formed.
03343       MatchScope &LastScope = MatchScopes.back();
03344       RecordedNodes.resize(LastScope.NumRecordedNodes);
03345       NodeStack.clear();
03346       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
03347       N = NodeStack.back();
03348 
03349       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
03350         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
03351       MatcherIndex = LastScope.FailIndex;
03352 
03353       DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
03354 
03355       InputChain = LastScope.InputChain;
03356       InputGlue = LastScope.InputGlue;
03357       if (!LastScope.HasChainNodesMatched)
03358         ChainNodesMatched.clear();
03359       if (!LastScope.HasGlueResultNodesMatched)
03360         GlueResultNodesMatched.clear();
03361 
03362       // Check to see what the offset is at the new MatcherIndex.  If it is zero
03363       // we have reached the end of this scope, otherwise we have another child
03364       // in the current scope to try.
03365       unsigned NumToSkip = MatcherTable[MatcherIndex++];
03366       if (NumToSkip & 128)
03367         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
03368 
03369       // If we have another child in this scope to match, update FailIndex and
03370       // try it.
03371       if (NumToSkip != 0) {
03372         LastScope.FailIndex = MatcherIndex+NumToSkip;
03373         break;
03374       }
03375 
03376       // End of this scope, pop it and try the next child in the containing
03377       // scope.
03378       MatchScopes.pop_back();
03379     }
03380   }
03381 }
03382 
03383 
03384 
03385 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
03386   std::string msg;
03387   raw_string_ostream Msg(msg);
03388   Msg << "Cannot select: ";
03389 
03390   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
03391       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
03392       N->getOpcode() != ISD::INTRINSIC_VOID) {
03393     N->printrFull(Msg, CurDAG);
03394     Msg << "\nIn function: " << MF->getName();
03395   } else {
03396     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
03397     unsigned iid =
03398       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
03399     if (iid < Intrinsic::num_intrinsics)
03400       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
03401     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
03402       Msg << "target intrinsic %" << TII->getName(iid);
03403     else
03404       Msg << "unknown intrinsic #" << iid;
03405   }
03406   report_fatal_error(Msg.str());
03407 }
03408 
03409 char SelectionDAGISel::ID = 0;