LLVM API Documentation

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