1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements the SelectionDAGISel class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/SelectionDAG.h" 15 #include "ScheduleDAGSDNodes.h" 16 #include "SelectionDAGBuilder.h" 17 #include "llvm/ADT/PostOrderIterator.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Analysis/BranchProbabilityInfo.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/EHPersonalities.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/CodeGen/FastISel.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GCMetadata.h" 27 #include "llvm/CodeGen/GCStrategy.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstrBuilder.h" 31 #include "llvm/CodeGen/MachineModuleInfo.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 34 #include "llvm/CodeGen/SchedulerRegistry.h" 35 #include "llvm/CodeGen/SelectionDAGISel.h" 36 #include "llvm/CodeGen/StackProtector.h" 37 #include "llvm/CodeGen/WinEHFuncInfo.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DebugInfo.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/InlineAsm.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/Intrinsics.h" 45 #include "llvm/IR/LLVMContext.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/MC/MCAsmInfo.h" 48 #include "llvm/Support/Compiler.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/ErrorHandling.h" 51 #include "llvm/Support/Timer.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Target/TargetInstrInfo.h" 54 #include "llvm/Target/TargetIntrinsicInfo.h" 55 #include "llvm/Target/TargetLowering.h" 56 #include "llvm/Target/TargetMachine.h" 57 #include "llvm/Target/TargetOptions.h" 58 #include "llvm/Target/TargetRegisterInfo.h" 59 #include "llvm/Target/TargetSubtargetInfo.h" 60 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 61 #include <algorithm> 62 63 using namespace llvm; 64 65 #define DEBUG_TYPE "isel" 66 67 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on"); 68 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected"); 69 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel"); 70 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG"); 71 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path"); 72 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered"); 73 STATISTIC(NumFastIselFailLowerArguments, 74 "Number of entry blocks where fast isel failed to lower arguments"); 75 76 #ifndef NDEBUG 77 static cl::opt<bool> 78 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden, 79 cl::desc("Enable extra verbose messages in the \"fast\" " 80 "instruction selector")); 81 82 // Terminators 83 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret"); 84 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br"); 85 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch"); 86 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr"); 87 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke"); 88 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume"); 89 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable"); 90 91 // Standard binary operators... 92 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add"); 93 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd"); 94 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub"); 95 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub"); 96 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul"); 97 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul"); 98 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv"); 99 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv"); 100 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv"); 101 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem"); 102 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem"); 103 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem"); 104 105 // Logical operators... 106 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And"); 107 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or"); 108 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor"); 109 110 // Memory instructions... 111 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca"); 112 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load"); 113 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store"); 114 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg"); 115 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM"); 116 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence"); 117 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr"); 118 119 // Convert instructions... 120 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc"); 121 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt"); 122 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt"); 123 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc"); 124 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt"); 125 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI"); 126 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI"); 127 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP"); 128 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP"); 129 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr"); 130 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt"); 131 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast"); 132 133 // Other instructions... 134 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp"); 135 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp"); 136 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI"); 137 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select"); 138 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call"); 139 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl"); 140 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr"); 141 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr"); 142 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg"); 143 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement"); 144 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement"); 145 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector"); 146 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue"); 147 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue"); 148 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad"); 149 150 // Intrinsic instructions... 151 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call"); 152 STATISTIC(NumFastIselFailSAddWithOverflow, 153 "Fast isel fails on sadd.with.overflow"); 154 STATISTIC(NumFastIselFailUAddWithOverflow, 155 "Fast isel fails on uadd.with.overflow"); 156 STATISTIC(NumFastIselFailSSubWithOverflow, 157 "Fast isel fails on ssub.with.overflow"); 158 STATISTIC(NumFastIselFailUSubWithOverflow, 159 "Fast isel fails on usub.with.overflow"); 160 STATISTIC(NumFastIselFailSMulWithOverflow, 161 "Fast isel fails on smul.with.overflow"); 162 STATISTIC(NumFastIselFailUMulWithOverflow, 163 "Fast isel fails on umul.with.overflow"); 164 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress"); 165 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call"); 166 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call"); 167 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call"); 168 #endif 169 170 static cl::opt<bool> 171 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden, 172 cl::desc("Enable verbose messages in the \"fast\" " 173 "instruction selector")); 174 static cl::opt<int> EnableFastISelAbort( 175 "fast-isel-abort", cl::Hidden, 176 cl::desc("Enable abort calls when \"fast\" instruction selection " 177 "fails to lower an instruction: 0 disable the abort, 1 will " 178 "abort but for args, calls and terminators, 2 will also " 179 "abort for argument lowering, and 3 will never fallback " 180 "to SelectionDAG.")); 181 182 static cl::opt<bool> 183 UseMBPI("use-mbpi", 184 cl::desc("use Machine Branch Probability Info"), 185 cl::init(true), cl::Hidden); 186 187 #ifndef NDEBUG 188 static cl::opt<std::string> 189 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, 190 cl::desc("Only display the basic block whose name " 191 "matches this for all view-*-dags options")); 192 static cl::opt<bool> 193 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, 194 cl::desc("Pop up a window to show dags before the first " 195 "dag combine pass")); 196 static cl::opt<bool> 197 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, 198 cl::desc("Pop up a window to show dags before legalize types")); 199 static cl::opt<bool> 200 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, 201 cl::desc("Pop up a window to show dags before legalize")); 202 static cl::opt<bool> 203 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, 204 cl::desc("Pop up a window to show dags before the second " 205 "dag combine pass")); 206 static cl::opt<bool> 207 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, 208 cl::desc("Pop up a window to show dags before the post legalize types" 209 " dag combine pass")); 210 static cl::opt<bool> 211 ViewISelDAGs("view-isel-dags", cl::Hidden, 212 cl::desc("Pop up a window to show isel dags as they are selected")); 213 static cl::opt<bool> 214 ViewSchedDAGs("view-sched-dags", cl::Hidden, 215 cl::desc("Pop up a window to show sched dags as they are processed")); 216 static cl::opt<bool> 217 ViewSUnitDAGs("view-sunit-dags", cl::Hidden, 218 cl::desc("Pop up a window to show SUnit dags after they are processed")); 219 #else 220 static const bool ViewDAGCombine1 = false, 221 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false, 222 ViewDAGCombine2 = false, 223 ViewDAGCombineLT = false, 224 ViewISelDAGs = false, ViewSchedDAGs = false, 225 ViewSUnitDAGs = false; 226 #endif 227 228 //===---------------------------------------------------------------------===// 229 /// 230 /// RegisterScheduler class - Track the registration of instruction schedulers. 231 /// 232 //===---------------------------------------------------------------------===// 233 MachinePassRegistry RegisterScheduler::Registry; 234 235 //===---------------------------------------------------------------------===// 236 /// 237 /// ISHeuristic command line option for instruction schedulers. 238 /// 239 //===---------------------------------------------------------------------===// 240 static cl::opt<RegisterScheduler::FunctionPassCtor, false, 241 RegisterPassParser<RegisterScheduler> > 242 ISHeuristic("pre-RA-sched", 243 cl::init(&createDefaultScheduler), cl::Hidden, 244 cl::desc("Instruction schedulers available (before register" 245 " allocation):")); 246 247 static RegisterScheduler 248 defaultListDAGScheduler("default", "Best scheduler for the target", 249 createDefaultScheduler); 250 251 namespace llvm { 252 //===--------------------------------------------------------------------===// 253 /// \brief This class is used by SelectionDAGISel to temporarily override 254 /// the optimization level on a per-function basis. 255 class OptLevelChanger { 256 SelectionDAGISel &IS; 257 CodeGenOpt::Level SavedOptLevel; 258 bool SavedFastISel; 259 260 public: 261 OptLevelChanger(SelectionDAGISel &ISel, 262 CodeGenOpt::Level NewOptLevel) : IS(ISel) { 263 SavedOptLevel = IS.OptLevel; 264 if (NewOptLevel == SavedOptLevel) 265 return; 266 IS.OptLevel = NewOptLevel; 267 IS.TM.setOptLevel(NewOptLevel); 268 DEBUG(dbgs() << "\nChanging optimization level for Function " 269 << IS.MF->getFunction()->getName() << "\n"); 270 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel 271 << " ; After: -O" << NewOptLevel << "\n"); 272 SavedFastISel = IS.TM.Options.EnableFastISel; 273 if (NewOptLevel == CodeGenOpt::None) { 274 IS.TM.setFastISel(IS.TM.getO0WantsFastISel()); 275 DEBUG(dbgs() << "\tFastISel is " 276 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled") 277 << "\n"); 278 } 279 } 280 281 ~OptLevelChanger() { 282 if (IS.OptLevel == SavedOptLevel) 283 return; 284 DEBUG(dbgs() << "\nRestoring optimization level for Function " 285 << IS.MF->getFunction()->getName() << "\n"); 286 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel 287 << " ; After: -O" << SavedOptLevel << "\n"); 288 IS.OptLevel = SavedOptLevel; 289 IS.TM.setOptLevel(SavedOptLevel); 290 IS.TM.setFastISel(SavedFastISel); 291 } 292 }; 293 294 //===--------------------------------------------------------------------===// 295 /// createDefaultScheduler - This creates an instruction scheduler appropriate 296 /// for the target. 297 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS, 298 CodeGenOpt::Level OptLevel) { 299 const TargetLowering *TLI = IS->TLI; 300 const TargetSubtargetInfo &ST = IS->MF->getSubtarget(); 301 302 // Try first to see if the Target has its own way of selecting a scheduler 303 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) { 304 return SchedulerCtor(IS, OptLevel); 305 } 306 307 if (OptLevel == CodeGenOpt::None || 308 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) || 309 TLI->getSchedulingPreference() == Sched::Source) 310 return createSourceListDAGScheduler(IS, OptLevel); 311 if (TLI->getSchedulingPreference() == Sched::RegPressure) 312 return createBURRListDAGScheduler(IS, OptLevel); 313 if (TLI->getSchedulingPreference() == Sched::Hybrid) 314 return createHybridListDAGScheduler(IS, OptLevel); 315 if (TLI->getSchedulingPreference() == Sched::VLIW) 316 return createVLIWDAGScheduler(IS, OptLevel); 317 assert(TLI->getSchedulingPreference() == Sched::ILP && 318 "Unknown sched type!"); 319 return createILPListDAGScheduler(IS, OptLevel); 320 } 321 } // end namespace llvm 322 323 // EmitInstrWithCustomInserter - This method should be implemented by targets 324 // that mark instructions with the 'usesCustomInserter' flag. These 325 // instructions are special in various ways, which require special support to 326 // insert. The specified MachineInstr is created but not inserted into any 327 // basic blocks, and this method is called to expand it into a sequence of 328 // instructions, potentially also creating new basic blocks and control flow. 329 // When new basic blocks are inserted and the edges from MBB to its successors 330 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the 331 // DenseMap. 332 MachineBasicBlock * 333 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 334 MachineBasicBlock *MBB) const { 335 #ifndef NDEBUG 336 dbgs() << "If a target marks an instruction with " 337 "'usesCustomInserter', it must implement " 338 "TargetLowering::EmitInstrWithCustomInserter!"; 339 #endif 340 llvm_unreachable(nullptr); 341 } 342 343 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 344 SDNode *Node) const { 345 assert(!MI.hasPostISelHook() && 346 "If a target marks an instruction with 'hasPostISelHook', " 347 "it must implement TargetLowering::AdjustInstrPostInstrSelection!"); 348 } 349 350 //===----------------------------------------------------------------------===// 351 // SelectionDAGISel code 352 //===----------------------------------------------------------------------===// 353 354 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, 355 CodeGenOpt::Level OL) : 356 MachineFunctionPass(ID), TM(tm), 357 FuncInfo(new FunctionLoweringInfo()), 358 CurDAG(new SelectionDAG(tm, OL)), 359 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)), 360 GFI(), 361 OptLevel(OL), 362 DAGSize(0) { 363 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry()); 364 initializeBranchProbabilityInfoWrapperPassPass( 365 *PassRegistry::getPassRegistry()); 366 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 367 initializeTargetLibraryInfoWrapperPassPass( 368 *PassRegistry::getPassRegistry()); 369 } 370 371 SelectionDAGISel::~SelectionDAGISel() { 372 delete SDB; 373 delete CurDAG; 374 delete FuncInfo; 375 } 376 377 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 378 AU.addRequired<AAResultsWrapperPass>(); 379 AU.addRequired<GCModuleInfo>(); 380 AU.addRequired<StackProtector>(); 381 AU.addPreserved<StackProtector>(); 382 AU.addPreserved<GCModuleInfo>(); 383 AU.addRequired<TargetLibraryInfoWrapperPass>(); 384 if (UseMBPI && OptLevel != CodeGenOpt::None) 385 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 386 MachineFunctionPass::getAnalysisUsage(AU); 387 } 388 389 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that 390 /// may trap on it. In this case we have to split the edge so that the path 391 /// through the predecessor block that doesn't go to the phi block doesn't 392 /// execute the possibly trapping instruction. 393 /// 394 /// This is required for correctness, so it must be done at -O0. 395 /// 396 static void SplitCriticalSideEffectEdges(Function &Fn) { 397 // Loop for blocks with phi nodes. 398 for (BasicBlock &BB : Fn) { 399 PHINode *PN = dyn_cast<PHINode>(BB.begin()); 400 if (!PN) continue; 401 402 ReprocessBlock: 403 // For each block with a PHI node, check to see if any of the input values 404 // are potentially trapping constant expressions. Constant expressions are 405 // the only potentially trapping value that can occur as the argument to a 406 // PHI. 407 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I) 408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 409 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i)); 410 if (!CE || !CE->canTrap()) continue; 411 412 // The only case we have to worry about is when the edge is critical. 413 // Since this block has a PHI Node, we assume it has multiple input 414 // edges: check to see if the pred has multiple successors. 415 BasicBlock *Pred = PN->getIncomingBlock(i); 416 if (Pred->getTerminator()->getNumSuccessors() == 1) 417 continue; 418 419 // Okay, we have to split this edge. 420 SplitCriticalEdge( 421 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB), 422 CriticalEdgeSplittingOptions().setMergeIdenticalEdges()); 423 goto ReprocessBlock; 424 } 425 } 426 } 427 428 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { 429 // If we already selected that function, we do not need to run SDISel. 430 if (mf.getProperties().hasProperty( 431 MachineFunctionProperties::Property::Selected)) 432 return false; 433 // Do some sanity-checking on the command-line options. 434 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) && 435 "-fast-isel-verbose requires -fast-isel"); 436 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) && 437 "-fast-isel-abort > 0 requires -fast-isel"); 438 439 const Function &Fn = *mf.getFunction(); 440 MF = &mf; 441 442 // Reset the target options before resetting the optimization 443 // level below. 444 // FIXME: This is a horrible hack and should be processed via 445 // codegen looking at the optimization level explicitly when 446 // it wants to look at it. 447 TM.resetTargetOptions(Fn); 448 // Reset OptLevel to None for optnone functions. 449 CodeGenOpt::Level NewOptLevel = OptLevel; 450 if (OptLevel != CodeGenOpt::None && skipFunction(Fn)) 451 NewOptLevel = CodeGenOpt::None; 452 OptLevelChanger OLC(*this, NewOptLevel); 453 454 TII = MF->getSubtarget().getInstrInfo(); 455 TLI = MF->getSubtarget().getTargetLowering(); 456 RegInfo = &MF->getRegInfo(); 457 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 458 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 459 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr; 460 461 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n"); 462 463 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn)); 464 465 CurDAG->init(*MF); 466 FuncInfo->set(Fn, *MF, CurDAG); 467 468 if (UseMBPI && OptLevel != CodeGenOpt::None) 469 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 470 else 471 FuncInfo->BPI = nullptr; 472 473 SDB->init(GFI, *AA, LibInfo); 474 475 MF->setHasInlineAsm(false); 476 477 FuncInfo->SplitCSR = false; 478 479 // We split CSR if the target supports it for the given function 480 // and the function has only return exits. 481 if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) { 482 FuncInfo->SplitCSR = true; 483 484 // Collect all the return blocks. 485 for (const BasicBlock &BB : Fn) { 486 if (!succ_empty(&BB)) 487 continue; 488 489 const TerminatorInst *Term = BB.getTerminator(); 490 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term)) 491 continue; 492 493 // Bail out if the exit block is not Return nor Unreachable. 494 FuncInfo->SplitCSR = false; 495 break; 496 } 497 } 498 499 MachineBasicBlock *EntryMBB = &MF->front(); 500 if (FuncInfo->SplitCSR) 501 // This performs initialization so lowering for SplitCSR will be correct. 502 TLI->initializeSplitCSR(EntryMBB); 503 504 SelectAllBasicBlocks(Fn); 505 506 // If the first basic block in the function has live ins that need to be 507 // copied into vregs, emit the copies into the top of the block before 508 // emitting the code for the block. 509 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); 510 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII); 511 512 // Insert copies in the entry block and the return blocks. 513 if (FuncInfo->SplitCSR) { 514 SmallVector<MachineBasicBlock*, 4> Returns; 515 // Collect all the return blocks. 516 for (MachineBasicBlock &MBB : mf) { 517 if (!MBB.succ_empty()) 518 continue; 519 520 MachineBasicBlock::iterator Term = MBB.getFirstTerminator(); 521 if (Term != MBB.end() && Term->isReturn()) { 522 Returns.push_back(&MBB); 523 continue; 524 } 525 } 526 TLI->insertCopiesSplitCSR(EntryMBB, Returns); 527 } 528 529 DenseMap<unsigned, unsigned> LiveInMap; 530 if (!FuncInfo->ArgDbgValues.empty()) 531 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(), 532 E = RegInfo->livein_end(); LI != E; ++LI) 533 if (LI->second) 534 LiveInMap.insert(std::make_pair(LI->first, LI->second)); 535 536 // Insert DBG_VALUE instructions for function arguments to the entry block. 537 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) { 538 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1]; 539 bool hasFI = MI->getOperand(0).isFI(); 540 unsigned Reg = 541 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg(); 542 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 543 EntryMBB->insert(EntryMBB->begin(), MI); 544 else { 545 MachineInstr *Def = RegInfo->getVRegDef(Reg); 546 if (Def) { 547 MachineBasicBlock::iterator InsertPos = Def; 548 // FIXME: VR def may not be in entry block. 549 Def->getParent()->insert(std::next(InsertPos), MI); 550 } else 551 DEBUG(dbgs() << "Dropping debug info for dead vreg" 552 << TargetRegisterInfo::virtReg2Index(Reg) << "\n"); 553 } 554 555 // If Reg is live-in then update debug info to track its copy in a vreg. 556 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg); 557 if (LDI != LiveInMap.end()) { 558 assert(!hasFI && "There's no handling of frame pointer updating here yet " 559 "- add if needed"); 560 MachineInstr *Def = RegInfo->getVRegDef(LDI->second); 561 MachineBasicBlock::iterator InsertPos = Def; 562 const MDNode *Variable = MI->getDebugVariable(); 563 const MDNode *Expr = MI->getDebugExpression(); 564 DebugLoc DL = MI->getDebugLoc(); 565 bool IsIndirect = MI->isIndirectDebugValue(); 566 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0; 567 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 568 "Expected inlined-at fields to agree"); 569 // Def is never a terminator here, so it is ok to increment InsertPos. 570 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE), 571 IsIndirect, LDI->second, Offset, Variable, Expr); 572 573 // If this vreg is directly copied into an exported register then 574 // that COPY instructions also need DBG_VALUE, if it is the only 575 // user of LDI->second. 576 MachineInstr *CopyUseMI = nullptr; 577 for (MachineRegisterInfo::use_instr_iterator 578 UI = RegInfo->use_instr_begin(LDI->second), 579 E = RegInfo->use_instr_end(); UI != E; ) { 580 MachineInstr *UseMI = &*(UI++); 581 if (UseMI->isDebugValue()) continue; 582 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) { 583 CopyUseMI = UseMI; continue; 584 } 585 // Otherwise this is another use or second copy use. 586 CopyUseMI = nullptr; break; 587 } 588 if (CopyUseMI) { 589 // Use MI's debug location, which describes where Variable was 590 // declared, rather than whatever is attached to CopyUseMI. 591 MachineInstr *NewMI = 592 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 593 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr); 594 MachineBasicBlock::iterator Pos = CopyUseMI; 595 EntryMBB->insertAfter(Pos, NewMI); 596 } 597 } 598 } 599 600 // Determine if there are any calls in this machine function. 601 MachineFrameInfo &MFI = MF->getFrameInfo(); 602 for (const auto &MBB : *MF) { 603 if (MFI.hasCalls() && MF->hasInlineAsm()) 604 break; 605 606 for (const auto &MI : MBB) { 607 const MCInstrDesc &MCID = TII->get(MI.getOpcode()); 608 if ((MCID.isCall() && !MCID.isReturn()) || 609 MI.isStackAligningInlineAsm()) { 610 MFI.setHasCalls(true); 611 } 612 if (MI.isInlineAsm()) { 613 MF->setHasInlineAsm(true); 614 } 615 } 616 } 617 618 // Determine if there is a call to setjmp in the machine function. 619 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice()); 620 621 // Replace forward-declared registers with the registers containing 622 // the desired value. 623 MachineRegisterInfo &MRI = MF->getRegInfo(); 624 for (DenseMap<unsigned, unsigned>::iterator 625 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end(); 626 I != E; ++I) { 627 unsigned From = I->first; 628 unsigned To = I->second; 629 // If To is also scheduled to be replaced, find what its ultimate 630 // replacement is. 631 for (;;) { 632 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To); 633 if (J == E) break; 634 To = J->second; 635 } 636 // Make sure the new register has a sufficiently constrained register class. 637 if (TargetRegisterInfo::isVirtualRegister(From) && 638 TargetRegisterInfo::isVirtualRegister(To)) 639 MRI.constrainRegClass(To, MRI.getRegClass(From)); 640 // Replace it. 641 642 643 // Replacing one register with another won't touch the kill flags. 644 // We need to conservatively clear the kill flags as a kill on the old 645 // register might dominate existing uses of the new register. 646 if (!MRI.use_empty(To)) 647 MRI.clearKillFlags(From); 648 MRI.replaceRegWith(From, To); 649 } 650 651 if (TLI->hasCopyImplyingStackAdjustment(MF)) 652 MFI.setHasCopyImplyingStackAdjustment(true); 653 654 // Freeze the set of reserved registers now that MachineFrameInfo has been 655 // set up. All the information required by getReservedRegs() should be 656 // available now. 657 MRI.freezeReservedRegs(*MF); 658 659 // Release function-specific state. SDB and CurDAG are already cleared 660 // at this point. 661 FuncInfo->clear(); 662 663 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n"); 664 DEBUG(MF->print(dbgs())); 665 666 return true; 667 } 668 669 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin, 670 BasicBlock::const_iterator End, 671 bool &HadTailCall) { 672 // Lower the instructions. If a call is emitted as a tail call, cease emitting 673 // nodes for this block. 674 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) 675 SDB->visit(*I); 676 677 // Make sure the root of the DAG is up-to-date. 678 CurDAG->setRoot(SDB->getControlRoot()); 679 HadTailCall = SDB->HasTailCall; 680 SDB->clear(); 681 682 // Final step, emit the lowered DAG as machine code. 683 CodeGenAndEmitDAG(); 684 } 685 686 void SelectionDAGISel::ComputeLiveOutVRegInfo() { 687 SmallPtrSet<SDNode*, 16> VisitedNodes; 688 SmallVector<SDNode*, 128> Worklist; 689 690 Worklist.push_back(CurDAG->getRoot().getNode()); 691 692 APInt KnownZero; 693 APInt KnownOne; 694 695 do { 696 SDNode *N = Worklist.pop_back_val(); 697 698 // If we've already seen this node, ignore it. 699 if (!VisitedNodes.insert(N).second) 700 continue; 701 702 // Otherwise, add all chain operands to the worklist. 703 for (const SDValue &Op : N->op_values()) 704 if (Op.getValueType() == MVT::Other) 705 Worklist.push_back(Op.getNode()); 706 707 // If this is a CopyToReg with a vreg dest, process it. 708 if (N->getOpcode() != ISD::CopyToReg) 709 continue; 710 711 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); 712 if (!TargetRegisterInfo::isVirtualRegister(DestReg)) 713 continue; 714 715 // Ignore non-scalar or non-integer values. 716 SDValue Src = N->getOperand(2); 717 EVT SrcVT = Src.getValueType(); 718 if (!SrcVT.isInteger() || SrcVT.isVector()) 719 continue; 720 721 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); 722 CurDAG->computeKnownBits(Src, KnownZero, KnownOne); 723 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne); 724 } while (!Worklist.empty()); 725 } 726 727 void SelectionDAGISel::CodeGenAndEmitDAG() { 728 StringRef GroupName = "sdag"; 729 StringRef GroupDescription = "Instruction Selection and Scheduling"; 730 std::string BlockName; 731 int BlockNumber = -1; 732 (void)BlockNumber; 733 bool MatchFilterBB = false; (void)MatchFilterBB; 734 #ifndef NDEBUG 735 MatchFilterBB = (FilterDAGBasicBlockName.empty() || 736 FilterDAGBasicBlockName == 737 FuncInfo->MBB->getBasicBlock()->getName().str()); 738 #endif 739 #ifdef NDEBUG 740 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs || 741 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs || 742 ViewSUnitDAGs) 743 #endif 744 { 745 BlockNumber = FuncInfo->MBB->getNumber(); 746 BlockName = 747 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str(); 748 } 749 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber 750 << " '" << BlockName << "'\n"; CurDAG->dump()); 751 752 if (ViewDAGCombine1 && MatchFilterBB) 753 CurDAG->viewGraph("dag-combine1 input for " + BlockName); 754 755 // Run the DAG combiner in pre-legalize mode. 756 { 757 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName, 758 GroupDescription, TimePassesIsEnabled); 759 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel); 760 } 761 762 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber 763 << " '" << BlockName << "'\n"; CurDAG->dump()); 764 765 // Second step, hack on the DAG until it only uses operations and types that 766 // the target supports. 767 if (ViewLegalizeTypesDAGs && MatchFilterBB) 768 CurDAG->viewGraph("legalize-types input for " + BlockName); 769 770 bool Changed; 771 { 772 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName, 773 GroupDescription, TimePassesIsEnabled); 774 Changed = CurDAG->LegalizeTypes(); 775 } 776 777 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber 778 << " '" << BlockName << "'\n"; CurDAG->dump()); 779 780 CurDAG->NewNodesMustHaveLegalTypes = true; 781 782 if (Changed) { 783 if (ViewDAGCombineLT && MatchFilterBB) 784 CurDAG->viewGraph("dag-combine-lt input for " + BlockName); 785 786 // Run the DAG combiner in post-type-legalize mode. 787 { 788 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types", 789 GroupName, GroupDescription, TimePassesIsEnabled); 790 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel); 791 } 792 793 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber 794 << " '" << BlockName << "'\n"; CurDAG->dump()); 795 796 } 797 798 { 799 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName, 800 GroupDescription, TimePassesIsEnabled); 801 Changed = CurDAG->LegalizeVectors(); 802 } 803 804 if (Changed) { 805 { 806 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName, 807 GroupDescription, TimePassesIsEnabled); 808 CurDAG->LegalizeTypes(); 809 } 810 811 if (ViewDAGCombineLT && MatchFilterBB) 812 CurDAG->viewGraph("dag-combine-lv input for " + BlockName); 813 814 // Run the DAG combiner in post-type-legalize mode. 815 { 816 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors", 817 GroupName, GroupDescription, TimePassesIsEnabled); 818 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel); 819 } 820 821 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#" 822 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); 823 } 824 825 if (ViewLegalizeDAGs && MatchFilterBB) 826 CurDAG->viewGraph("legalize input for " + BlockName); 827 828 { 829 NamedRegionTimer T("legalize", "DAG Legalization", GroupName, 830 GroupDescription, TimePassesIsEnabled); 831 CurDAG->Legalize(); 832 } 833 834 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber 835 << " '" << BlockName << "'\n"; CurDAG->dump()); 836 837 if (ViewDAGCombine2 && MatchFilterBB) 838 CurDAG->viewGraph("dag-combine2 input for " + BlockName); 839 840 // Run the DAG combiner in post-legalize mode. 841 { 842 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName, 843 GroupDescription, TimePassesIsEnabled); 844 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel); 845 } 846 847 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber 848 << " '" << BlockName << "'\n"; CurDAG->dump()); 849 850 if (OptLevel != CodeGenOpt::None) 851 ComputeLiveOutVRegInfo(); 852 853 if (ViewISelDAGs && MatchFilterBB) 854 CurDAG->viewGraph("isel input for " + BlockName); 855 856 // Third, instruction select all of the operations to machine code, adding the 857 // code to the MachineBasicBlock. 858 { 859 NamedRegionTimer T("isel", "Instruction Selection", GroupName, 860 GroupDescription, TimePassesIsEnabled); 861 DoInstructionSelection(); 862 } 863 864 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber 865 << " '" << BlockName << "'\n"; CurDAG->dump()); 866 867 if (ViewSchedDAGs && MatchFilterBB) 868 CurDAG->viewGraph("scheduler input for " + BlockName); 869 870 // Schedule machine code. 871 ScheduleDAGSDNodes *Scheduler = CreateScheduler(); 872 { 873 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName, 874 GroupDescription, TimePassesIsEnabled); 875 Scheduler->Run(CurDAG, FuncInfo->MBB); 876 } 877 878 if (ViewSUnitDAGs && MatchFilterBB) 879 Scheduler->viewGraph(); 880 881 // Emit machine code to BB. This can change 'BB' to the last block being 882 // inserted into. 883 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB; 884 { 885 NamedRegionTimer T("emit", "Instruction Creation", GroupName, 886 GroupDescription, TimePassesIsEnabled); 887 888 // FuncInfo->InsertPt is passed by reference and set to the end of the 889 // scheduled instructions. 890 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt); 891 } 892 893 // If the block was split, make sure we update any references that are used to 894 // update PHI nodes later on. 895 if (FirstMBB != LastMBB) 896 SDB->UpdateSplitBlock(FirstMBB, LastMBB); 897 898 // Free the scheduler state. 899 { 900 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName, 901 GroupDescription, TimePassesIsEnabled); 902 delete Scheduler; 903 } 904 905 // Free the SelectionDAG state, now that we're finished with it. 906 CurDAG->clear(); 907 } 908 909 namespace { 910 /// ISelUpdater - helper class to handle updates of the instruction selection 911 /// graph. 912 class ISelUpdater : public SelectionDAG::DAGUpdateListener { 913 SelectionDAG::allnodes_iterator &ISelPosition; 914 public: 915 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp) 916 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {} 917 918 /// NodeDeleted - Handle nodes deleted from the graph. If the node being 919 /// deleted is the current ISelPosition node, update ISelPosition. 920 /// 921 void NodeDeleted(SDNode *N, SDNode *E) override { 922 if (ISelPosition == SelectionDAG::allnodes_iterator(N)) 923 ++ISelPosition; 924 } 925 }; 926 } // end anonymous namespace 927 928 static bool isStrictFPOp(SDNode *Node, unsigned &NewOpc) { 929 unsigned OrigOpc = Node->getOpcode(); 930 switch (OrigOpc) { 931 case ISD::STRICT_FADD: NewOpc = ISD::FADD; return true; 932 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; return true; 933 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; return true; 934 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; return true; 935 case ISD::STRICT_FREM: NewOpc = ISD::FREM; return true; 936 default: return false; 937 } 938 } 939 940 SDNode* SelectionDAGISel::MutateStrictFPToFP(SDNode *Node, unsigned NewOpc) { 941 assert(((Node->getOpcode() == ISD::STRICT_FADD && NewOpc == ISD::FADD) || 942 (Node->getOpcode() == ISD::STRICT_FSUB && NewOpc == ISD::FSUB) || 943 (Node->getOpcode() == ISD::STRICT_FMUL && NewOpc == ISD::FMUL) || 944 (Node->getOpcode() == ISD::STRICT_FDIV && NewOpc == ISD::FDIV) || 945 (Node->getOpcode() == ISD::STRICT_FREM && NewOpc == ISD::FREM)) && 946 "Unexpected StrictFP opcode!"); 947 948 // We're taking this node out of the chain, so we need to re-link things. 949 SDValue InputChain = Node->getOperand(0); 950 SDValue OutputChain = SDValue(Node, 1); 951 CurDAG->ReplaceAllUsesOfValueWith(OutputChain, InputChain); 952 953 SDVTList VTs = CurDAG->getVTList(Node->getOperand(1).getValueType()); 954 SDValue Ops[2] = { Node->getOperand(1), Node->getOperand(2) }; 955 SDNode *Res = CurDAG->MorphNodeTo(Node, NewOpc, VTs, Ops); 956 957 // MorphNodeTo can operate in two ways: if an existing node with the 958 // specified operands exists, it can just return it. Otherwise, it 959 // updates the node in place to have the requested operands. 960 if (Res == Node) { 961 // If we updated the node in place, reset the node ID. To the isel, 962 // this should be just like a newly allocated machine node. 963 Res->setNodeId(-1); 964 } else { 965 CurDAG->ReplaceAllUsesWith(Node, Res); 966 CurDAG->RemoveDeadNode(Node); 967 } 968 969 return Res; 970 } 971 972 void SelectionDAGISel::DoInstructionSelection() { 973 DEBUG(dbgs() << "===== Instruction selection begins: BB#" 974 << FuncInfo->MBB->getNumber() 975 << " '" << FuncInfo->MBB->getName() << "'\n"); 976 977 PreprocessISelDAG(); 978 979 // Select target instructions for the DAG. 980 { 981 // Number all nodes with a topological order and set DAGSize. 982 DAGSize = CurDAG->AssignTopologicalOrder(); 983 984 // Create a dummy node (which is not added to allnodes), that adds 985 // a reference to the root node, preventing it from being deleted, 986 // and tracking any changes of the root. 987 HandleSDNode Dummy(CurDAG->getRoot()); 988 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode()); 989 ++ISelPosition; 990 991 // Make sure that ISelPosition gets properly updated when nodes are deleted 992 // in calls made from this function. 993 ISelUpdater ISU(*CurDAG, ISelPosition); 994 995 // The AllNodes list is now topological-sorted. Visit the 996 // nodes by starting at the end of the list (the root of the 997 // graph) and preceding back toward the beginning (the entry 998 // node). 999 while (ISelPosition != CurDAG->allnodes_begin()) { 1000 SDNode *Node = &*--ISelPosition; 1001 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes, 1002 // but there are currently some corner cases that it misses. Also, this 1003 // makes it theoretically possible to disable the DAGCombiner. 1004 if (Node->use_empty()) 1005 continue; 1006 1007 // When we are using non-default rounding modes or FP exception behavior 1008 // FP operations are represented by StrictFP pseudo-operations. They 1009 // need to be simplified here so that the target-specific instruction 1010 // selectors know how to handle them. 1011 // 1012 // If the current node is a strict FP pseudo-op, the isStrictFPOp() 1013 // function will provide the corresponding normal FP opcode to which the 1014 // node should be mutated. 1015 unsigned NormalFPOpc = ISD::UNDEF; 1016 bool IsStrictFPOp = isStrictFPOp(Node, NormalFPOpc); 1017 if (IsStrictFPOp) 1018 Node = MutateStrictFPToFP(Node, NormalFPOpc); 1019 1020 Select(Node); 1021 1022 // FIXME: Add code here to attach an implicit def and use of 1023 // target-specific FP environment registers. 1024 } 1025 1026 CurDAG->setRoot(Dummy.getValue()); 1027 } 1028 1029 DEBUG(dbgs() << "===== Instruction selection ends:\n"); 1030 1031 PostprocessISelDAG(); 1032 } 1033 1034 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) { 1035 for (const User *U : CPI->users()) { 1036 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) { 1037 Intrinsic::ID IID = EHPtrCall->getIntrinsicID(); 1038 if (IID == Intrinsic::eh_exceptionpointer || 1039 IID == Intrinsic::eh_exceptioncode) 1040 return true; 1041 } 1042 } 1043 return false; 1044 } 1045 1046 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and 1047 /// do other setup for EH landing-pad blocks. 1048 bool SelectionDAGISel::PrepareEHLandingPad() { 1049 MachineBasicBlock *MBB = FuncInfo->MBB; 1050 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn(); 1051 const BasicBlock *LLVMBB = MBB->getBasicBlock(); 1052 const TargetRegisterClass *PtrRC = 1053 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout())); 1054 1055 // Catchpads have one live-in register, which typically holds the exception 1056 // pointer or code. 1057 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) { 1058 if (hasExceptionPointerOrCodeUser(CPI)) { 1059 // Get or create the virtual register to hold the pointer or code. Mark 1060 // the live in physreg and copy into the vreg. 1061 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn); 1062 assert(EHPhysReg && "target lacks exception pointer register"); 1063 MBB->addLiveIn(EHPhysReg); 1064 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC); 1065 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), 1066 TII->get(TargetOpcode::COPY), VReg) 1067 .addReg(EHPhysReg, RegState::Kill); 1068 } 1069 return true; 1070 } 1071 1072 if (!LLVMBB->isLandingPad()) 1073 return true; 1074 1075 // Add a label to mark the beginning of the landing pad. Deletion of the 1076 // landing pad can thus be detected via the MachineModuleInfo. 1077 MCSymbol *Label = MF->addLandingPad(MBB); 1078 1079 // Assign the call site to the landing pad's begin label. 1080 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]); 1081 1082 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL); 1083 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II) 1084 .addSym(Label); 1085 1086 // Mark exception register as live in. 1087 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn)) 1088 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC); 1089 1090 // Mark exception selector register as live in. 1091 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn)) 1092 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC); 1093 1094 return true; 1095 } 1096 1097 /// isFoldedOrDeadInstruction - Return true if the specified instruction is 1098 /// side-effect free and is either dead or folded into a generated instruction. 1099 /// Return false if it needs to be emitted. 1100 static bool isFoldedOrDeadInstruction(const Instruction *I, 1101 FunctionLoweringInfo *FuncInfo) { 1102 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded. 1103 !isa<TerminatorInst>(I) && // Terminators aren't folded. 1104 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded. 1105 !I->isEHPad() && // EH pad instructions aren't folded. 1106 !FuncInfo->isExportedInst(I); // Exported instrs must be computed. 1107 } 1108 1109 #ifndef NDEBUG 1110 // Collect per Instruction statistics for fast-isel misses. Only those 1111 // instructions that cause the bail are accounted for. It does not account for 1112 // instructions higher in the block. Thus, summing the per instructions stats 1113 // will not add up to what is reported by NumFastIselFailures. 1114 static void collectFailStats(const Instruction *I) { 1115 switch (I->getOpcode()) { 1116 default: assert (0 && "<Invalid operator> "); 1117 1118 // Terminators 1119 case Instruction::Ret: NumFastIselFailRet++; return; 1120 case Instruction::Br: NumFastIselFailBr++; return; 1121 case Instruction::Switch: NumFastIselFailSwitch++; return; 1122 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return; 1123 case Instruction::Invoke: NumFastIselFailInvoke++; return; 1124 case Instruction::Resume: NumFastIselFailResume++; return; 1125 case Instruction::Unreachable: NumFastIselFailUnreachable++; return; 1126 1127 // Standard binary operators... 1128 case Instruction::Add: NumFastIselFailAdd++; return; 1129 case Instruction::FAdd: NumFastIselFailFAdd++; return; 1130 case Instruction::Sub: NumFastIselFailSub++; return; 1131 case Instruction::FSub: NumFastIselFailFSub++; return; 1132 case Instruction::Mul: NumFastIselFailMul++; return; 1133 case Instruction::FMul: NumFastIselFailFMul++; return; 1134 case Instruction::UDiv: NumFastIselFailUDiv++; return; 1135 case Instruction::SDiv: NumFastIselFailSDiv++; return; 1136 case Instruction::FDiv: NumFastIselFailFDiv++; return; 1137 case Instruction::URem: NumFastIselFailURem++; return; 1138 case Instruction::SRem: NumFastIselFailSRem++; return; 1139 case Instruction::FRem: NumFastIselFailFRem++; return; 1140 1141 // Logical operators... 1142 case Instruction::And: NumFastIselFailAnd++; return; 1143 case Instruction::Or: NumFastIselFailOr++; return; 1144 case Instruction::Xor: NumFastIselFailXor++; return; 1145 1146 // Memory instructions... 1147 case Instruction::Alloca: NumFastIselFailAlloca++; return; 1148 case Instruction::Load: NumFastIselFailLoad++; return; 1149 case Instruction::Store: NumFastIselFailStore++; return; 1150 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return; 1151 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return; 1152 case Instruction::Fence: NumFastIselFailFence++; return; 1153 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return; 1154 1155 // Convert instructions... 1156 case Instruction::Trunc: NumFastIselFailTrunc++; return; 1157 case Instruction::ZExt: NumFastIselFailZExt++; return; 1158 case Instruction::SExt: NumFastIselFailSExt++; return; 1159 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return; 1160 case Instruction::FPExt: NumFastIselFailFPExt++; return; 1161 case Instruction::FPToUI: NumFastIselFailFPToUI++; return; 1162 case Instruction::FPToSI: NumFastIselFailFPToSI++; return; 1163 case Instruction::UIToFP: NumFastIselFailUIToFP++; return; 1164 case Instruction::SIToFP: NumFastIselFailSIToFP++; return; 1165 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return; 1166 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return; 1167 case Instruction::BitCast: NumFastIselFailBitCast++; return; 1168 1169 // Other instructions... 1170 case Instruction::ICmp: NumFastIselFailICmp++; return; 1171 case Instruction::FCmp: NumFastIselFailFCmp++; return; 1172 case Instruction::PHI: NumFastIselFailPHI++; return; 1173 case Instruction::Select: NumFastIselFailSelect++; return; 1174 case Instruction::Call: { 1175 if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) { 1176 switch (Intrinsic->getIntrinsicID()) { 1177 default: 1178 NumFastIselFailIntrinsicCall++; return; 1179 case Intrinsic::sadd_with_overflow: 1180 NumFastIselFailSAddWithOverflow++; return; 1181 case Intrinsic::uadd_with_overflow: 1182 NumFastIselFailUAddWithOverflow++; return; 1183 case Intrinsic::ssub_with_overflow: 1184 NumFastIselFailSSubWithOverflow++; return; 1185 case Intrinsic::usub_with_overflow: 1186 NumFastIselFailUSubWithOverflow++; return; 1187 case Intrinsic::smul_with_overflow: 1188 NumFastIselFailSMulWithOverflow++; return; 1189 case Intrinsic::umul_with_overflow: 1190 NumFastIselFailUMulWithOverflow++; return; 1191 case Intrinsic::frameaddress: 1192 NumFastIselFailFrameaddress++; return; 1193 case Intrinsic::sqrt: 1194 NumFastIselFailSqrt++; return; 1195 case Intrinsic::experimental_stackmap: 1196 NumFastIselFailStackMap++; return; 1197 case Intrinsic::experimental_patchpoint_void: // fall-through 1198 case Intrinsic::experimental_patchpoint_i64: 1199 NumFastIselFailPatchPoint++; return; 1200 } 1201 } 1202 NumFastIselFailCall++; 1203 return; 1204 } 1205 case Instruction::Shl: NumFastIselFailShl++; return; 1206 case Instruction::LShr: NumFastIselFailLShr++; return; 1207 case Instruction::AShr: NumFastIselFailAShr++; return; 1208 case Instruction::VAArg: NumFastIselFailVAArg++; return; 1209 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return; 1210 case Instruction::InsertElement: NumFastIselFailInsertElement++; return; 1211 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return; 1212 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return; 1213 case Instruction::InsertValue: NumFastIselFailInsertValue++; return; 1214 case Instruction::LandingPad: NumFastIselFailLandingPad++; return; 1215 } 1216 } 1217 #endif // NDEBUG 1218 1219 /// Set up SwiftErrorVals by going through the function. If the function has 1220 /// swifterror argument, it will be the first entry. 1221 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI, 1222 FunctionLoweringInfo *FuncInfo) { 1223 if (!TLI->supportSwiftError()) 1224 return; 1225 1226 FuncInfo->SwiftErrorVals.clear(); 1227 FuncInfo->SwiftErrorVRegDefMap.clear(); 1228 FuncInfo->SwiftErrorVRegUpwardsUse.clear(); 1229 FuncInfo->SwiftErrorArg = nullptr; 1230 1231 // Check if function has a swifterror argument. 1232 bool HaveSeenSwiftErrorArg = false; 1233 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end(); 1234 AI != AE; ++AI) 1235 if (AI->hasSwiftErrorAttr()) { 1236 assert(!HaveSeenSwiftErrorArg && 1237 "Must have only one swifterror parameter"); 1238 (void)HaveSeenSwiftErrorArg; // silence warning. 1239 HaveSeenSwiftErrorArg = true; 1240 FuncInfo->SwiftErrorArg = &*AI; 1241 FuncInfo->SwiftErrorVals.push_back(&*AI); 1242 } 1243 1244 for (const auto &LLVMBB : Fn) 1245 for (const auto &Inst : LLVMBB) { 1246 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst)) 1247 if (Alloca->isSwiftError()) 1248 FuncInfo->SwiftErrorVals.push_back(Alloca); 1249 } 1250 } 1251 1252 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo, 1253 const TargetLowering *TLI, 1254 const TargetInstrInfo *TII, 1255 const BasicBlock *LLVMBB, 1256 SelectionDAGBuilder *SDB) { 1257 if (!TLI->supportSwiftError()) 1258 return; 1259 1260 // We only need to do this when we have swifterror parameter or swifterror 1261 // alloc. 1262 if (FuncInfo->SwiftErrorVals.empty()) 1263 return; 1264 1265 if (pred_begin(LLVMBB) == pred_end(LLVMBB)) { 1266 auto &DL = FuncInfo->MF->getDataLayout(); 1267 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1268 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1269 // We will always generate a copy from the argument. It is always used at 1270 // least by the 'return' of the swifterror. 1271 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal) 1272 continue; 1273 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1274 // Assign Undef to Vreg. We construct MI directly to make sure it works 1275 // with FastISel. 1276 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(), 1277 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF), 1278 VReg); 1279 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg); 1280 } 1281 } 1282 } 1283 1284 /// Propagate swifterror values through the machine function CFG. 1285 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) { 1286 auto *TLI = FuncInfo->TLI; 1287 if (!TLI->supportSwiftError()) 1288 return; 1289 1290 // We only need to do this when we have swifterror parameter or swifterror 1291 // alloc. 1292 if (FuncInfo->SwiftErrorVals.empty()) 1293 return; 1294 1295 // For each machine basic block in reverse post order. 1296 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF); 1297 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator 1298 It = RPOT.begin(), 1299 E = RPOT.end(); 1300 It != E; ++It) { 1301 MachineBasicBlock *MBB = *It; 1302 1303 // For each swifterror value in the function. 1304 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1305 auto Key = std::make_pair(MBB, SwiftErrorVal); 1306 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1307 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key); 1308 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end(); 1309 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0; 1310 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end(); 1311 assert(!(UpwardsUse && !DownwardDef) && 1312 "We can't have an upwards use but no downwards def"); 1313 1314 // If there is no upwards exposed use and an entry for the swifterror in 1315 // the def map for this value we don't need to do anything: We already 1316 // have a downward def for this basic block. 1317 if (!UpwardsUse && DownwardDef) 1318 continue; 1319 1320 // Otherwise we either have an upwards exposed use vreg that we need to 1321 // materialize or need to forward the downward def from predecessors. 1322 1323 // Check whether we have a single vreg def from all predecessors. 1324 // Otherwise we need a phi. 1325 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs; 1326 SmallSet<const MachineBasicBlock*, 8> Visited; 1327 for (auto *Pred : MBB->predecessors()) { 1328 if (!Visited.insert(Pred).second) 1329 continue; 1330 VRegs.push_back(std::make_pair( 1331 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal))); 1332 if (Pred != MBB) 1333 continue; 1334 // We have a self-edge. 1335 // If there was no upwards use in this basic block there is now one: the 1336 // phi needs to use it self. 1337 if (!UpwardsUse) { 1338 UpwardsUse = true; 1339 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1340 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end()); 1341 UUseVReg = UUseIt->second; 1342 } 1343 } 1344 1345 // We need a phi node if we have more than one predecessor with different 1346 // downward defs. 1347 bool needPHI = 1348 VRegs.size() >= 1 && 1349 std::find_if( 1350 VRegs.begin(), VRegs.end(), 1351 [&](const std::pair<const MachineBasicBlock *, unsigned> &V) 1352 -> bool { return V.second != VRegs[0].second; }) != 1353 VRegs.end(); 1354 1355 // If there is no upwards exposed used and we don't need a phi just 1356 // forward the swifterror vreg from the predecessor(s). 1357 if (!UpwardsUse && !needPHI) { 1358 assert(!VRegs.empty() && 1359 "No predecessors? The entry block should bail out earlier"); 1360 // Just forward the swifterror vreg from the predecessor(s). 1361 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second); 1362 continue; 1363 } 1364 1365 auto DLoc = isa<Instruction>(SwiftErrorVal) 1366 ? dyn_cast<Instruction>(SwiftErrorVal)->getDebugLoc() 1367 : DebugLoc(); 1368 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo(); 1369 1370 // If we don't need a phi create a copy to the upward exposed vreg. 1371 if (!needPHI) { 1372 assert(UpwardsUse); 1373 unsigned DestReg = UUseVReg; 1374 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY), 1375 DestReg) 1376 .addReg(VRegs[0].second); 1377 continue; 1378 } 1379 1380 // We need a phi: if there is an upwards exposed use we already have a 1381 // destination virtual register number otherwise we generate a new one. 1382 auto &DL = FuncInfo->MF->getDataLayout(); 1383 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1384 unsigned PHIVReg = 1385 UpwardsUse ? UUseVReg 1386 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1387 MachineInstrBuilder SwiftErrorPHI = 1388 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, 1389 TII->get(TargetOpcode::PHI), PHIVReg); 1390 for (auto BBRegPair : VRegs) { 1391 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first); 1392 } 1393 1394 // We did not have a definition in this block before: store the phi's vreg 1395 // as this block downward exposed def. 1396 if (!UpwardsUse) 1397 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg); 1398 } 1399 } 1400 } 1401 1402 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { 1403 // Initialize the Fast-ISel state, if needed. 1404 FastISel *FastIS = nullptr; 1405 if (TM.Options.EnableFastISel) 1406 FastIS = TLI->createFastISel(*FuncInfo, LibInfo); 1407 1408 setupSwiftErrorVals(Fn, TLI, FuncInfo); 1409 1410 // Iterate over all basic blocks in the function. 1411 ReversePostOrderTraversal<const Function*> RPOT(&Fn); 1412 for (ReversePostOrderTraversal<const Function*>::rpo_iterator 1413 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 1414 const BasicBlock *LLVMBB = *I; 1415 1416 if (OptLevel != CodeGenOpt::None) { 1417 bool AllPredsVisited = true; 1418 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); 1419 PI != PE; ++PI) { 1420 if (!FuncInfo->VisitedBBs.count(*PI)) { 1421 AllPredsVisited = false; 1422 break; 1423 } 1424 } 1425 1426 if (AllPredsVisited) { 1427 for (BasicBlock::const_iterator I = LLVMBB->begin(); 1428 const PHINode *PN = dyn_cast<PHINode>(I); ++I) 1429 FuncInfo->ComputePHILiveOutRegInfo(PN); 1430 } else { 1431 for (BasicBlock::const_iterator I = LLVMBB->begin(); 1432 const PHINode *PN = dyn_cast<PHINode>(I); ++I) 1433 FuncInfo->InvalidatePHILiveOutRegInfo(PN); 1434 } 1435 1436 FuncInfo->VisitedBBs.insert(LLVMBB); 1437 } 1438 1439 BasicBlock::const_iterator const Begin = 1440 LLVMBB->getFirstNonPHI()->getIterator(); 1441 BasicBlock::const_iterator const End = LLVMBB->end(); 1442 BasicBlock::const_iterator BI = End; 1443 1444 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB]; 1445 if (!FuncInfo->MBB) 1446 continue; // Some blocks like catchpads have no code or MBB. 1447 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI(); 1448 createSwiftErrorEntriesInEntryBlock(FuncInfo, TLI, TII, LLVMBB, SDB); 1449 1450 // Setup an EH landing-pad block. 1451 FuncInfo->ExceptionPointerVirtReg = 0; 1452 FuncInfo->ExceptionSelectorVirtReg = 0; 1453 if (LLVMBB->isEHPad()) 1454 if (!PrepareEHLandingPad()) 1455 continue; 1456 1457 // Before doing SelectionDAG ISel, see if FastISel has been requested. 1458 if (FastIS) { 1459 FastIS->startNewBlock(); 1460 1461 // Emit code for any incoming arguments. This must happen before 1462 // beginning FastISel on the entry block. 1463 if (LLVMBB == &Fn.getEntryBlock()) { 1464 ++NumEntryBlocks; 1465 1466 // Lower any arguments needed in this block if this is the entry block. 1467 if (!FastIS->lowerArguments()) { 1468 // Fast isel failed to lower these arguments 1469 ++NumFastIselFailLowerArguments; 1470 if (EnableFastISelAbort > 1) 1471 report_fatal_error("FastISel didn't lower all arguments"); 1472 1473 // Use SelectionDAG argument lowering 1474 LowerArguments(Fn); 1475 CurDAG->setRoot(SDB->getControlRoot()); 1476 SDB->clear(); 1477 CodeGenAndEmitDAG(); 1478 } 1479 1480 // If we inserted any instructions at the beginning, make a note of 1481 // where they are, so we can be sure to emit subsequent instructions 1482 // after them. 1483 if (FuncInfo->InsertPt != FuncInfo->MBB->begin()) 1484 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); 1485 else 1486 FastIS->setLastLocalValue(nullptr); 1487 } 1488 1489 unsigned NumFastIselRemaining = std::distance(Begin, End); 1490 // Do FastISel on as many instructions as possible. 1491 for (; BI != Begin; --BI) { 1492 const Instruction *Inst = &*std::prev(BI); 1493 1494 // If we no longer require this instruction, skip it. 1495 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) { 1496 --NumFastIselRemaining; 1497 continue; 1498 } 1499 1500 // Bottom-up: reset the insert pos at the top, after any local-value 1501 // instructions. 1502 FastIS->recomputeInsertPt(); 1503 1504 // Try to select the instruction with FastISel. 1505 if (FastIS->selectInstruction(Inst)) { 1506 --NumFastIselRemaining; 1507 ++NumFastIselSuccess; 1508 // If fast isel succeeded, skip over all the folded instructions, and 1509 // then see if there is a load right before the selected instructions. 1510 // Try to fold the load if so. 1511 const Instruction *BeforeInst = Inst; 1512 while (BeforeInst != &*Begin) { 1513 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst)); 1514 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo)) 1515 break; 1516 } 1517 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) && 1518 BeforeInst->hasOneUse() && 1519 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) { 1520 // If we succeeded, don't re-select the load. 1521 BI = std::next(BasicBlock::const_iterator(BeforeInst)); 1522 --NumFastIselRemaining; 1523 ++NumFastIselSuccess; 1524 } 1525 continue; 1526 } 1527 1528 #ifndef NDEBUG 1529 if (EnableFastISelVerbose2) 1530 collectFailStats(Inst); 1531 #endif 1532 1533 // Then handle certain instructions as single-LLVM-Instruction blocks. 1534 if (isa<CallInst>(Inst)) { 1535 1536 if (EnableFastISelVerbose || EnableFastISelAbort) { 1537 dbgs() << "FastISel missed call: "; 1538 Inst->print(dbgs()); 1539 } 1540 if (EnableFastISelAbort > 2) 1541 // FastISel selector couldn't handle something and bailed. 1542 // For the purpose of debugging, just abort. 1543 report_fatal_error("FastISel didn't select the entire block"); 1544 1545 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() && 1546 !Inst->use_empty()) { 1547 unsigned &R = FuncInfo->ValueMap[Inst]; 1548 if (!R) 1549 R = FuncInfo->CreateRegs(Inst->getType()); 1550 } 1551 1552 bool HadTailCall = false; 1553 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt; 1554 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall); 1555 1556 // If the call was emitted as a tail call, we're done with the block. 1557 // We also need to delete any previously emitted instructions. 1558 if (HadTailCall) { 1559 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end()); 1560 --BI; 1561 break; 1562 } 1563 1564 // Recompute NumFastIselRemaining as Selection DAG instruction 1565 // selection may have handled the call, input args, etc. 1566 unsigned RemainingNow = std::distance(Begin, BI); 1567 NumFastIselFailures += NumFastIselRemaining - RemainingNow; 1568 NumFastIselRemaining = RemainingNow; 1569 continue; 1570 } 1571 1572 bool ShouldAbort = EnableFastISelAbort; 1573 if (EnableFastISelVerbose || EnableFastISelAbort) { 1574 if (isa<TerminatorInst>(Inst)) { 1575 // Use a different message for terminator misses. 1576 dbgs() << "FastISel missed terminator: "; 1577 // Don't abort unless for terminator unless the level is really high 1578 ShouldAbort = (EnableFastISelAbort > 2); 1579 } else { 1580 dbgs() << "FastISel miss: "; 1581 } 1582 Inst->print(dbgs()); 1583 } 1584 if (ShouldAbort) 1585 // FastISel selector couldn't handle something and bailed. 1586 // For the purpose of debugging, just abort. 1587 report_fatal_error("FastISel didn't select the entire block"); 1588 1589 NumFastIselFailures += NumFastIselRemaining; 1590 break; 1591 } 1592 1593 FastIS->recomputeInsertPt(); 1594 } else { 1595 // Lower any arguments needed in this block if this is the entry block. 1596 if (LLVMBB == &Fn.getEntryBlock()) { 1597 ++NumEntryBlocks; 1598 LowerArguments(Fn); 1599 } 1600 } 1601 if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB)) { 1602 bool FunctionBasedInstrumentation = 1603 TLI->getSSPStackGuardCheck(*Fn.getParent()); 1604 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], 1605 FunctionBasedInstrumentation); 1606 } 1607 1608 if (Begin != BI) 1609 ++NumDAGBlocks; 1610 else 1611 ++NumFastIselBlocks; 1612 1613 if (Begin != BI) { 1614 // Run SelectionDAG instruction selection on the remainder of the block 1615 // not handled by FastISel. If FastISel is not run, this is the entire 1616 // block. 1617 bool HadTailCall; 1618 SelectBasicBlock(Begin, BI, HadTailCall); 1619 } 1620 1621 FinishBasicBlock(); 1622 FuncInfo->PHINodesToUpdate.clear(); 1623 } 1624 1625 propagateSwiftErrorVRegs(FuncInfo); 1626 1627 delete FastIS; 1628 SDB->clearDanglingDebugInfo(); 1629 SDB->SPDescriptor.resetPerFunctionState(); 1630 } 1631 1632 /// Given that the input MI is before a partial terminator sequence TSeq, return 1633 /// true if M + TSeq also a partial terminator sequence. 1634 /// 1635 /// A Terminator sequence is a sequence of MachineInstrs which at this point in 1636 /// lowering copy vregs into physical registers, which are then passed into 1637 /// terminator instructors so we can satisfy ABI constraints. A partial 1638 /// terminator sequence is an improper subset of a terminator sequence (i.e. it 1639 /// may be the whole terminator sequence). 1640 static bool MIIsInTerminatorSequence(const MachineInstr &MI) { 1641 // If we do not have a copy or an implicit def, we return true if and only if 1642 // MI is a debug value. 1643 if (!MI.isCopy() && !MI.isImplicitDef()) 1644 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the 1645 // physical registers if there is debug info associated with the terminator 1646 // of our mbb. We want to include said debug info in our terminator 1647 // sequence, so we return true in that case. 1648 return MI.isDebugValue(); 1649 1650 // We have left the terminator sequence if we are not doing one of the 1651 // following: 1652 // 1653 // 1. Copying a vreg into a physical register. 1654 // 2. Copying a vreg into a vreg. 1655 // 3. Defining a register via an implicit def. 1656 1657 // OPI should always be a register definition... 1658 MachineInstr::const_mop_iterator OPI = MI.operands_begin(); 1659 if (!OPI->isReg() || !OPI->isDef()) 1660 return false; 1661 1662 // Defining any register via an implicit def is always ok. 1663 if (MI.isImplicitDef()) 1664 return true; 1665 1666 // Grab the copy source... 1667 MachineInstr::const_mop_iterator OPI2 = OPI; 1668 ++OPI2; 1669 assert(OPI2 != MI.operands_end() 1670 && "Should have a copy implying we should have 2 arguments."); 1671 1672 // Make sure that the copy dest is not a vreg when the copy source is a 1673 // physical register. 1674 if (!OPI2->isReg() || 1675 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) && 1676 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg()))) 1677 return false; 1678 1679 return true; 1680 } 1681 1682 /// Find the split point at which to splice the end of BB into its success stack 1683 /// protector check machine basic block. 1684 /// 1685 /// On many platforms, due to ABI constraints, terminators, even before register 1686 /// allocation, use physical registers. This creates an issue for us since 1687 /// physical registers at this point can not travel across basic 1688 /// blocks. Luckily, selectiondag always moves physical registers into vregs 1689 /// when they enter functions and moves them through a sequence of copies back 1690 /// into the physical registers right before the terminator creating a 1691 /// ``Terminator Sequence''. This function is searching for the beginning of the 1692 /// terminator sequence so that we can ensure that we splice off not just the 1693 /// terminator, but additionally the copies that move the vregs into the 1694 /// physical registers. 1695 static MachineBasicBlock::iterator 1696 FindSplitPointForStackProtector(MachineBasicBlock *BB) { 1697 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); 1698 // 1699 if (SplitPoint == BB->begin()) 1700 return SplitPoint; 1701 1702 MachineBasicBlock::iterator Start = BB->begin(); 1703 MachineBasicBlock::iterator Previous = SplitPoint; 1704 --Previous; 1705 1706 while (MIIsInTerminatorSequence(*Previous)) { 1707 SplitPoint = Previous; 1708 if (Previous == Start) 1709 break; 1710 --Previous; 1711 } 1712 1713 return SplitPoint; 1714 } 1715 1716 void 1717 SelectionDAGISel::FinishBasicBlock() { 1718 DEBUG(dbgs() << "Total amount of phi nodes to update: " 1719 << FuncInfo->PHINodesToUpdate.size() << "\n"; 1720 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) 1721 dbgs() << "Node " << i << " : (" 1722 << FuncInfo->PHINodesToUpdate[i].first 1723 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); 1724 1725 // Next, now that we know what the last MBB the LLVM BB expanded is, update 1726 // PHI nodes in successors. 1727 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { 1728 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); 1729 assert(PHI->isPHI() && 1730 "This is not a machine PHI node that we are updating!"); 1731 if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) 1732 continue; 1733 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); 1734 } 1735 1736 // Handle stack protector. 1737 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { 1738 // The target provides a guard check function. There is no need to 1739 // generate error handling code or to split current basic block. 1740 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1741 1742 // Add load and check to the basicblock. 1743 FuncInfo->MBB = ParentMBB; 1744 FuncInfo->InsertPt = 1745 FindSplitPointForStackProtector(ParentMBB); 1746 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1747 CurDAG->setRoot(SDB->getRoot()); 1748 SDB->clear(); 1749 CodeGenAndEmitDAG(); 1750 1751 // Clear the Per-BB State. 1752 SDB->SPDescriptor.resetPerBBState(); 1753 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { 1754 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1755 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); 1756 1757 // Find the split point to split the parent mbb. At the same time copy all 1758 // physical registers used in the tail of parent mbb into virtual registers 1759 // before the split point and back into physical registers after the split 1760 // point. This prevents us needing to deal with Live-ins and many other 1761 // register allocation issues caused by us splitting the parent mbb. The 1762 // register allocator will clean up said virtual copies later on. 1763 MachineBasicBlock::iterator SplitPoint = 1764 FindSplitPointForStackProtector(ParentMBB); 1765 1766 // Splice the terminator of ParentMBB into SuccessMBB. 1767 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, 1768 SplitPoint, 1769 ParentMBB->end()); 1770 1771 // Add compare/jump on neq/jump to the parent BB. 1772 FuncInfo->MBB = ParentMBB; 1773 FuncInfo->InsertPt = ParentMBB->end(); 1774 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1775 CurDAG->setRoot(SDB->getRoot()); 1776 SDB->clear(); 1777 CodeGenAndEmitDAG(); 1778 1779 // CodeGen Failure MBB if we have not codegened it yet. 1780 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); 1781 if (FailureMBB->empty()) { 1782 FuncInfo->MBB = FailureMBB; 1783 FuncInfo->InsertPt = FailureMBB->end(); 1784 SDB->visitSPDescriptorFailure(SDB->SPDescriptor); 1785 CurDAG->setRoot(SDB->getRoot()); 1786 SDB->clear(); 1787 CodeGenAndEmitDAG(); 1788 } 1789 1790 // Clear the Per-BB State. 1791 SDB->SPDescriptor.resetPerBBState(); 1792 } 1793 1794 // Lower each BitTestBlock. 1795 for (auto &BTB : SDB->BitTestCases) { 1796 // Lower header first, if it wasn't already lowered 1797 if (!BTB.Emitted) { 1798 // Set the current basic block to the mbb we wish to insert the code into 1799 FuncInfo->MBB = BTB.Parent; 1800 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1801 // Emit the code 1802 SDB->visitBitTestHeader(BTB, FuncInfo->MBB); 1803 CurDAG->setRoot(SDB->getRoot()); 1804 SDB->clear(); 1805 CodeGenAndEmitDAG(); 1806 } 1807 1808 BranchProbability UnhandledProb = BTB.Prob; 1809 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { 1810 UnhandledProb -= BTB.Cases[j].ExtraProb; 1811 // Set the current basic block to the mbb we wish to insert the code into 1812 FuncInfo->MBB = BTB.Cases[j].ThisBB; 1813 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1814 // Emit the code 1815 1816 // If all cases cover a contiguous range, it is not necessary to jump to 1817 // the default block after the last bit test fails. This is because the 1818 // range check during bit test header creation has guaranteed that every 1819 // case here doesn't go outside the range. In this case, there is no need 1820 // to perform the last bit test, as it will always be true. Instead, make 1821 // the second-to-last bit-test fall through to the target of the last bit 1822 // test, and delete the last bit test. 1823 1824 MachineBasicBlock *NextMBB; 1825 if (BTB.ContiguousRange && j + 2 == ej) { 1826 // Second-to-last bit-test with contiguous range: fall through to the 1827 // target of the final bit test. 1828 NextMBB = BTB.Cases[j + 1].TargetBB; 1829 } else if (j + 1 == ej) { 1830 // For the last bit test, fall through to Default. 1831 NextMBB = BTB.Default; 1832 } else { 1833 // Otherwise, fall through to the next bit test. 1834 NextMBB = BTB.Cases[j + 1].ThisBB; 1835 } 1836 1837 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], 1838 FuncInfo->MBB); 1839 1840 CurDAG->setRoot(SDB->getRoot()); 1841 SDB->clear(); 1842 CodeGenAndEmitDAG(); 1843 1844 if (BTB.ContiguousRange && j + 2 == ej) { 1845 // Since we're not going to use the final bit test, remove it. 1846 BTB.Cases.pop_back(); 1847 break; 1848 } 1849 } 1850 1851 // Update PHI Nodes 1852 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 1853 pi != pe; ++pi) { 1854 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 1855 MachineBasicBlock *PHIBB = PHI->getParent(); 1856 assert(PHI->isPHI() && 1857 "This is not a machine PHI node that we are updating!"); 1858 // This is "default" BB. We have two jumps to it. From "header" BB and 1859 // from last "case" BB, unless the latter was skipped. 1860 if (PHIBB == BTB.Default) { 1861 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); 1862 if (!BTB.ContiguousRange) { 1863 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 1864 .addMBB(BTB.Cases.back().ThisBB); 1865 } 1866 } 1867 // One of "cases" BB. 1868 for (unsigned j = 0, ej = BTB.Cases.size(); 1869 j != ej; ++j) { 1870 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; 1871 if (cBB->isSuccessor(PHIBB)) 1872 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); 1873 } 1874 } 1875 } 1876 SDB->BitTestCases.clear(); 1877 1878 // If the JumpTable record is filled in, then we need to emit a jump table. 1879 // Updating the PHI nodes is tricky in this case, since we need to determine 1880 // whether the PHI is a successor of the range check MBB or the jump table MBB 1881 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) { 1882 // Lower header first, if it wasn't already lowered 1883 if (!SDB->JTCases[i].first.Emitted) { 1884 // Set the current basic block to the mbb we wish to insert the code into 1885 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB; 1886 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1887 // Emit the code 1888 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first, 1889 FuncInfo->MBB); 1890 CurDAG->setRoot(SDB->getRoot()); 1891 SDB->clear(); 1892 CodeGenAndEmitDAG(); 1893 } 1894 1895 // Set the current basic block to the mbb we wish to insert the code into 1896 FuncInfo->MBB = SDB->JTCases[i].second.MBB; 1897 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1898 // Emit the code 1899 SDB->visitJumpTable(SDB->JTCases[i].second); 1900 CurDAG->setRoot(SDB->getRoot()); 1901 SDB->clear(); 1902 CodeGenAndEmitDAG(); 1903 1904 // Update PHI Nodes 1905 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 1906 pi != pe; ++pi) { 1907 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 1908 MachineBasicBlock *PHIBB = PHI->getParent(); 1909 assert(PHI->isPHI() && 1910 "This is not a machine PHI node that we are updating!"); 1911 // "default" BB. We can go there only from header BB. 1912 if (PHIBB == SDB->JTCases[i].second.Default) 1913 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 1914 .addMBB(SDB->JTCases[i].first.HeaderBB); 1915 // JT BB. Just iterate over successors here 1916 if (FuncInfo->MBB->isSuccessor(PHIBB)) 1917 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); 1918 } 1919 } 1920 SDB->JTCases.clear(); 1921 1922 // If we generated any switch lowering information, build and codegen any 1923 // additional DAGs necessary. 1924 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) { 1925 // Set the current basic block to the mbb we wish to insert the code into 1926 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB; 1927 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1928 1929 // Determine the unique successors. 1930 SmallVector<MachineBasicBlock *, 2> Succs; 1931 Succs.push_back(SDB->SwitchCases[i].TrueBB); 1932 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB) 1933 Succs.push_back(SDB->SwitchCases[i].FalseBB); 1934 1935 // Emit the code. Note that this could result in FuncInfo->MBB being split. 1936 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB); 1937 CurDAG->setRoot(SDB->getRoot()); 1938 SDB->clear(); 1939 CodeGenAndEmitDAG(); 1940 1941 // Remember the last block, now that any splitting is done, for use in 1942 // populating PHI nodes in successors. 1943 MachineBasicBlock *ThisBB = FuncInfo->MBB; 1944 1945 // Handle any PHI nodes in successors of this chunk, as if we were coming 1946 // from the original BB before switch expansion. Note that PHI nodes can 1947 // occur multiple times in PHINodesToUpdate. We have to be very careful to 1948 // handle them the right number of times. 1949 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1950 FuncInfo->MBB = Succs[i]; 1951 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1952 // FuncInfo->MBB may have been removed from the CFG if a branch was 1953 // constant folded. 1954 if (ThisBB->isSuccessor(FuncInfo->MBB)) { 1955 for (MachineBasicBlock::iterator 1956 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); 1957 MBBI != MBBE && MBBI->isPHI(); ++MBBI) { 1958 MachineInstrBuilder PHI(*MF, MBBI); 1959 // This value for this PHI node is recorded in PHINodesToUpdate. 1960 for (unsigned pn = 0; ; ++pn) { 1961 assert(pn != FuncInfo->PHINodesToUpdate.size() && 1962 "Didn't find PHI entry!"); 1963 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { 1964 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); 1965 break; 1966 } 1967 } 1968 } 1969 } 1970 } 1971 } 1972 SDB->SwitchCases.clear(); 1973 } 1974 1975 /// Create the scheduler. If a specific scheduler was specified 1976 /// via the SchedulerRegistry, use it, otherwise select the 1977 /// one preferred by the target. 1978 /// 1979 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { 1980 return ISHeuristic(this, OptLevel); 1981 } 1982 1983 //===----------------------------------------------------------------------===// 1984 // Helper functions used by the generated instruction selector. 1985 //===----------------------------------------------------------------------===// 1986 // Calls to these methods are generated by tblgen. 1987 1988 /// CheckAndMask - The isel is trying to match something like (and X, 255). If 1989 /// the dag combiner simplified the 255, we still want to match. RHS is the 1990 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 1991 /// specified in the .td file (e.g. 255). 1992 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 1993 int64_t DesiredMaskS) const { 1994 const APInt &ActualMask = RHS->getAPIntValue(); 1995 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 1996 1997 // If the actual mask exactly matches, success! 1998 if (ActualMask == DesiredMask) 1999 return true; 2000 2001 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2002 if (ActualMask.intersects(~DesiredMask)) 2003 return false; 2004 2005 // Otherwise, the DAG Combiner may have proven that the value coming in is 2006 // either already zero or is not demanded. Check for known zero input bits. 2007 APInt NeededMask = DesiredMask & ~ActualMask; 2008 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 2009 return true; 2010 2011 // TODO: check to see if missing bits are just not demanded. 2012 2013 // Otherwise, this pattern doesn't match. 2014 return false; 2015 } 2016 2017 /// CheckOrMask - The isel is trying to match something like (or X, 255). If 2018 /// the dag combiner simplified the 255, we still want to match. RHS is the 2019 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 2020 /// specified in the .td file (e.g. 255). 2021 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 2022 int64_t DesiredMaskS) const { 2023 const APInt &ActualMask = RHS->getAPIntValue(); 2024 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 2025 2026 // If the actual mask exactly matches, success! 2027 if (ActualMask == DesiredMask) 2028 return true; 2029 2030 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2031 if (ActualMask.intersects(~DesiredMask)) 2032 return false; 2033 2034 // Otherwise, the DAG Combiner may have proven that the value coming in is 2035 // either already zero or is not demanded. Check for known zero input bits. 2036 APInt NeededMask = DesiredMask & ~ActualMask; 2037 2038 APInt KnownZero, KnownOne; 2039 CurDAG->computeKnownBits(LHS, KnownZero, KnownOne); 2040 2041 // If all the missing bits in the or are already known to be set, match! 2042 if ((NeededMask & KnownOne) == NeededMask) 2043 return true; 2044 2045 // TODO: check to see if missing bits are just not demanded. 2046 2047 // Otherwise, this pattern doesn't match. 2048 return false; 2049 } 2050 2051 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 2052 /// by tblgen. Others should not call it. 2053 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, 2054 const SDLoc &DL) { 2055 std::vector<SDValue> InOps; 2056 std::swap(InOps, Ops); 2057 2058 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 2059 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 2060 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc 2061 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) 2062 2063 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); 2064 if (InOps[e-1].getValueType() == MVT::Glue) 2065 --e; // Don't process a glue operand if it is here. 2066 2067 while (i != e) { 2068 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 2069 if (!InlineAsm::isMemKind(Flags)) { 2070 // Just skip over this operand, copying the operands verbatim. 2071 Ops.insert(Ops.end(), InOps.begin()+i, 2072 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); 2073 i += InlineAsm::getNumOperandRegisters(Flags) + 1; 2074 } else { 2075 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && 2076 "Memory operand with multiple values?"); 2077 2078 unsigned TiedToOperand; 2079 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { 2080 // We need the constraint ID from the operand this is tied to. 2081 unsigned CurOp = InlineAsm::Op_FirstOperand; 2082 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2083 for (; TiedToOperand; --TiedToOperand) { 2084 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; 2085 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2086 } 2087 } 2088 2089 // Otherwise, this is a memory operand. Ask the target to select it. 2090 std::vector<SDValue> SelOps; 2091 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags); 2092 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps)) 2093 report_fatal_error("Could not match memory address. Inline asm" 2094 " failure!"); 2095 2096 // Add this to the output node. 2097 unsigned NewFlags = 2098 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); 2099 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID); 2100 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); 2101 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 2102 i += 2; 2103 } 2104 } 2105 2106 // Add the glue input back if present. 2107 if (e != InOps.size()) 2108 Ops.push_back(InOps.back()); 2109 } 2110 2111 /// findGlueUse - Return use of MVT::Glue value produced by the specified 2112 /// SDNode. 2113 /// 2114 static SDNode *findGlueUse(SDNode *N) { 2115 unsigned FlagResNo = N->getNumValues()-1; 2116 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 2117 SDUse &Use = I.getUse(); 2118 if (Use.getResNo() == FlagResNo) 2119 return Use.getUser(); 2120 } 2121 return nullptr; 2122 } 2123 2124 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def". 2125 /// This function recursively traverses up the operand chain, ignoring 2126 /// certain nodes. 2127 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse, 2128 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited, 2129 bool IgnoreChains) { 2130 // The NodeID's are given uniques ID's where a node ID is guaranteed to be 2131 // greater than all of its (recursive) operands. If we scan to a point where 2132 // 'use' is smaller than the node we're scanning for, then we know we will 2133 // never find it. 2134 // 2135 // The Use may be -1 (unassigned) if it is a newly allocated node. This can 2136 // happen because we scan down to newly selected nodes in the case of glue 2137 // uses. 2138 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1)) 2139 return false; 2140 2141 // Don't revisit nodes if we already scanned it and didn't fail, we know we 2142 // won't fail if we scan it again. 2143 if (!Visited.insert(Use).second) 2144 return false; 2145 2146 for (const SDValue &Op : Use->op_values()) { 2147 // Ignore chain uses, they are validated by HandleMergeInputChains. 2148 if (Op.getValueType() == MVT::Other && IgnoreChains) 2149 continue; 2150 2151 SDNode *N = Op.getNode(); 2152 if (N == Def) { 2153 if (Use == ImmedUse || Use == Root) 2154 continue; // We are not looking for immediate use. 2155 assert(N != Root); 2156 return true; 2157 } 2158 2159 // Traverse up the operand chain. 2160 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains)) 2161 return true; 2162 } 2163 return false; 2164 } 2165 2166 /// IsProfitableToFold - Returns true if it's profitable to fold the specific 2167 /// operand node N of U during instruction selection that starts at Root. 2168 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, 2169 SDNode *Root) const { 2170 if (OptLevel == CodeGenOpt::None) return false; 2171 return N.hasOneUse(); 2172 } 2173 2174 /// IsLegalToFold - Returns true if the specific operand node N of 2175 /// U can be folded during instruction selection that starts at Root. 2176 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, 2177 CodeGenOpt::Level OptLevel, 2178 bool IgnoreChains) { 2179 if (OptLevel == CodeGenOpt::None) return false; 2180 2181 // If Root use can somehow reach N through a path that that doesn't contain 2182 // U then folding N would create a cycle. e.g. In the following 2183 // diagram, Root can reach N through X. If N is folded into into Root, then 2184 // X is both a predecessor and a successor of U. 2185 // 2186 // [N*] // 2187 // ^ ^ // 2188 // / \ // 2189 // [U*] [X]? // 2190 // ^ ^ // 2191 // \ / // 2192 // \ / // 2193 // [Root*] // 2194 // 2195 // * indicates nodes to be folded together. 2196 // 2197 // If Root produces glue, then it gets (even more) interesting. Since it 2198 // will be "glued" together with its glue use in the scheduler, we need to 2199 // check if it might reach N. 2200 // 2201 // [N*] // 2202 // ^ ^ // 2203 // / \ // 2204 // [U*] [X]? // 2205 // ^ ^ // 2206 // \ \ // 2207 // \ | // 2208 // [Root*] | // 2209 // ^ | // 2210 // f | // 2211 // | / // 2212 // [Y] / // 2213 // ^ / // 2214 // f / // 2215 // | / // 2216 // [GU] // 2217 // 2218 // If GU (glue use) indirectly reaches N (the load), and Root folds N 2219 // (call it Fold), then X is a predecessor of GU and a successor of 2220 // Fold. But since Fold and GU are glued together, this will create 2221 // a cycle in the scheduling graph. 2222 2223 // If the node has glue, walk down the graph to the "lowest" node in the 2224 // glueged set. 2225 EVT VT = Root->getValueType(Root->getNumValues()-1); 2226 while (VT == MVT::Glue) { 2227 SDNode *GU = findGlueUse(Root); 2228 if (!GU) 2229 break; 2230 Root = GU; 2231 VT = Root->getValueType(Root->getNumValues()-1); 2232 2233 // If our query node has a glue result with a use, we've walked up it. If 2234 // the user (which has already been selected) has a chain or indirectly uses 2235 // the chain, our WalkChainUsers predicate will not consider it. Because of 2236 // this, we cannot ignore chains in this predicate. 2237 IgnoreChains = false; 2238 } 2239 2240 2241 SmallPtrSet<SDNode*, 16> Visited; 2242 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains); 2243 } 2244 2245 void SelectionDAGISel::Select_INLINEASM(SDNode *N) { 2246 SDLoc DL(N); 2247 2248 std::vector<SDValue> Ops(N->op_begin(), N->op_end()); 2249 SelectInlineAsmMemoryOperands(Ops, DL); 2250 2251 const EVT VTs[] = {MVT::Other, MVT::Glue}; 2252 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops); 2253 New->setNodeId(-1); 2254 ReplaceUses(N, New.getNode()); 2255 CurDAG->RemoveDeadNode(N); 2256 } 2257 2258 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { 2259 SDLoc dl(Op); 2260 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2261 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2262 unsigned Reg = 2263 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0), 2264 *CurDAG); 2265 SDValue New = CurDAG->getCopyFromReg( 2266 Op->getOperand(0), dl, Reg, Op->getValueType(0)); 2267 New->setNodeId(-1); 2268 ReplaceUses(Op, New.getNode()); 2269 CurDAG->RemoveDeadNode(Op); 2270 } 2271 2272 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { 2273 SDLoc dl(Op); 2274 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2275 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2276 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), 2277 Op->getOperand(2).getValueType(), 2278 *CurDAG); 2279 SDValue New = CurDAG->getCopyToReg( 2280 Op->getOperand(0), dl, Reg, Op->getOperand(2)); 2281 New->setNodeId(-1); 2282 ReplaceUses(Op, New.getNode()); 2283 CurDAG->RemoveDeadNode(Op); 2284 } 2285 2286 void SelectionDAGISel::Select_UNDEF(SDNode *N) { 2287 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); 2288 } 2289 2290 /// GetVBR - decode a vbr encoding whose top bit is set. 2291 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t 2292 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { 2293 assert(Val >= 128 && "Not a VBR"); 2294 Val &= 127; // Remove first vbr bit. 2295 2296 unsigned Shift = 7; 2297 uint64_t NextBits; 2298 do { 2299 NextBits = MatcherTable[Idx++]; 2300 Val |= (NextBits&127) << Shift; 2301 Shift += 7; 2302 } while (NextBits & 128); 2303 2304 return Val; 2305 } 2306 2307 /// When a match is complete, this method updates uses of interior chain results 2308 /// to use the new results. 2309 void SelectionDAGISel::UpdateChains( 2310 SDNode *NodeToMatch, SDValue InputChain, 2311 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { 2312 SmallVector<SDNode*, 4> NowDeadNodes; 2313 2314 // Now that all the normal results are replaced, we replace the chain and 2315 // glue results if present. 2316 if (!ChainNodesMatched.empty()) { 2317 assert(InputChain.getNode() && 2318 "Matched input chains but didn't produce a chain"); 2319 // Loop over all of the nodes we matched that produced a chain result. 2320 // Replace all the chain results with the final chain we ended up with. 2321 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2322 SDNode *ChainNode = ChainNodesMatched[i]; 2323 // If ChainNode is null, it's because we replaced it on a previous 2324 // iteration and we cleared it out of the map. Just skip it. 2325 if (!ChainNode) 2326 continue; 2327 2328 assert(ChainNode->getOpcode() != ISD::DELETED_NODE && 2329 "Deleted node left in chain"); 2330 2331 // Don't replace the results of the root node if we're doing a 2332 // MorphNodeTo. 2333 if (ChainNode == NodeToMatch && isMorphNodeTo) 2334 continue; 2335 2336 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); 2337 if (ChainVal.getValueType() == MVT::Glue) 2338 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); 2339 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); 2340 SelectionDAG::DAGNodeDeletedListener NDL( 2341 *CurDAG, [&](SDNode *N, SDNode *E) { 2342 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N, 2343 static_cast<SDNode *>(nullptr)); 2344 }); 2345 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain); 2346 2347 // If the node became dead and we haven't already seen it, delete it. 2348 if (ChainNode != NodeToMatch && ChainNode->use_empty() && 2349 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) 2350 NowDeadNodes.push_back(ChainNode); 2351 } 2352 } 2353 2354 if (!NowDeadNodes.empty()) 2355 CurDAG->RemoveDeadNodes(NowDeadNodes); 2356 2357 DEBUG(dbgs() << "ISEL: Match complete!\n"); 2358 } 2359 2360 enum ChainResult { 2361 CR_Simple, 2362 CR_InducesCycle, 2363 CR_LeadsToInteriorNode 2364 }; 2365 2366 /// WalkChainUsers - Walk down the users of the specified chained node that is 2367 /// part of the pattern we're matching, looking at all of the users we find. 2368 /// This determines whether something is an interior node, whether we have a 2369 /// non-pattern node in between two pattern nodes (which prevent folding because 2370 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched 2371 /// between pattern nodes (in which case the TF becomes part of the pattern). 2372 /// 2373 /// The walk we do here is guaranteed to be small because we quickly get down to 2374 /// already selected nodes "below" us. 2375 static ChainResult 2376 WalkChainUsers(const SDNode *ChainedNode, 2377 SmallVectorImpl<SDNode *> &ChainedNodesInPattern, 2378 DenseMap<const SDNode *, ChainResult> &TokenFactorResult, 2379 SmallVectorImpl<SDNode *> &InteriorChainedNodes) { 2380 ChainResult Result = CR_Simple; 2381 2382 for (SDNode::use_iterator UI = ChainedNode->use_begin(), 2383 E = ChainedNode->use_end(); UI != E; ++UI) { 2384 // Make sure the use is of the chain, not some other value we produce. 2385 if (UI.getUse().getValueType() != MVT::Other) continue; 2386 2387 SDNode *User = *UI; 2388 2389 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph. 2390 continue; 2391 2392 // If we see an already-selected machine node, then we've gone beyond the 2393 // pattern that we're selecting down into the already selected chunk of the 2394 // DAG. 2395 unsigned UserOpcode = User->getOpcode(); 2396 if (User->isMachineOpcode() || 2397 UserOpcode == ISD::CopyToReg || 2398 UserOpcode == ISD::CopyFromReg || 2399 UserOpcode == ISD::INLINEASM || 2400 UserOpcode == ISD::EH_LABEL || 2401 UserOpcode == ISD::LIFETIME_START || 2402 UserOpcode == ISD::LIFETIME_END) { 2403 // If their node ID got reset to -1 then they've already been selected. 2404 // Treat them like a MachineOpcode. 2405 if (User->getNodeId() == -1) 2406 continue; 2407 } 2408 2409 // If we have a TokenFactor, we handle it specially. 2410 if (User->getOpcode() != ISD::TokenFactor) { 2411 // If the node isn't a token factor and isn't part of our pattern, then it 2412 // must be a random chained node in between two nodes we're selecting. 2413 // This happens when we have something like: 2414 // x = load ptr 2415 // call 2416 // y = x+4 2417 // store y -> ptr 2418 // Because we structurally match the load/store as a read/modify/write, 2419 // but the call is chained between them. We cannot fold in this case 2420 // because it would induce a cycle in the graph. 2421 if (!std::count(ChainedNodesInPattern.begin(), 2422 ChainedNodesInPattern.end(), User)) 2423 return CR_InducesCycle; 2424 2425 // Otherwise we found a node that is part of our pattern. For example in: 2426 // x = load ptr 2427 // y = x+4 2428 // store y -> ptr 2429 // This would happen when we're scanning down from the load and see the 2430 // store as a user. Record that there is a use of ChainedNode that is 2431 // part of the pattern and keep scanning uses. 2432 Result = CR_LeadsToInteriorNode; 2433 InteriorChainedNodes.push_back(User); 2434 continue; 2435 } 2436 2437 // If we found a TokenFactor, there are two cases to consider: first if the 2438 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no 2439 // uses of the TF are in our pattern) we just want to ignore it. Second, 2440 // the TokenFactor can be sandwiched in between two chained nodes, like so: 2441 // [Load chain] 2442 // ^ 2443 // | 2444 // [Load] 2445 // ^ ^ 2446 // | \ DAG's like cheese 2447 // / \ do you? 2448 // / | 2449 // [TokenFactor] [Op] 2450 // ^ ^ 2451 // | | 2452 // \ / 2453 // \ / 2454 // [Store] 2455 // 2456 // In this case, the TokenFactor becomes part of our match and we rewrite it 2457 // as a new TokenFactor. 2458 // 2459 // To distinguish these two cases, do a recursive walk down the uses. 2460 auto MemoizeResult = TokenFactorResult.find(User); 2461 bool Visited = MemoizeResult != TokenFactorResult.end(); 2462 // Recursively walk chain users only if the result is not memoized. 2463 if (!Visited) { 2464 auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult, 2465 InteriorChainedNodes); 2466 MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first; 2467 } 2468 switch (MemoizeResult->second) { 2469 case CR_Simple: 2470 // If the uses of the TokenFactor are just already-selected nodes, ignore 2471 // it, it is "below" our pattern. 2472 continue; 2473 case CR_InducesCycle: 2474 // If the uses of the TokenFactor lead to nodes that are not part of our 2475 // pattern that are not selected, folding would turn this into a cycle, 2476 // bail out now. 2477 return CR_InducesCycle; 2478 case CR_LeadsToInteriorNode: 2479 break; // Otherwise, keep processing. 2480 } 2481 2482 // Okay, we know we're in the interesting interior case. The TokenFactor 2483 // is now going to be considered part of the pattern so that we rewrite its 2484 // uses (it may have uses that are not part of the pattern) with the 2485 // ultimate chain result of the generated code. We will also add its chain 2486 // inputs as inputs to the ultimate TokenFactor we create. 2487 Result = CR_LeadsToInteriorNode; 2488 if (!Visited) { 2489 ChainedNodesInPattern.push_back(User); 2490 InteriorChainedNodes.push_back(User); 2491 } 2492 } 2493 2494 return Result; 2495 } 2496 2497 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains 2498 /// operation for when the pattern matched at least one node with a chains. The 2499 /// input vector contains a list of all of the chained nodes that we match. We 2500 /// must determine if this is a valid thing to cover (i.e. matching it won't 2501 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will 2502 /// be used as the input node chain for the generated nodes. 2503 static SDValue 2504 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, 2505 SelectionDAG *CurDAG) { 2506 // Used for memoization. Without it WalkChainUsers could take exponential 2507 // time to run. 2508 DenseMap<const SDNode *, ChainResult> TokenFactorResult; 2509 // Walk all of the chained nodes we've matched, recursively scanning down the 2510 // users of the chain result. This adds any TokenFactor nodes that are caught 2511 // in between chained nodes to the chained and interior nodes list. 2512 SmallVector<SDNode*, 3> InteriorChainedNodes; 2513 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2514 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched, 2515 TokenFactorResult, 2516 InteriorChainedNodes) == CR_InducesCycle) 2517 return SDValue(); // Would induce a cycle. 2518 } 2519 2520 // Okay, we have walked all the matched nodes and collected TokenFactor nodes 2521 // that we are interested in. Form our input TokenFactor node. 2522 SmallVector<SDValue, 3> InputChains; 2523 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2524 // Add the input chain of this node to the InputChains list (which will be 2525 // the operands of the generated TokenFactor) if it's not an interior node. 2526 SDNode *N = ChainNodesMatched[i]; 2527 if (N->getOpcode() != ISD::TokenFactor) { 2528 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N)) 2529 continue; 2530 2531 // Otherwise, add the input chain. 2532 SDValue InChain = ChainNodesMatched[i]->getOperand(0); 2533 assert(InChain.getValueType() == MVT::Other && "Not a chain"); 2534 InputChains.push_back(InChain); 2535 continue; 2536 } 2537 2538 // If we have a token factor, we want to add all inputs of the token factor 2539 // that are not part of the pattern we're matching. 2540 for (const SDValue &Op : N->op_values()) { 2541 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(), 2542 Op.getNode())) 2543 InputChains.push_back(Op); 2544 } 2545 } 2546 2547 if (InputChains.size() == 1) 2548 return InputChains[0]; 2549 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), 2550 MVT::Other, InputChains); 2551 } 2552 2553 /// MorphNode - Handle morphing a node in place for the selector. 2554 SDNode *SelectionDAGISel:: 2555 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, 2556 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { 2557 // It is possible we're using MorphNodeTo to replace a node with no 2558 // normal results with one that has a normal result (or we could be 2559 // adding a chain) and the input could have glue and chains as well. 2560 // In this case we need to shift the operands down. 2561 // FIXME: This is a horrible hack and broken in obscure cases, no worse 2562 // than the old isel though. 2563 int OldGlueResultNo = -1, OldChainResultNo = -1; 2564 2565 unsigned NTMNumResults = Node->getNumValues(); 2566 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { 2567 OldGlueResultNo = NTMNumResults-1; 2568 if (NTMNumResults != 1 && 2569 Node->getValueType(NTMNumResults-2) == MVT::Other) 2570 OldChainResultNo = NTMNumResults-2; 2571 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) 2572 OldChainResultNo = NTMNumResults-1; 2573 2574 // Call the underlying SelectionDAG routine to do the transmogrification. Note 2575 // that this deletes operands of the old node that become dead. 2576 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); 2577 2578 // MorphNodeTo can operate in two ways: if an existing node with the 2579 // specified operands exists, it can just return it. Otherwise, it 2580 // updates the node in place to have the requested operands. 2581 if (Res == Node) { 2582 // If we updated the node in place, reset the node ID. To the isel, 2583 // this should be just like a newly allocated machine node. 2584 Res->setNodeId(-1); 2585 } 2586 2587 unsigned ResNumResults = Res->getNumValues(); 2588 // Move the glue if needed. 2589 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && 2590 (unsigned)OldGlueResultNo != ResNumResults-1) 2591 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo), 2592 SDValue(Res, ResNumResults-1)); 2593 2594 if ((EmitNodeInfo & OPFL_GlueOutput) != 0) 2595 --ResNumResults; 2596 2597 // Move the chain reference if needed. 2598 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && 2599 (unsigned)OldChainResultNo != ResNumResults-1) 2600 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo), 2601 SDValue(Res, ResNumResults-1)); 2602 2603 // Otherwise, no replacement happened because the node already exists. Replace 2604 // Uses of the old node with the new one. 2605 if (Res != Node) { 2606 CurDAG->ReplaceAllUsesWith(Node, Res); 2607 CurDAG->RemoveDeadNode(Node); 2608 } 2609 2610 return Res; 2611 } 2612 2613 /// CheckSame - Implements OP_CheckSame. 2614 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2615 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2616 SDValue N, 2617 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { 2618 // Accept if it is exactly the same as a previously recorded node. 2619 unsigned RecNo = MatcherTable[MatcherIndex++]; 2620 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); 2621 return N == RecordedNodes[RecNo].first; 2622 } 2623 2624 /// CheckChildSame - Implements OP_CheckChildXSame. 2625 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2626 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2627 SDValue N, 2628 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes, 2629 unsigned ChildNo) { 2630 if (ChildNo >= N.getNumOperands()) 2631 return false; // Match fails if out of range child #. 2632 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), 2633 RecordedNodes); 2634 } 2635 2636 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. 2637 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2638 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2639 const SelectionDAGISel &SDISel) { 2640 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); 2641 } 2642 2643 /// CheckNodePredicate - Implements OP_CheckNodePredicate. 2644 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2645 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2646 const SelectionDAGISel &SDISel, SDNode *N) { 2647 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); 2648 } 2649 2650 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2651 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2652 SDNode *N) { 2653 uint16_t Opc = MatcherTable[MatcherIndex++]; 2654 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 2655 return N->getOpcode() == Opc; 2656 } 2657 2658 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2659 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, 2660 const TargetLowering *TLI, const DataLayout &DL) { 2661 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2662 if (N.getValueType() == VT) return true; 2663 2664 // Handle the case when VT is iPTR. 2665 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); 2666 } 2667 2668 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2669 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2670 SDValue N, const TargetLowering *TLI, const DataLayout &DL, 2671 unsigned ChildNo) { 2672 if (ChildNo >= N.getNumOperands()) 2673 return false; // Match fails if out of range child #. 2674 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, 2675 DL); 2676 } 2677 2678 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2679 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2680 SDValue N) { 2681 return cast<CondCodeSDNode>(N)->get() == 2682 (ISD::CondCode)MatcherTable[MatcherIndex++]; 2683 } 2684 2685 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2686 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2687 SDValue N, const TargetLowering *TLI, const DataLayout &DL) { 2688 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2689 if (cast<VTSDNode>(N)->getVT() == VT) 2690 return true; 2691 2692 // Handle the case when VT is iPTR. 2693 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); 2694 } 2695 2696 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2697 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2698 SDValue N) { 2699 int64_t Val = MatcherTable[MatcherIndex++]; 2700 if (Val & 128) 2701 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2702 2703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 2704 return C && C->getSExtValue() == Val; 2705 } 2706 2707 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2708 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2709 SDValue N, unsigned ChildNo) { 2710 if (ChildNo >= N.getNumOperands()) 2711 return false; // Match fails if out of range child #. 2712 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); 2713 } 2714 2715 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2716 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2717 SDValue N, const SelectionDAGISel &SDISel) { 2718 int64_t Val = MatcherTable[MatcherIndex++]; 2719 if (Val & 128) 2720 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2721 2722 if (N->getOpcode() != ISD::AND) return false; 2723 2724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2725 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); 2726 } 2727 2728 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2729 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2730 SDValue N, const SelectionDAGISel &SDISel) { 2731 int64_t Val = MatcherTable[MatcherIndex++]; 2732 if (Val & 128) 2733 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2734 2735 if (N->getOpcode() != ISD::OR) return false; 2736 2737 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2738 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); 2739 } 2740 2741 /// IsPredicateKnownToFail - If we know how and can do so without pushing a 2742 /// scope, evaluate the current node. If the current predicate is known to 2743 /// fail, set Result=true and return anything. If the current predicate is 2744 /// known to pass, set Result=false and return the MatcherIndex to continue 2745 /// with. If the current predicate is unknown, set Result=false and return the 2746 /// MatcherIndex to continue with. 2747 static unsigned IsPredicateKnownToFail(const unsigned char *Table, 2748 unsigned Index, SDValue N, 2749 bool &Result, 2750 const SelectionDAGISel &SDISel, 2751 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { 2752 switch (Table[Index++]) { 2753 default: 2754 Result = false; 2755 return Index-1; // Could not evaluate this predicate. 2756 case SelectionDAGISel::OPC_CheckSame: 2757 Result = !::CheckSame(Table, Index, N, RecordedNodes); 2758 return Index; 2759 case SelectionDAGISel::OPC_CheckChild0Same: 2760 case SelectionDAGISel::OPC_CheckChild1Same: 2761 case SelectionDAGISel::OPC_CheckChild2Same: 2762 case SelectionDAGISel::OPC_CheckChild3Same: 2763 Result = !::CheckChildSame(Table, Index, N, RecordedNodes, 2764 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); 2765 return Index; 2766 case SelectionDAGISel::OPC_CheckPatternPredicate: 2767 Result = !::CheckPatternPredicate(Table, Index, SDISel); 2768 return Index; 2769 case SelectionDAGISel::OPC_CheckPredicate: 2770 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); 2771 return Index; 2772 case SelectionDAGISel::OPC_CheckOpcode: 2773 Result = !::CheckOpcode(Table, Index, N.getNode()); 2774 return Index; 2775 case SelectionDAGISel::OPC_CheckType: 2776 Result = !::CheckType(Table, Index, N, SDISel.TLI, 2777 SDISel.CurDAG->getDataLayout()); 2778 return Index; 2779 case SelectionDAGISel::OPC_CheckChild0Type: 2780 case SelectionDAGISel::OPC_CheckChild1Type: 2781 case SelectionDAGISel::OPC_CheckChild2Type: 2782 case SelectionDAGISel::OPC_CheckChild3Type: 2783 case SelectionDAGISel::OPC_CheckChild4Type: 2784 case SelectionDAGISel::OPC_CheckChild5Type: 2785 case SelectionDAGISel::OPC_CheckChild6Type: 2786 case SelectionDAGISel::OPC_CheckChild7Type: 2787 Result = !::CheckChildType( 2788 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), 2789 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); 2790 return Index; 2791 case SelectionDAGISel::OPC_CheckCondCode: 2792 Result = !::CheckCondCode(Table, Index, N); 2793 return Index; 2794 case SelectionDAGISel::OPC_CheckValueType: 2795 Result = !::CheckValueType(Table, Index, N, SDISel.TLI, 2796 SDISel.CurDAG->getDataLayout()); 2797 return Index; 2798 case SelectionDAGISel::OPC_CheckInteger: 2799 Result = !::CheckInteger(Table, Index, N); 2800 return Index; 2801 case SelectionDAGISel::OPC_CheckChild0Integer: 2802 case SelectionDAGISel::OPC_CheckChild1Integer: 2803 case SelectionDAGISel::OPC_CheckChild2Integer: 2804 case SelectionDAGISel::OPC_CheckChild3Integer: 2805 case SelectionDAGISel::OPC_CheckChild4Integer: 2806 Result = !::CheckChildInteger(Table, Index, N, 2807 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); 2808 return Index; 2809 case SelectionDAGISel::OPC_CheckAndImm: 2810 Result = !::CheckAndImm(Table, Index, N, SDISel); 2811 return Index; 2812 case SelectionDAGISel::OPC_CheckOrImm: 2813 Result = !::CheckOrImm(Table, Index, N, SDISel); 2814 return Index; 2815 } 2816 } 2817 2818 namespace { 2819 struct MatchScope { 2820 /// FailIndex - If this match fails, this is the index to continue with. 2821 unsigned FailIndex; 2822 2823 /// NodeStack - The node stack when the scope was formed. 2824 SmallVector<SDValue, 4> NodeStack; 2825 2826 /// NumRecordedNodes - The number of recorded nodes when the scope was formed. 2827 unsigned NumRecordedNodes; 2828 2829 /// NumMatchedMemRefs - The number of matched memref entries. 2830 unsigned NumMatchedMemRefs; 2831 2832 /// InputChain/InputGlue - The current chain/glue 2833 SDValue InputChain, InputGlue; 2834 2835 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. 2836 bool HasChainNodesMatched; 2837 }; 2838 2839 /// \\brief A DAG update listener to keep the matching state 2840 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to 2841 /// change the DAG while matching. X86 addressing mode matcher is an example 2842 /// for this. 2843 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener 2844 { 2845 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes; 2846 SmallVectorImpl<MatchScope> &MatchScopes; 2847 public: 2848 MatchStateUpdater(SelectionDAG &DAG, 2849 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN, 2850 SmallVectorImpl<MatchScope> &MS) : 2851 SelectionDAG::DAGUpdateListener(DAG), 2852 RecordedNodes(RN), MatchScopes(MS) { } 2853 2854 void NodeDeleted(SDNode *N, SDNode *E) override { 2855 // Some early-returns here to avoid the search if we deleted the node or 2856 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we 2857 // do, so it's unnecessary to update matching state at that point). 2858 // Neither of these can occur currently because we only install this 2859 // update listener during matching a complex patterns. 2860 if (!E || E->isMachineOpcode()) 2861 return; 2862 // Performing linear search here does not matter because we almost never 2863 // run this code. You'd have to have a CSE during complex pattern 2864 // matching. 2865 for (auto &I : RecordedNodes) 2866 if (I.first.getNode() == N) 2867 I.first.setNode(E); 2868 2869 for (auto &I : MatchScopes) 2870 for (auto &J : I.NodeStack) 2871 if (J.getNode() == N) 2872 J.setNode(E); 2873 } 2874 }; 2875 } // end anonymous namespace 2876 2877 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, 2878 const unsigned char *MatcherTable, 2879 unsigned TableSize) { 2880 // FIXME: Should these even be selected? Handle these cases in the caller? 2881 switch (NodeToMatch->getOpcode()) { 2882 default: 2883 break; 2884 case ISD::EntryToken: // These nodes remain the same. 2885 case ISD::BasicBlock: 2886 case ISD::Register: 2887 case ISD::RegisterMask: 2888 case ISD::HANDLENODE: 2889 case ISD::MDNODE_SDNODE: 2890 case ISD::TargetConstant: 2891 case ISD::TargetConstantFP: 2892 case ISD::TargetConstantPool: 2893 case ISD::TargetFrameIndex: 2894 case ISD::TargetExternalSymbol: 2895 case ISD::MCSymbol: 2896 case ISD::TargetBlockAddress: 2897 case ISD::TargetJumpTable: 2898 case ISD::TargetGlobalTLSAddress: 2899 case ISD::TargetGlobalAddress: 2900 case ISD::TokenFactor: 2901 case ISD::CopyFromReg: 2902 case ISD::CopyToReg: 2903 case ISD::EH_LABEL: 2904 case ISD::LIFETIME_START: 2905 case ISD::LIFETIME_END: 2906 NodeToMatch->setNodeId(-1); // Mark selected. 2907 return; 2908 case ISD::AssertSext: 2909 case ISD::AssertZext: 2910 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0), 2911 NodeToMatch->getOperand(0)); 2912 CurDAG->RemoveDeadNode(NodeToMatch); 2913 return; 2914 case ISD::INLINEASM: 2915 Select_INLINEASM(NodeToMatch); 2916 return; 2917 case ISD::READ_REGISTER: 2918 Select_READ_REGISTER(NodeToMatch); 2919 return; 2920 case ISD::WRITE_REGISTER: 2921 Select_WRITE_REGISTER(NodeToMatch); 2922 return; 2923 case ISD::UNDEF: 2924 Select_UNDEF(NodeToMatch); 2925 return; 2926 } 2927 2928 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); 2929 2930 // Set up the node stack with NodeToMatch as the only node on the stack. 2931 SmallVector<SDValue, 8> NodeStack; 2932 SDValue N = SDValue(NodeToMatch, 0); 2933 NodeStack.push_back(N); 2934 2935 // MatchScopes - Scopes used when matching, if a match failure happens, this 2936 // indicates where to continue checking. 2937 SmallVector<MatchScope, 8> MatchScopes; 2938 2939 // RecordedNodes - This is the set of nodes that have been recorded by the 2940 // state machine. The second value is the parent of the node, or null if the 2941 // root is recorded. 2942 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; 2943 2944 // MatchedMemRefs - This is the set of MemRef's we've seen in the input 2945 // pattern. 2946 SmallVector<MachineMemOperand*, 2> MatchedMemRefs; 2947 2948 // These are the current input chain and glue for use when generating nodes. 2949 // Various Emit operations change these. For example, emitting a copytoreg 2950 // uses and updates these. 2951 SDValue InputChain, InputGlue; 2952 2953 // ChainNodesMatched - If a pattern matches nodes that have input/output 2954 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates 2955 // which ones they are. The result is captured into this list so that we can 2956 // update the chain results when the pattern is complete. 2957 SmallVector<SDNode*, 3> ChainNodesMatched; 2958 2959 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: "; 2960 NodeToMatch->dump(CurDAG); 2961 dbgs() << '\n'); 2962 2963 // Determine where to start the interpreter. Normally we start at opcode #0, 2964 // but if the state machine starts with an OPC_SwitchOpcode, then we 2965 // accelerate the first lookup (which is guaranteed to be hot) with the 2966 // OpcodeOffset table. 2967 unsigned MatcherIndex = 0; 2968 2969 if (!OpcodeOffset.empty()) { 2970 // Already computed the OpcodeOffset table, just index into it. 2971 if (N.getOpcode() < OpcodeOffset.size()) 2972 MatcherIndex = OpcodeOffset[N.getOpcode()]; 2973 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); 2974 2975 } else if (MatcherTable[0] == OPC_SwitchOpcode) { 2976 // Otherwise, the table isn't computed, but the state machine does start 2977 // with an OPC_SwitchOpcode instruction. Populate the table now, since this 2978 // is the first time we're selecting an instruction. 2979 unsigned Idx = 1; 2980 while (1) { 2981 // Get the size of this case. 2982 unsigned CaseSize = MatcherTable[Idx++]; 2983 if (CaseSize & 128) 2984 CaseSize = GetVBR(CaseSize, MatcherTable, Idx); 2985 if (CaseSize == 0) break; 2986 2987 // Get the opcode, add the index to the table. 2988 uint16_t Opc = MatcherTable[Idx++]; 2989 Opc |= (unsigned short)MatcherTable[Idx++] << 8; 2990 if (Opc >= OpcodeOffset.size()) 2991 OpcodeOffset.resize((Opc+1)*2); 2992 OpcodeOffset[Opc] = Idx; 2993 Idx += CaseSize; 2994 } 2995 2996 // Okay, do the lookup for the first opcode. 2997 if (N.getOpcode() < OpcodeOffset.size()) 2998 MatcherIndex = OpcodeOffset[N.getOpcode()]; 2999 } 3000 3001 while (1) { 3002 assert(MatcherIndex < TableSize && "Invalid index"); 3003 #ifndef NDEBUG 3004 unsigned CurrentOpcodeIndex = MatcherIndex; 3005 #endif 3006 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; 3007 switch (Opcode) { 3008 case OPC_Scope: { 3009 // Okay, the semantics of this operation are that we should push a scope 3010 // then evaluate the first child. However, pushing a scope only to have 3011 // the first check fail (which then pops it) is inefficient. If we can 3012 // determine immediately that the first check (or first several) will 3013 // immediately fail, don't even bother pushing a scope for them. 3014 unsigned FailIndex; 3015 3016 while (1) { 3017 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3018 if (NumToSkip & 128) 3019 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3020 // Found the end of the scope with no match. 3021 if (NumToSkip == 0) { 3022 FailIndex = 0; 3023 break; 3024 } 3025 3026 FailIndex = MatcherIndex+NumToSkip; 3027 3028 unsigned MatcherIndexOfPredicate = MatcherIndex; 3029 (void)MatcherIndexOfPredicate; // silence warning. 3030 3031 // If we can't evaluate this predicate without pushing a scope (e.g. if 3032 // it is a 'MoveParent') or if the predicate succeeds on this node, we 3033 // push the scope and evaluate the full predicate chain. 3034 bool Result; 3035 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, 3036 Result, *this, RecordedNodes); 3037 if (!Result) 3038 break; 3039 3040 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at " 3041 << "index " << MatcherIndexOfPredicate 3042 << ", continuing at " << FailIndex << "\n"); 3043 ++NumDAGIselRetries; 3044 3045 // Otherwise, we know that this case of the Scope is guaranteed to fail, 3046 // move to the next case. 3047 MatcherIndex = FailIndex; 3048 } 3049 3050 // If the whole scope failed to match, bail. 3051 if (FailIndex == 0) break; 3052 3053 // Push a MatchScope which indicates where to go if the first child fails 3054 // to match. 3055 MatchScope NewEntry; 3056 NewEntry.FailIndex = FailIndex; 3057 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); 3058 NewEntry.NumRecordedNodes = RecordedNodes.size(); 3059 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); 3060 NewEntry.InputChain = InputChain; 3061 NewEntry.InputGlue = InputGlue; 3062 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); 3063 MatchScopes.push_back(NewEntry); 3064 continue; 3065 } 3066 case OPC_RecordNode: { 3067 // Remember this node, it may end up being an operand in the pattern. 3068 SDNode *Parent = nullptr; 3069 if (NodeStack.size() > 1) 3070 Parent = NodeStack[NodeStack.size()-2].getNode(); 3071 RecordedNodes.push_back(std::make_pair(N, Parent)); 3072 continue; 3073 } 3074 3075 case OPC_RecordChild0: case OPC_RecordChild1: 3076 case OPC_RecordChild2: case OPC_RecordChild3: 3077 case OPC_RecordChild4: case OPC_RecordChild5: 3078 case OPC_RecordChild6: case OPC_RecordChild7: { 3079 unsigned ChildNo = Opcode-OPC_RecordChild0; 3080 if (ChildNo >= N.getNumOperands()) 3081 break; // Match fails if out of range child #. 3082 3083 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), 3084 N.getNode())); 3085 continue; 3086 } 3087 case OPC_RecordMemRef: 3088 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand()); 3089 continue; 3090 3091 case OPC_CaptureGlueInput: 3092 // If the current node has an input glue, capture it in InputGlue. 3093 if (N->getNumOperands() != 0 && 3094 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) 3095 InputGlue = N->getOperand(N->getNumOperands()-1); 3096 continue; 3097 3098 case OPC_MoveChild: { 3099 unsigned ChildNo = MatcherTable[MatcherIndex++]; 3100 if (ChildNo >= N.getNumOperands()) 3101 break; // Match fails if out of range child #. 3102 N = N.getOperand(ChildNo); 3103 NodeStack.push_back(N); 3104 continue; 3105 } 3106 3107 case OPC_MoveChild0: case OPC_MoveChild1: 3108 case OPC_MoveChild2: case OPC_MoveChild3: 3109 case OPC_MoveChild4: case OPC_MoveChild5: 3110 case OPC_MoveChild6: case OPC_MoveChild7: { 3111 unsigned ChildNo = Opcode-OPC_MoveChild0; 3112 if (ChildNo >= N.getNumOperands()) 3113 break; // Match fails if out of range child #. 3114 N = N.getOperand(ChildNo); 3115 NodeStack.push_back(N); 3116 continue; 3117 } 3118 3119 case OPC_MoveParent: 3120 // Pop the current node off the NodeStack. 3121 NodeStack.pop_back(); 3122 assert(!NodeStack.empty() && "Node stack imbalance!"); 3123 N = NodeStack.back(); 3124 continue; 3125 3126 case OPC_CheckSame: 3127 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; 3128 continue; 3129 3130 case OPC_CheckChild0Same: case OPC_CheckChild1Same: 3131 case OPC_CheckChild2Same: case OPC_CheckChild3Same: 3132 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, 3133 Opcode-OPC_CheckChild0Same)) 3134 break; 3135 continue; 3136 3137 case OPC_CheckPatternPredicate: 3138 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; 3139 continue; 3140 case OPC_CheckPredicate: 3141 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, 3142 N.getNode())) 3143 break; 3144 continue; 3145 case OPC_CheckComplexPat: { 3146 unsigned CPNum = MatcherTable[MatcherIndex++]; 3147 unsigned RecNo = MatcherTable[MatcherIndex++]; 3148 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); 3149 3150 // If target can modify DAG during matching, keep the matching state 3151 // consistent. 3152 std::unique_ptr<MatchStateUpdater> MSU; 3153 if (ComplexPatternFuncMutatesDAG()) 3154 MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes, 3155 MatchScopes)); 3156 3157 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, 3158 RecordedNodes[RecNo].first, CPNum, 3159 RecordedNodes)) 3160 break; 3161 continue; 3162 } 3163 case OPC_CheckOpcode: 3164 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; 3165 continue; 3166 3167 case OPC_CheckType: 3168 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, 3169 CurDAG->getDataLayout())) 3170 break; 3171 continue; 3172 3173 case OPC_SwitchOpcode: { 3174 unsigned CurNodeOpcode = N.getOpcode(); 3175 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3176 unsigned CaseSize; 3177 while (1) { 3178 // Get the size of this case. 3179 CaseSize = MatcherTable[MatcherIndex++]; 3180 if (CaseSize & 128) 3181 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3182 if (CaseSize == 0) break; 3183 3184 uint16_t Opc = MatcherTable[MatcherIndex++]; 3185 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3186 3187 // If the opcode matches, then we will execute this case. 3188 if (CurNodeOpcode == Opc) 3189 break; 3190 3191 // Otherwise, skip over this case. 3192 MatcherIndex += CaseSize; 3193 } 3194 3195 // If no cases matched, bail out. 3196 if (CaseSize == 0) break; 3197 3198 // Otherwise, execute the case we found. 3199 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart 3200 << " to " << MatcherIndex << "\n"); 3201 continue; 3202 } 3203 3204 case OPC_SwitchType: { 3205 MVT CurNodeVT = N.getSimpleValueType(); 3206 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3207 unsigned CaseSize; 3208 while (1) { 3209 // Get the size of this case. 3210 CaseSize = MatcherTable[MatcherIndex++]; 3211 if (CaseSize & 128) 3212 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3213 if (CaseSize == 0) break; 3214 3215 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3216 if (CaseVT == MVT::iPTR) 3217 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); 3218 3219 // If the VT matches, then we will execute this case. 3220 if (CurNodeVT == CaseVT) 3221 break; 3222 3223 // Otherwise, skip over this case. 3224 MatcherIndex += CaseSize; 3225 } 3226 3227 // If no cases matched, bail out. 3228 if (CaseSize == 0) break; 3229 3230 // Otherwise, execute the case we found. 3231 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() 3232 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n'); 3233 continue; 3234 } 3235 case OPC_CheckChild0Type: case OPC_CheckChild1Type: 3236 case OPC_CheckChild2Type: case OPC_CheckChild3Type: 3237 case OPC_CheckChild4Type: case OPC_CheckChild5Type: 3238 case OPC_CheckChild6Type: case OPC_CheckChild7Type: 3239 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, 3240 CurDAG->getDataLayout(), 3241 Opcode - OPC_CheckChild0Type)) 3242 break; 3243 continue; 3244 case OPC_CheckCondCode: 3245 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; 3246 continue; 3247 case OPC_CheckValueType: 3248 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, 3249 CurDAG->getDataLayout())) 3250 break; 3251 continue; 3252 case OPC_CheckInteger: 3253 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; 3254 continue; 3255 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: 3256 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: 3257 case OPC_CheckChild4Integer: 3258 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, 3259 Opcode-OPC_CheckChild0Integer)) break; 3260 continue; 3261 case OPC_CheckAndImm: 3262 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; 3263 continue; 3264 case OPC_CheckOrImm: 3265 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; 3266 continue; 3267 3268 case OPC_CheckFoldableChainNode: { 3269 assert(NodeStack.size() != 1 && "No parent node"); 3270 // Verify that all intermediate nodes between the root and this one have 3271 // a single use. 3272 bool HasMultipleUses = false; 3273 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) 3274 if (!NodeStack[i].hasOneUse()) { 3275 HasMultipleUses = true; 3276 break; 3277 } 3278 if (HasMultipleUses) break; 3279 3280 // Check to see that the target thinks this is profitable to fold and that 3281 // we can fold it without inducing cycles in the graph. 3282 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3283 NodeToMatch) || 3284 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3285 NodeToMatch, OptLevel, 3286 true/*We validate our own chains*/)) 3287 break; 3288 3289 continue; 3290 } 3291 case OPC_EmitInteger: { 3292 MVT::SimpleValueType VT = 3293 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3294 int64_t Val = MatcherTable[MatcherIndex++]; 3295 if (Val & 128) 3296 Val = GetVBR(Val, MatcherTable, MatcherIndex); 3297 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3298 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), 3299 VT), nullptr)); 3300 continue; 3301 } 3302 case OPC_EmitRegister: { 3303 MVT::SimpleValueType VT = 3304 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3305 unsigned RegNo = MatcherTable[MatcherIndex++]; 3306 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3307 CurDAG->getRegister(RegNo, VT), nullptr)); 3308 continue; 3309 } 3310 case OPC_EmitRegister2: { 3311 // For targets w/ more than 256 register names, the register enum 3312 // values are stored in two bytes in the matcher table (just like 3313 // opcodes). 3314 MVT::SimpleValueType VT = 3315 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3316 unsigned RegNo = MatcherTable[MatcherIndex++]; 3317 RegNo |= MatcherTable[MatcherIndex++] << 8; 3318 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3319 CurDAG->getRegister(RegNo, VT), nullptr)); 3320 continue; 3321 } 3322 3323 case OPC_EmitConvertToTarget: { 3324 // Convert from IMM/FPIMM to target version. 3325 unsigned RecNo = MatcherTable[MatcherIndex++]; 3326 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); 3327 SDValue Imm = RecordedNodes[RecNo].first; 3328 3329 if (Imm->getOpcode() == ISD::Constant) { 3330 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); 3331 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), 3332 Imm.getValueType()); 3333 } else if (Imm->getOpcode() == ISD::ConstantFP) { 3334 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); 3335 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), 3336 Imm.getValueType()); 3337 } 3338 3339 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); 3340 continue; 3341 } 3342 3343 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 3344 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 3345 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 3346 // These are space-optimized forms of OPC_EmitMergeInputChains. 3347 assert(!InputChain.getNode() && 3348 "EmitMergeInputChains should be the first chain producing node"); 3349 assert(ChainNodesMatched.empty() && 3350 "Should only have one EmitMergeInputChains per match"); 3351 3352 // Read all of the chained nodes. 3353 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; 3354 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3355 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3356 3357 // FIXME: What if other value results of the node have uses not matched 3358 // by this pattern? 3359 if (ChainNodesMatched.back() != NodeToMatch && 3360 !RecordedNodes[RecNo].first.hasOneUse()) { 3361 ChainNodesMatched.clear(); 3362 break; 3363 } 3364 3365 // Merge the input chains if they are not intra-pattern references. 3366 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3367 3368 if (!InputChain.getNode()) 3369 break; // Failed to merge. 3370 continue; 3371 } 3372 3373 case OPC_EmitMergeInputChains: { 3374 assert(!InputChain.getNode() && 3375 "EmitMergeInputChains should be the first chain producing node"); 3376 // This node gets a list of nodes we matched in the input that have 3377 // chains. We want to token factor all of the input chains to these nodes 3378 // together. However, if any of the input chains is actually one of the 3379 // nodes matched in this pattern, then we have an intra-match reference. 3380 // Ignore these because the newly token factored chain should not refer to 3381 // the old nodes. 3382 unsigned NumChains = MatcherTable[MatcherIndex++]; 3383 assert(NumChains != 0 && "Can't TF zero chains"); 3384 3385 assert(ChainNodesMatched.empty() && 3386 "Should only have one EmitMergeInputChains per match"); 3387 3388 // Read all of the chained nodes. 3389 for (unsigned i = 0; i != NumChains; ++i) { 3390 unsigned RecNo = MatcherTable[MatcherIndex++]; 3391 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3392 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3393 3394 // FIXME: What if other value results of the node have uses not matched 3395 // by this pattern? 3396 if (ChainNodesMatched.back() != NodeToMatch && 3397 !RecordedNodes[RecNo].first.hasOneUse()) { 3398 ChainNodesMatched.clear(); 3399 break; 3400 } 3401 } 3402 3403 // If the inner loop broke out, the match fails. 3404 if (ChainNodesMatched.empty()) 3405 break; 3406 3407 // Merge the input chains if they are not intra-pattern references. 3408 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3409 3410 if (!InputChain.getNode()) 3411 break; // Failed to merge. 3412 3413 continue; 3414 } 3415 3416 case OPC_EmitCopyToReg: { 3417 unsigned RecNo = MatcherTable[MatcherIndex++]; 3418 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); 3419 unsigned DestPhysReg = MatcherTable[MatcherIndex++]; 3420 3421 if (!InputChain.getNode()) 3422 InputChain = CurDAG->getEntryNode(); 3423 3424 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), 3425 DestPhysReg, RecordedNodes[RecNo].first, 3426 InputGlue); 3427 3428 InputGlue = InputChain.getValue(1); 3429 continue; 3430 } 3431 3432 case OPC_EmitNodeXForm: { 3433 unsigned XFormNo = MatcherTable[MatcherIndex++]; 3434 unsigned RecNo = MatcherTable[MatcherIndex++]; 3435 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); 3436 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); 3437 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); 3438 continue; 3439 } 3440 3441 case OPC_EmitNode: case OPC_MorphNodeTo: 3442 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: 3443 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { 3444 uint16_t TargetOpc = MatcherTable[MatcherIndex++]; 3445 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3446 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; 3447 // Get the result VT list. 3448 unsigned NumVTs; 3449 // If this is one of the compressed forms, get the number of VTs based 3450 // on the Opcode. Otherwise read the next byte from the table. 3451 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) 3452 NumVTs = Opcode - OPC_MorphNodeTo0; 3453 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) 3454 NumVTs = Opcode - OPC_EmitNode0; 3455 else 3456 NumVTs = MatcherTable[MatcherIndex++]; 3457 SmallVector<EVT, 4> VTs; 3458 for (unsigned i = 0; i != NumVTs; ++i) { 3459 MVT::SimpleValueType VT = 3460 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3461 if (VT == MVT::iPTR) 3462 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; 3463 VTs.push_back(VT); 3464 } 3465 3466 if (EmitNodeInfo & OPFL_Chain) 3467 VTs.push_back(MVT::Other); 3468 if (EmitNodeInfo & OPFL_GlueOutput) 3469 VTs.push_back(MVT::Glue); 3470 3471 // This is hot code, so optimize the two most common cases of 1 and 2 3472 // results. 3473 SDVTList VTList; 3474 if (VTs.size() == 1) 3475 VTList = CurDAG->getVTList(VTs[0]); 3476 else if (VTs.size() == 2) 3477 VTList = CurDAG->getVTList(VTs[0], VTs[1]); 3478 else 3479 VTList = CurDAG->getVTList(VTs); 3480 3481 // Get the operand list. 3482 unsigned NumOps = MatcherTable[MatcherIndex++]; 3483 SmallVector<SDValue, 8> Ops; 3484 for (unsigned i = 0; i != NumOps; ++i) { 3485 unsigned RecNo = MatcherTable[MatcherIndex++]; 3486 if (RecNo & 128) 3487 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); 3488 3489 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); 3490 Ops.push_back(RecordedNodes[RecNo].first); 3491 } 3492 3493 // If there are variadic operands to add, handle them now. 3494 if (EmitNodeInfo & OPFL_VariadicInfo) { 3495 // Determine the start index to copy from. 3496 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); 3497 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; 3498 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && 3499 "Invalid variadic node"); 3500 // Copy all of the variadic operands, not including a potential glue 3501 // input. 3502 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); 3503 i != e; ++i) { 3504 SDValue V = NodeToMatch->getOperand(i); 3505 if (V.getValueType() == MVT::Glue) break; 3506 Ops.push_back(V); 3507 } 3508 } 3509 3510 // If this has chain/glue inputs, add them. 3511 if (EmitNodeInfo & OPFL_Chain) 3512 Ops.push_back(InputChain); 3513 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) 3514 Ops.push_back(InputGlue); 3515 3516 // Create the node. 3517 SDNode *Res = nullptr; 3518 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || 3519 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); 3520 if (!IsMorphNodeTo) { 3521 // If this is a normal EmitNode command, just create the new node and 3522 // add the results to the RecordedNodes list. 3523 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), 3524 VTList, Ops); 3525 3526 // Add all the non-glue/non-chain results to the RecordedNodes list. 3527 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 3528 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; 3529 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), 3530 nullptr)); 3531 } 3532 3533 } else { 3534 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && 3535 "NodeToMatch was removed partway through selection"); 3536 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, 3537 SDNode *E) { 3538 auto &Chain = ChainNodesMatched; 3539 assert((!E || !is_contained(Chain, N)) && 3540 "Chain node replaced during MorphNode"); 3541 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); 3542 }); 3543 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo); 3544 } 3545 3546 // If the node had chain/glue results, update our notion of the current 3547 // chain and glue. 3548 if (EmitNodeInfo & OPFL_GlueOutput) { 3549 InputGlue = SDValue(Res, VTs.size()-1); 3550 if (EmitNodeInfo & OPFL_Chain) 3551 InputChain = SDValue(Res, VTs.size()-2); 3552 } else if (EmitNodeInfo & OPFL_Chain) 3553 InputChain = SDValue(Res, VTs.size()-1); 3554 3555 // If the OPFL_MemRefs glue is set on this node, slap all of the 3556 // accumulated memrefs onto it. 3557 // 3558 // FIXME: This is vastly incorrect for patterns with multiple outputs 3559 // instructions that access memory and for ComplexPatterns that match 3560 // loads. 3561 if (EmitNodeInfo & OPFL_MemRefs) { 3562 // Only attach load or store memory operands if the generated 3563 // instruction may load or store. 3564 const MCInstrDesc &MCID = TII->get(TargetOpc); 3565 bool mayLoad = MCID.mayLoad(); 3566 bool mayStore = MCID.mayStore(); 3567 3568 unsigned NumMemRefs = 0; 3569 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = 3570 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { 3571 if ((*I)->isLoad()) { 3572 if (mayLoad) 3573 ++NumMemRefs; 3574 } else if ((*I)->isStore()) { 3575 if (mayStore) 3576 ++NumMemRefs; 3577 } else { 3578 ++NumMemRefs; 3579 } 3580 } 3581 3582 MachineSDNode::mmo_iterator MemRefs = 3583 MF->allocateMemRefsArray(NumMemRefs); 3584 3585 MachineSDNode::mmo_iterator MemRefsPos = MemRefs; 3586 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = 3587 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { 3588 if ((*I)->isLoad()) { 3589 if (mayLoad) 3590 *MemRefsPos++ = *I; 3591 } else if ((*I)->isStore()) { 3592 if (mayStore) 3593 *MemRefsPos++ = *I; 3594 } else { 3595 *MemRefsPos++ = *I; 3596 } 3597 } 3598 3599 cast<MachineSDNode>(Res) 3600 ->setMemRefs(MemRefs, MemRefs + NumMemRefs); 3601 } 3602 3603 DEBUG(dbgs() << " " 3604 << (IsMorphNodeTo ? "Morphed" : "Created") 3605 << " node: "; Res->dump(CurDAG); dbgs() << "\n"); 3606 3607 // If this was a MorphNodeTo then we're completely done! 3608 if (IsMorphNodeTo) { 3609 // Update chain uses. 3610 UpdateChains(Res, InputChain, ChainNodesMatched, true); 3611 return; 3612 } 3613 continue; 3614 } 3615 3616 case OPC_CompleteMatch: { 3617 // The match has been completed, and any new nodes (if any) have been 3618 // created. Patch up references to the matched dag to use the newly 3619 // created nodes. 3620 unsigned NumResults = MatcherTable[MatcherIndex++]; 3621 3622 for (unsigned i = 0; i != NumResults; ++i) { 3623 unsigned ResSlot = MatcherTable[MatcherIndex++]; 3624 if (ResSlot & 128) 3625 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); 3626 3627 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); 3628 SDValue Res = RecordedNodes[ResSlot].first; 3629 3630 assert(i < NodeToMatch->getNumValues() && 3631 NodeToMatch->getValueType(i) != MVT::Other && 3632 NodeToMatch->getValueType(i) != MVT::Glue && 3633 "Invalid number of results to complete!"); 3634 assert((NodeToMatch->getValueType(i) == Res.getValueType() || 3635 NodeToMatch->getValueType(i) == MVT::iPTR || 3636 Res.getValueType() == MVT::iPTR || 3637 NodeToMatch->getValueType(i).getSizeInBits() == 3638 Res.getValueSizeInBits()) && 3639 "invalid replacement"); 3640 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res); 3641 } 3642 3643 // Update chain uses. 3644 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); 3645 3646 // If the root node defines glue, we need to update it to the glue result. 3647 // TODO: This never happens in our tests and I think it can be removed / 3648 // replaced with an assert, but if we do it this the way the change is 3649 // NFC. 3650 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == 3651 MVT::Glue && 3652 InputGlue.getNode()) 3653 CurDAG->ReplaceAllUsesOfValueWith( 3654 SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue); 3655 3656 assert(NodeToMatch->use_empty() && 3657 "Didn't replace all uses of the node?"); 3658 CurDAG->RemoveDeadNode(NodeToMatch); 3659 3660 return; 3661 } 3662 } 3663 3664 // If the code reached this point, then the match failed. See if there is 3665 // another child to try in the current 'Scope', otherwise pop it until we 3666 // find a case to check. 3667 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n"); 3668 ++NumDAGIselRetries; 3669 while (1) { 3670 if (MatchScopes.empty()) { 3671 CannotYetSelect(NodeToMatch); 3672 return; 3673 } 3674 3675 // Restore the interpreter state back to the point where the scope was 3676 // formed. 3677 MatchScope &LastScope = MatchScopes.back(); 3678 RecordedNodes.resize(LastScope.NumRecordedNodes); 3679 NodeStack.clear(); 3680 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); 3681 N = NodeStack.back(); 3682 3683 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) 3684 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); 3685 MatcherIndex = LastScope.FailIndex; 3686 3687 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); 3688 3689 InputChain = LastScope.InputChain; 3690 InputGlue = LastScope.InputGlue; 3691 if (!LastScope.HasChainNodesMatched) 3692 ChainNodesMatched.clear(); 3693 3694 // Check to see what the offset is at the new MatcherIndex. If it is zero 3695 // we have reached the end of this scope, otherwise we have another child 3696 // in the current scope to try. 3697 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3698 if (NumToSkip & 128) 3699 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3700 3701 // If we have another child in this scope to match, update FailIndex and 3702 // try it. 3703 if (NumToSkip != 0) { 3704 LastScope.FailIndex = MatcherIndex+NumToSkip; 3705 break; 3706 } 3707 3708 // End of this scope, pop it and try the next child in the containing 3709 // scope. 3710 MatchScopes.pop_back(); 3711 } 3712 } 3713 } 3714 3715 void SelectionDAGISel::CannotYetSelect(SDNode *N) { 3716 std::string msg; 3717 raw_string_ostream Msg(msg); 3718 Msg << "Cannot select: "; 3719 3720 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && 3721 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && 3722 N->getOpcode() != ISD::INTRINSIC_VOID) { 3723 N->printrFull(Msg, CurDAG); 3724 Msg << "\nIn function: " << MF->getName(); 3725 } else { 3726 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; 3727 unsigned iid = 3728 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); 3729 if (iid < Intrinsic::num_intrinsics) 3730 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None); 3731 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) 3732 Msg << "target intrinsic %" << TII->getName(iid); 3733 else 3734 Msg << "unknown intrinsic #" << iid; 3735 } 3736 report_fatal_error(Msg.str()); 3737 } 3738 3739 char SelectionDAGISel::ID = 0; 3740