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