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