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