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 bool FunctionBasedInstrumentation = 1468 TLI->getSSPStackGuardCheck(*Fn.getParent()); 1469 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], 1470 FunctionBasedInstrumentation); 1471 } 1472 1473 if (Begin != BI) 1474 ++NumDAGBlocks; 1475 else 1476 ++NumFastIselBlocks; 1477 1478 if (Begin != BI) { 1479 // Run SelectionDAG instruction selection on the remainder of the block 1480 // not handled by FastISel. If FastISel is not run, this is the entire 1481 // block. 1482 bool HadTailCall; 1483 SelectBasicBlock(Begin, BI, HadTailCall); 1484 } 1485 1486 FinishBasicBlock(); 1487 FuncInfo->PHINodesToUpdate.clear(); 1488 } 1489 1490 delete FastIS; 1491 SDB->clearDanglingDebugInfo(); 1492 SDB->SPDescriptor.resetPerFunctionState(); 1493 } 1494 1495 /// Given that the input MI is before a partial terminator sequence TSeq, return 1496 /// true if M + TSeq also a partial terminator sequence. 1497 /// 1498 /// A Terminator sequence is a sequence of MachineInstrs which at this point in 1499 /// lowering copy vregs into physical registers, which are then passed into 1500 /// terminator instructors so we can satisfy ABI constraints. A partial 1501 /// terminator sequence is an improper subset of a terminator sequence (i.e. it 1502 /// may be the whole terminator sequence). 1503 static bool MIIsInTerminatorSequence(const MachineInstr *MI) { 1504 // If we do not have a copy or an implicit def, we return true if and only if 1505 // MI is a debug value. 1506 if (!MI->isCopy() && !MI->isImplicitDef()) 1507 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the 1508 // physical registers if there is debug info associated with the terminator 1509 // of our mbb. We want to include said debug info in our terminator 1510 // sequence, so we return true in that case. 1511 return MI->isDebugValue(); 1512 1513 // We have left the terminator sequence if we are not doing one of the 1514 // following: 1515 // 1516 // 1. Copying a vreg into a physical register. 1517 // 2. Copying a vreg into a vreg. 1518 // 3. Defining a register via an implicit def. 1519 1520 // OPI should always be a register definition... 1521 MachineInstr::const_mop_iterator OPI = MI->operands_begin(); 1522 if (!OPI->isReg() || !OPI->isDef()) 1523 return false; 1524 1525 // Defining any register via an implicit def is always ok. 1526 if (MI->isImplicitDef()) 1527 return true; 1528 1529 // Grab the copy source... 1530 MachineInstr::const_mop_iterator OPI2 = OPI; 1531 ++OPI2; 1532 assert(OPI2 != MI->operands_end() 1533 && "Should have a copy implying we should have 2 arguments."); 1534 1535 // Make sure that the copy dest is not a vreg when the copy source is a 1536 // physical register. 1537 if (!OPI2->isReg() || 1538 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) && 1539 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg()))) 1540 return false; 1541 1542 return true; 1543 } 1544 1545 /// Find the split point at which to splice the end of BB into its success stack 1546 /// protector check machine basic block. 1547 /// 1548 /// On many platforms, due to ABI constraints, terminators, even before register 1549 /// allocation, use physical registers. This creates an issue for us since 1550 /// physical registers at this point can not travel across basic 1551 /// blocks. Luckily, selectiondag always moves physical registers into vregs 1552 /// when they enter functions and moves them through a sequence of copies back 1553 /// into the physical registers right before the terminator creating a 1554 /// ``Terminator Sequence''. This function is searching for the beginning of the 1555 /// terminator sequence so that we can ensure that we splice off not just the 1556 /// terminator, but additionally the copies that move the vregs into the 1557 /// physical registers. 1558 static MachineBasicBlock::iterator 1559 FindSplitPointForStackProtector(MachineBasicBlock *BB) { 1560 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); 1561 // 1562 if (SplitPoint == BB->begin()) 1563 return SplitPoint; 1564 1565 MachineBasicBlock::iterator Start = BB->begin(); 1566 MachineBasicBlock::iterator Previous = SplitPoint; 1567 --Previous; 1568 1569 while (MIIsInTerminatorSequence(Previous)) { 1570 SplitPoint = Previous; 1571 if (Previous == Start) 1572 break; 1573 --Previous; 1574 } 1575 1576 return SplitPoint; 1577 } 1578 1579 void 1580 SelectionDAGISel::FinishBasicBlock() { 1581 DEBUG(dbgs() << "Total amount of phi nodes to update: " 1582 << FuncInfo->PHINodesToUpdate.size() << "\n"; 1583 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) 1584 dbgs() << "Node " << i << " : (" 1585 << FuncInfo->PHINodesToUpdate[i].first 1586 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); 1587 1588 // Next, now that we know what the last MBB the LLVM BB expanded is, update 1589 // PHI nodes in successors. 1590 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { 1591 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); 1592 assert(PHI->isPHI() && 1593 "This is not a machine PHI node that we are updating!"); 1594 if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) 1595 continue; 1596 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); 1597 } 1598 1599 // Handle stack protector. 1600 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { 1601 // The target provides a guard check function. There is no need to 1602 // generate error handling code or to split current basic block. 1603 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1604 1605 // Add load and check to the basicblock. 1606 FuncInfo->MBB = ParentMBB; 1607 FuncInfo->InsertPt = 1608 FindSplitPointForStackProtector(ParentMBB); 1609 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1610 CurDAG->setRoot(SDB->getRoot()); 1611 SDB->clear(); 1612 CodeGenAndEmitDAG(); 1613 1614 // Clear the Per-BB State. 1615 SDB->SPDescriptor.resetPerBBState(); 1616 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { 1617 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1618 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); 1619 1620 // Find the split point to split the parent mbb. At the same time copy all 1621 // physical registers used in the tail of parent mbb into virtual registers 1622 // before the split point and back into physical registers after the split 1623 // point. This prevents us needing to deal with Live-ins and many other 1624 // register allocation issues caused by us splitting the parent mbb. The 1625 // register allocator will clean up said virtual copies later on. 1626 MachineBasicBlock::iterator SplitPoint = 1627 FindSplitPointForStackProtector(ParentMBB); 1628 1629 // Splice the terminator of ParentMBB into SuccessMBB. 1630 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, 1631 SplitPoint, 1632 ParentMBB->end()); 1633 1634 // Add compare/jump on neq/jump to the parent BB. 1635 FuncInfo->MBB = ParentMBB; 1636 FuncInfo->InsertPt = ParentMBB->end(); 1637 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1638 CurDAG->setRoot(SDB->getRoot()); 1639 SDB->clear(); 1640 CodeGenAndEmitDAG(); 1641 1642 // CodeGen Failure MBB if we have not codegened it yet. 1643 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); 1644 if (FailureMBB->empty()) { 1645 FuncInfo->MBB = FailureMBB; 1646 FuncInfo->InsertPt = FailureMBB->end(); 1647 SDB->visitSPDescriptorFailure(SDB->SPDescriptor); 1648 CurDAG->setRoot(SDB->getRoot()); 1649 SDB->clear(); 1650 CodeGenAndEmitDAG(); 1651 } 1652 1653 // Clear the Per-BB State. 1654 SDB->SPDescriptor.resetPerBBState(); 1655 } 1656 1657 // Lower each BitTestBlock. 1658 for (auto &BTB : SDB->BitTestCases) { 1659 // Lower header first, if it wasn't already lowered 1660 if (!BTB.Emitted) { 1661 // Set the current basic block to the mbb we wish to insert the code into 1662 FuncInfo->MBB = BTB.Parent; 1663 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1664 // Emit the code 1665 SDB->visitBitTestHeader(BTB, FuncInfo->MBB); 1666 CurDAG->setRoot(SDB->getRoot()); 1667 SDB->clear(); 1668 CodeGenAndEmitDAG(); 1669 } 1670 1671 BranchProbability UnhandledProb = BTB.Prob; 1672 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { 1673 UnhandledProb -= BTB.Cases[j].ExtraProb; 1674 // Set the current basic block to the mbb we wish to insert the code into 1675 FuncInfo->MBB = BTB.Cases[j].ThisBB; 1676 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1677 // Emit the code 1678 1679 // If all cases cover a contiguous range, it is not necessary to jump to 1680 // the default block after the last bit test fails. This is because the 1681 // range check during bit test header creation has guaranteed that every 1682 // case here doesn't go outside the range. In this case, there is no need 1683 // to perform the last bit test, as it will always be true. Instead, make 1684 // the second-to-last bit-test fall through to the target of the last bit 1685 // test, and delete the last bit test. 1686 1687 MachineBasicBlock *NextMBB; 1688 if (BTB.ContiguousRange && j + 2 == ej) { 1689 // Second-to-last bit-test with contiguous range: fall through to the 1690 // target of the final bit test. 1691 NextMBB = BTB.Cases[j + 1].TargetBB; 1692 } else if (j + 1 == ej) { 1693 // For the last bit test, fall through to Default. 1694 NextMBB = BTB.Default; 1695 } else { 1696 // Otherwise, fall through to the next bit test. 1697 NextMBB = BTB.Cases[j + 1].ThisBB; 1698 } 1699 1700 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], 1701 FuncInfo->MBB); 1702 1703 CurDAG->setRoot(SDB->getRoot()); 1704 SDB->clear(); 1705 CodeGenAndEmitDAG(); 1706 1707 if (BTB.ContiguousRange && j + 2 == ej) { 1708 // Since we're not going to use the final bit test, remove it. 1709 BTB.Cases.pop_back(); 1710 break; 1711 } 1712 } 1713 1714 // Update PHI Nodes 1715 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 1716 pi != pe; ++pi) { 1717 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 1718 MachineBasicBlock *PHIBB = PHI->getParent(); 1719 assert(PHI->isPHI() && 1720 "This is not a machine PHI node that we are updating!"); 1721 // This is "default" BB. We have two jumps to it. From "header" BB and 1722 // from last "case" BB, unless the latter was skipped. 1723 if (PHIBB == BTB.Default) { 1724 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); 1725 if (!BTB.ContiguousRange) { 1726 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 1727 .addMBB(BTB.Cases.back().ThisBB); 1728 } 1729 } 1730 // One of "cases" BB. 1731 for (unsigned j = 0, ej = BTB.Cases.size(); 1732 j != ej; ++j) { 1733 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; 1734 if (cBB->isSuccessor(PHIBB)) 1735 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); 1736 } 1737 } 1738 } 1739 SDB->BitTestCases.clear(); 1740 1741 // If the JumpTable record is filled in, then we need to emit a jump table. 1742 // Updating the PHI nodes is tricky in this case, since we need to determine 1743 // whether the PHI is a successor of the range check MBB or the jump table MBB 1744 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) { 1745 // Lower header first, if it wasn't already lowered 1746 if (!SDB->JTCases[i].first.Emitted) { 1747 // Set the current basic block to the mbb we wish to insert the code into 1748 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB; 1749 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1750 // Emit the code 1751 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first, 1752 FuncInfo->MBB); 1753 CurDAG->setRoot(SDB->getRoot()); 1754 SDB->clear(); 1755 CodeGenAndEmitDAG(); 1756 } 1757 1758 // Set the current basic block to the mbb we wish to insert the code into 1759 FuncInfo->MBB = SDB->JTCases[i].second.MBB; 1760 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1761 // Emit the code 1762 SDB->visitJumpTable(SDB->JTCases[i].second); 1763 CurDAG->setRoot(SDB->getRoot()); 1764 SDB->clear(); 1765 CodeGenAndEmitDAG(); 1766 1767 // Update PHI Nodes 1768 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 1769 pi != pe; ++pi) { 1770 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 1771 MachineBasicBlock *PHIBB = PHI->getParent(); 1772 assert(PHI->isPHI() && 1773 "This is not a machine PHI node that we are updating!"); 1774 // "default" BB. We can go there only from header BB. 1775 if (PHIBB == SDB->JTCases[i].second.Default) 1776 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 1777 .addMBB(SDB->JTCases[i].first.HeaderBB); 1778 // JT BB. Just iterate over successors here 1779 if (FuncInfo->MBB->isSuccessor(PHIBB)) 1780 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); 1781 } 1782 } 1783 SDB->JTCases.clear(); 1784 1785 // If we generated any switch lowering information, build and codegen any 1786 // additional DAGs necessary. 1787 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) { 1788 // Set the current basic block to the mbb we wish to insert the code into 1789 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB; 1790 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1791 1792 // Determine the unique successors. 1793 SmallVector<MachineBasicBlock *, 2> Succs; 1794 Succs.push_back(SDB->SwitchCases[i].TrueBB); 1795 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB) 1796 Succs.push_back(SDB->SwitchCases[i].FalseBB); 1797 1798 // Emit the code. Note that this could result in FuncInfo->MBB being split. 1799 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB); 1800 CurDAG->setRoot(SDB->getRoot()); 1801 SDB->clear(); 1802 CodeGenAndEmitDAG(); 1803 1804 // Remember the last block, now that any splitting is done, for use in 1805 // populating PHI nodes in successors. 1806 MachineBasicBlock *ThisBB = FuncInfo->MBB; 1807 1808 // Handle any PHI nodes in successors of this chunk, as if we were coming 1809 // from the original BB before switch expansion. Note that PHI nodes can 1810 // occur multiple times in PHINodesToUpdate. We have to be very careful to 1811 // handle them the right number of times. 1812 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1813 FuncInfo->MBB = Succs[i]; 1814 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1815 // FuncInfo->MBB may have been removed from the CFG if a branch was 1816 // constant folded. 1817 if (ThisBB->isSuccessor(FuncInfo->MBB)) { 1818 for (MachineBasicBlock::iterator 1819 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); 1820 MBBI != MBBE && MBBI->isPHI(); ++MBBI) { 1821 MachineInstrBuilder PHI(*MF, MBBI); 1822 // This value for this PHI node is recorded in PHINodesToUpdate. 1823 for (unsigned pn = 0; ; ++pn) { 1824 assert(pn != FuncInfo->PHINodesToUpdate.size() && 1825 "Didn't find PHI entry!"); 1826 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { 1827 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); 1828 break; 1829 } 1830 } 1831 } 1832 } 1833 } 1834 } 1835 SDB->SwitchCases.clear(); 1836 } 1837 1838 /// Create the scheduler. If a specific scheduler was specified 1839 /// via the SchedulerRegistry, use it, otherwise select the 1840 /// one preferred by the target. 1841 /// 1842 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { 1843 return ISHeuristic(this, OptLevel); 1844 } 1845 1846 //===----------------------------------------------------------------------===// 1847 // Helper functions used by the generated instruction selector. 1848 //===----------------------------------------------------------------------===// 1849 // Calls to these methods are generated by tblgen. 1850 1851 /// CheckAndMask - The isel is trying to match something like (and X, 255). If 1852 /// the dag combiner simplified the 255, we still want to match. RHS is the 1853 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 1854 /// specified in the .td file (e.g. 255). 1855 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 1856 int64_t DesiredMaskS) const { 1857 const APInt &ActualMask = RHS->getAPIntValue(); 1858 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 1859 1860 // If the actual mask exactly matches, success! 1861 if (ActualMask == DesiredMask) 1862 return true; 1863 1864 // If the actual AND mask is allowing unallowed bits, this doesn't match. 1865 if (ActualMask.intersects(~DesiredMask)) 1866 return false; 1867 1868 // Otherwise, the DAG Combiner may have proven that the value coming in is 1869 // either already zero or is not demanded. Check for known zero input bits. 1870 APInt NeededMask = DesiredMask & ~ActualMask; 1871 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 1872 return true; 1873 1874 // TODO: check to see if missing bits are just not demanded. 1875 1876 // Otherwise, this pattern doesn't match. 1877 return false; 1878 } 1879 1880 /// CheckOrMask - The isel is trying to match something like (or X, 255). If 1881 /// the dag combiner simplified the 255, we still want to match. RHS is the 1882 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 1883 /// specified in the .td file (e.g. 255). 1884 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 1885 int64_t DesiredMaskS) const { 1886 const APInt &ActualMask = RHS->getAPIntValue(); 1887 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 1888 1889 // If the actual mask exactly matches, success! 1890 if (ActualMask == DesiredMask) 1891 return true; 1892 1893 // If the actual AND mask is allowing unallowed bits, this doesn't match. 1894 if (ActualMask.intersects(~DesiredMask)) 1895 return false; 1896 1897 // Otherwise, the DAG Combiner may have proven that the value coming in is 1898 // either already zero or is not demanded. Check for known zero input bits. 1899 APInt NeededMask = DesiredMask & ~ActualMask; 1900 1901 APInt KnownZero, KnownOne; 1902 CurDAG->computeKnownBits(LHS, KnownZero, KnownOne); 1903 1904 // If all the missing bits in the or are already known to be set, match! 1905 if ((NeededMask & KnownOne) == NeededMask) 1906 return true; 1907 1908 // TODO: check to see if missing bits are just not demanded. 1909 1910 // Otherwise, this pattern doesn't match. 1911 return false; 1912 } 1913 1914 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 1915 /// by tblgen. Others should not call it. 1916 void SelectionDAGISel:: 1917 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SDLoc DL) { 1918 std::vector<SDValue> InOps; 1919 std::swap(InOps, Ops); 1920 1921 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 1922 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 1923 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc 1924 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) 1925 1926 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); 1927 if (InOps[e-1].getValueType() == MVT::Glue) 1928 --e; // Don't process a glue operand if it is here. 1929 1930 while (i != e) { 1931 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 1932 if (!InlineAsm::isMemKind(Flags)) { 1933 // Just skip over this operand, copying the operands verbatim. 1934 Ops.insert(Ops.end(), InOps.begin()+i, 1935 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); 1936 i += InlineAsm::getNumOperandRegisters(Flags) + 1; 1937 } else { 1938 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && 1939 "Memory operand with multiple values?"); 1940 1941 unsigned TiedToOperand; 1942 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { 1943 // We need the constraint ID from the operand this is tied to. 1944 unsigned CurOp = InlineAsm::Op_FirstOperand; 1945 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 1946 for (; TiedToOperand; --TiedToOperand) { 1947 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; 1948 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 1949 } 1950 } 1951 1952 // Otherwise, this is a memory operand. Ask the target to select it. 1953 std::vector<SDValue> SelOps; 1954 if (SelectInlineAsmMemoryOperand(InOps[i+1], 1955 InlineAsm::getMemoryConstraintID(Flags), 1956 SelOps)) 1957 report_fatal_error("Could not match memory address. Inline asm" 1958 " failure!"); 1959 1960 // Add this to the output node. 1961 unsigned NewFlags = 1962 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); 1963 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); 1964 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 1965 i += 2; 1966 } 1967 } 1968 1969 // Add the glue input back if present. 1970 if (e != InOps.size()) 1971 Ops.push_back(InOps.back()); 1972 } 1973 1974 /// findGlueUse - Return use of MVT::Glue value produced by the specified 1975 /// SDNode. 1976 /// 1977 static SDNode *findGlueUse(SDNode *N) { 1978 unsigned FlagResNo = N->getNumValues()-1; 1979 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 1980 SDUse &Use = I.getUse(); 1981 if (Use.getResNo() == FlagResNo) 1982 return Use.getUser(); 1983 } 1984 return nullptr; 1985 } 1986 1987 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def". 1988 /// This function recursively traverses up the operand chain, ignoring 1989 /// certain nodes. 1990 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse, 1991 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited, 1992 bool IgnoreChains) { 1993 // The NodeID's are given uniques ID's where a node ID is guaranteed to be 1994 // greater than all of its (recursive) operands. If we scan to a point where 1995 // 'use' is smaller than the node we're scanning for, then we know we will 1996 // never find it. 1997 // 1998 // The Use may be -1 (unassigned) if it is a newly allocated node. This can 1999 // happen because we scan down to newly selected nodes in the case of glue 2000 // uses. 2001 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1)) 2002 return false; 2003 2004 // Don't revisit nodes if we already scanned it and didn't fail, we know we 2005 // won't fail if we scan it again. 2006 if (!Visited.insert(Use).second) 2007 return false; 2008 2009 for (const SDValue &Op : Use->op_values()) { 2010 // Ignore chain uses, they are validated by HandleMergeInputChains. 2011 if (Op.getValueType() == MVT::Other && IgnoreChains) 2012 continue; 2013 2014 SDNode *N = Op.getNode(); 2015 if (N == Def) { 2016 if (Use == ImmedUse || Use == Root) 2017 continue; // We are not looking for immediate use. 2018 assert(N != Root); 2019 return true; 2020 } 2021 2022 // Traverse up the operand chain. 2023 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains)) 2024 return true; 2025 } 2026 return false; 2027 } 2028 2029 /// IsProfitableToFold - Returns true if it's profitable to fold the specific 2030 /// operand node N of U during instruction selection that starts at Root. 2031 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, 2032 SDNode *Root) const { 2033 if (OptLevel == CodeGenOpt::None) return false; 2034 return N.hasOneUse(); 2035 } 2036 2037 /// IsLegalToFold - Returns true if the specific operand node N of 2038 /// U can be folded during instruction selection that starts at Root. 2039 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, 2040 CodeGenOpt::Level OptLevel, 2041 bool IgnoreChains) { 2042 if (OptLevel == CodeGenOpt::None) return false; 2043 2044 // If Root use can somehow reach N through a path that that doesn't contain 2045 // U then folding N would create a cycle. e.g. In the following 2046 // diagram, Root can reach N through X. If N is folded into into Root, then 2047 // X is both a predecessor and a successor of U. 2048 // 2049 // [N*] // 2050 // ^ ^ // 2051 // / \ // 2052 // [U*] [X]? // 2053 // ^ ^ // 2054 // \ / // 2055 // \ / // 2056 // [Root*] // 2057 // 2058 // * indicates nodes to be folded together. 2059 // 2060 // If Root produces glue, then it gets (even more) interesting. Since it 2061 // will be "glued" together with its glue use in the scheduler, we need to 2062 // check if it might reach N. 2063 // 2064 // [N*] // 2065 // ^ ^ // 2066 // / \ // 2067 // [U*] [X]? // 2068 // ^ ^ // 2069 // \ \ // 2070 // \ | // 2071 // [Root*] | // 2072 // ^ | // 2073 // f | // 2074 // | / // 2075 // [Y] / // 2076 // ^ / // 2077 // f / // 2078 // | / // 2079 // [GU] // 2080 // 2081 // If GU (glue use) indirectly reaches N (the load), and Root folds N 2082 // (call it Fold), then X is a predecessor of GU and a successor of 2083 // Fold. But since Fold and GU are glued together, this will create 2084 // a cycle in the scheduling graph. 2085 2086 // If the node has glue, walk down the graph to the "lowest" node in the 2087 // glueged set. 2088 EVT VT = Root->getValueType(Root->getNumValues()-1); 2089 while (VT == MVT::Glue) { 2090 SDNode *GU = findGlueUse(Root); 2091 if (!GU) 2092 break; 2093 Root = GU; 2094 VT = Root->getValueType(Root->getNumValues()-1); 2095 2096 // If our query node has a glue result with a use, we've walked up it. If 2097 // the user (which has already been selected) has a chain or indirectly uses 2098 // the chain, our WalkChainUsers predicate will not consider it. Because of 2099 // this, we cannot ignore chains in this predicate. 2100 IgnoreChains = false; 2101 } 2102 2103 2104 SmallPtrSet<SDNode*, 16> Visited; 2105 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains); 2106 } 2107 2108 void SelectionDAGISel::Select_INLINEASM(SDNode *N) { 2109 SDLoc DL(N); 2110 2111 std::vector<SDValue> Ops(N->op_begin(), N->op_end()); 2112 SelectInlineAsmMemoryOperands(Ops, DL); 2113 2114 const EVT VTs[] = {MVT::Other, MVT::Glue}; 2115 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops); 2116 New->setNodeId(-1); 2117 ReplaceUses(N, New.getNode()); 2118 CurDAG->RemoveDeadNode(N); 2119 } 2120 2121 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { 2122 SDLoc dl(Op); 2123 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2124 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2125 unsigned Reg = 2126 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0), 2127 *CurDAG); 2128 SDValue New = CurDAG->getCopyFromReg( 2129 Op->getOperand(0), dl, Reg, Op->getValueType(0)); 2130 New->setNodeId(-1); 2131 ReplaceUses(Op, New.getNode()); 2132 CurDAG->RemoveDeadNode(Op); 2133 } 2134 2135 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { 2136 SDLoc dl(Op); 2137 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2138 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2139 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), 2140 Op->getOperand(2).getValueType(), 2141 *CurDAG); 2142 SDValue New = CurDAG->getCopyToReg( 2143 Op->getOperand(0), dl, Reg, Op->getOperand(2)); 2144 New->setNodeId(-1); 2145 ReplaceUses(Op, New.getNode()); 2146 CurDAG->RemoveDeadNode(Op); 2147 } 2148 2149 void SelectionDAGISel::Select_UNDEF(SDNode *N) { 2150 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); 2151 } 2152 2153 /// GetVBR - decode a vbr encoding whose top bit is set. 2154 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t 2155 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { 2156 assert(Val >= 128 && "Not a VBR"); 2157 Val &= 127; // Remove first vbr bit. 2158 2159 unsigned Shift = 7; 2160 uint64_t NextBits; 2161 do { 2162 NextBits = MatcherTable[Idx++]; 2163 Val |= (NextBits&127) << Shift; 2164 Shift += 7; 2165 } while (NextBits & 128); 2166 2167 return Val; 2168 } 2169 2170 /// When a match is complete, this method updates uses of interior chain results 2171 /// to use the new results. 2172 void SelectionDAGISel::UpdateChains( 2173 SDNode *NodeToMatch, SDValue InputChain, 2174 const SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { 2175 SmallVector<SDNode*, 4> NowDeadNodes; 2176 2177 // Now that all the normal results are replaced, we replace the chain and 2178 // glue results if present. 2179 if (!ChainNodesMatched.empty()) { 2180 assert(InputChain.getNode() && 2181 "Matched input chains but didn't produce a chain"); 2182 // Loop over all of the nodes we matched that produced a chain result. 2183 // Replace all the chain results with the final chain we ended up with. 2184 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2185 SDNode *ChainNode = ChainNodesMatched[i]; 2186 assert(ChainNode->getOpcode() != ISD::DELETED_NODE && 2187 "Deleted node left in chain"); 2188 2189 // Don't replace the results of the root node if we're doing a 2190 // MorphNodeTo. 2191 if (ChainNode == NodeToMatch && isMorphNodeTo) 2192 continue; 2193 2194 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); 2195 if (ChainVal.getValueType() == MVT::Glue) 2196 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); 2197 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); 2198 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain); 2199 2200 // If the node became dead and we haven't already seen it, delete it. 2201 if (ChainNode != NodeToMatch && ChainNode->use_empty() && 2202 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) 2203 NowDeadNodes.push_back(ChainNode); 2204 } 2205 } 2206 2207 if (!NowDeadNodes.empty()) 2208 CurDAG->RemoveDeadNodes(NowDeadNodes); 2209 2210 DEBUG(dbgs() << "ISEL: Match complete!\n"); 2211 } 2212 2213 enum ChainResult { 2214 CR_Simple, 2215 CR_InducesCycle, 2216 CR_LeadsToInteriorNode 2217 }; 2218 2219 /// WalkChainUsers - Walk down the users of the specified chained node that is 2220 /// part of the pattern we're matching, looking at all of the users we find. 2221 /// This determines whether something is an interior node, whether we have a 2222 /// non-pattern node in between two pattern nodes (which prevent folding because 2223 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched 2224 /// between pattern nodes (in which case the TF becomes part of the pattern). 2225 /// 2226 /// The walk we do here is guaranteed to be small because we quickly get down to 2227 /// already selected nodes "below" us. 2228 static ChainResult 2229 WalkChainUsers(const SDNode *ChainedNode, 2230 SmallVectorImpl<SDNode *> &ChainedNodesInPattern, 2231 DenseMap<const SDNode *, ChainResult> &TokenFactorResult, 2232 SmallVectorImpl<SDNode *> &InteriorChainedNodes) { 2233 ChainResult Result = CR_Simple; 2234 2235 for (SDNode::use_iterator UI = ChainedNode->use_begin(), 2236 E = ChainedNode->use_end(); UI != E; ++UI) { 2237 // Make sure the use is of the chain, not some other value we produce. 2238 if (UI.getUse().getValueType() != MVT::Other) continue; 2239 2240 SDNode *User = *UI; 2241 2242 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph. 2243 continue; 2244 2245 // If we see an already-selected machine node, then we've gone beyond the 2246 // pattern that we're selecting down into the already selected chunk of the 2247 // DAG. 2248 unsigned UserOpcode = User->getOpcode(); 2249 if (User->isMachineOpcode() || 2250 UserOpcode == ISD::CopyToReg || 2251 UserOpcode == ISD::CopyFromReg || 2252 UserOpcode == ISD::INLINEASM || 2253 UserOpcode == ISD::EH_LABEL || 2254 UserOpcode == ISD::LIFETIME_START || 2255 UserOpcode == ISD::LIFETIME_END) { 2256 // If their node ID got reset to -1 then they've already been selected. 2257 // Treat them like a MachineOpcode. 2258 if (User->getNodeId() == -1) 2259 continue; 2260 } 2261 2262 // If we have a TokenFactor, we handle it specially. 2263 if (User->getOpcode() != ISD::TokenFactor) { 2264 // If the node isn't a token factor and isn't part of our pattern, then it 2265 // must be a random chained node in between two nodes we're selecting. 2266 // This happens when we have something like: 2267 // x = load ptr 2268 // call 2269 // y = x+4 2270 // store y -> ptr 2271 // Because we structurally match the load/store as a read/modify/write, 2272 // but the call is chained between them. We cannot fold in this case 2273 // because it would induce a cycle in the graph. 2274 if (!std::count(ChainedNodesInPattern.begin(), 2275 ChainedNodesInPattern.end(), User)) 2276 return CR_InducesCycle; 2277 2278 // Otherwise we found a node that is part of our pattern. For example in: 2279 // x = load ptr 2280 // y = x+4 2281 // store y -> ptr 2282 // This would happen when we're scanning down from the load and see the 2283 // store as a user. Record that there is a use of ChainedNode that is 2284 // part of the pattern and keep scanning uses. 2285 Result = CR_LeadsToInteriorNode; 2286 InteriorChainedNodes.push_back(User); 2287 continue; 2288 } 2289 2290 // If we found a TokenFactor, there are two cases to consider: first if the 2291 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no 2292 // uses of the TF are in our pattern) we just want to ignore it. Second, 2293 // the TokenFactor can be sandwiched in between two chained nodes, like so: 2294 // [Load chain] 2295 // ^ 2296 // | 2297 // [Load] 2298 // ^ ^ 2299 // | \ DAG's like cheese 2300 // / \ do you? 2301 // / | 2302 // [TokenFactor] [Op] 2303 // ^ ^ 2304 // | | 2305 // \ / 2306 // \ / 2307 // [Store] 2308 // 2309 // In this case, the TokenFactor becomes part of our match and we rewrite it 2310 // as a new TokenFactor. 2311 // 2312 // To distinguish these two cases, do a recursive walk down the uses. 2313 auto MemoizeResult = TokenFactorResult.find(User); 2314 bool Visited = MemoizeResult != TokenFactorResult.end(); 2315 // Recursively walk chain users only if the result is not memoized. 2316 if (!Visited) { 2317 auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult, 2318 InteriorChainedNodes); 2319 MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first; 2320 } 2321 switch (MemoizeResult->second) { 2322 case CR_Simple: 2323 // If the uses of the TokenFactor are just already-selected nodes, ignore 2324 // it, it is "below" our pattern. 2325 continue; 2326 case CR_InducesCycle: 2327 // If the uses of the TokenFactor lead to nodes that are not part of our 2328 // pattern that are not selected, folding would turn this into a cycle, 2329 // bail out now. 2330 return CR_InducesCycle; 2331 case CR_LeadsToInteriorNode: 2332 break; // Otherwise, keep processing. 2333 } 2334 2335 // Okay, we know we're in the interesting interior case. The TokenFactor 2336 // is now going to be considered part of the pattern so that we rewrite its 2337 // uses (it may have uses that are not part of the pattern) with the 2338 // ultimate chain result of the generated code. We will also add its chain 2339 // inputs as inputs to the ultimate TokenFactor we create. 2340 Result = CR_LeadsToInteriorNode; 2341 if (!Visited) { 2342 ChainedNodesInPattern.push_back(User); 2343 InteriorChainedNodes.push_back(User); 2344 } 2345 } 2346 2347 return Result; 2348 } 2349 2350 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains 2351 /// operation for when the pattern matched at least one node with a chains. The 2352 /// input vector contains a list of all of the chained nodes that we match. We 2353 /// must determine if this is a valid thing to cover (i.e. matching it won't 2354 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will 2355 /// be used as the input node chain for the generated nodes. 2356 static SDValue 2357 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, 2358 SelectionDAG *CurDAG) { 2359 // Used for memoization. Without it WalkChainUsers could take exponential 2360 // time to run. 2361 DenseMap<const SDNode *, ChainResult> TokenFactorResult; 2362 // Walk all of the chained nodes we've matched, recursively scanning down the 2363 // users of the chain result. This adds any TokenFactor nodes that are caught 2364 // in between chained nodes to the chained and interior nodes list. 2365 SmallVector<SDNode*, 3> InteriorChainedNodes; 2366 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2367 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched, 2368 TokenFactorResult, 2369 InteriorChainedNodes) == CR_InducesCycle) 2370 return SDValue(); // Would induce a cycle. 2371 } 2372 2373 // Okay, we have walked all the matched nodes and collected TokenFactor nodes 2374 // that we are interested in. Form our input TokenFactor node. 2375 SmallVector<SDValue, 3> InputChains; 2376 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2377 // Add the input chain of this node to the InputChains list (which will be 2378 // the operands of the generated TokenFactor) if it's not an interior node. 2379 SDNode *N = ChainNodesMatched[i]; 2380 if (N->getOpcode() != ISD::TokenFactor) { 2381 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N)) 2382 continue; 2383 2384 // Otherwise, add the input chain. 2385 SDValue InChain = ChainNodesMatched[i]->getOperand(0); 2386 assert(InChain.getValueType() == MVT::Other && "Not a chain"); 2387 InputChains.push_back(InChain); 2388 continue; 2389 } 2390 2391 // If we have a token factor, we want to add all inputs of the token factor 2392 // that are not part of the pattern we're matching. 2393 for (const SDValue &Op : N->op_values()) { 2394 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(), 2395 Op.getNode())) 2396 InputChains.push_back(Op); 2397 } 2398 } 2399 2400 if (InputChains.size() == 1) 2401 return InputChains[0]; 2402 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), 2403 MVT::Other, InputChains); 2404 } 2405 2406 /// MorphNode - Handle morphing a node in place for the selector. 2407 SDNode *SelectionDAGISel:: 2408 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, 2409 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { 2410 // It is possible we're using MorphNodeTo to replace a node with no 2411 // normal results with one that has a normal result (or we could be 2412 // adding a chain) and the input could have glue and chains as well. 2413 // In this case we need to shift the operands down. 2414 // FIXME: This is a horrible hack and broken in obscure cases, no worse 2415 // than the old isel though. 2416 int OldGlueResultNo = -1, OldChainResultNo = -1; 2417 2418 unsigned NTMNumResults = Node->getNumValues(); 2419 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { 2420 OldGlueResultNo = NTMNumResults-1; 2421 if (NTMNumResults != 1 && 2422 Node->getValueType(NTMNumResults-2) == MVT::Other) 2423 OldChainResultNo = NTMNumResults-2; 2424 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) 2425 OldChainResultNo = NTMNumResults-1; 2426 2427 // Call the underlying SelectionDAG routine to do the transmogrification. Note 2428 // that this deletes operands of the old node that become dead. 2429 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); 2430 2431 // MorphNodeTo can operate in two ways: if an existing node with the 2432 // specified operands exists, it can just return it. Otherwise, it 2433 // updates the node in place to have the requested operands. 2434 if (Res == Node) { 2435 // If we updated the node in place, reset the node ID. To the isel, 2436 // this should be just like a newly allocated machine node. 2437 Res->setNodeId(-1); 2438 } 2439 2440 unsigned ResNumResults = Res->getNumValues(); 2441 // Move the glue if needed. 2442 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && 2443 (unsigned)OldGlueResultNo != ResNumResults-1) 2444 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo), 2445 SDValue(Res, ResNumResults-1)); 2446 2447 if ((EmitNodeInfo & OPFL_GlueOutput) != 0) 2448 --ResNumResults; 2449 2450 // Move the chain reference if needed. 2451 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && 2452 (unsigned)OldChainResultNo != ResNumResults-1) 2453 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo), 2454 SDValue(Res, ResNumResults-1)); 2455 2456 // Otherwise, no replacement happened because the node already exists. Replace 2457 // Uses of the old node with the new one. 2458 if (Res != Node) { 2459 CurDAG->ReplaceAllUsesWith(Node, Res); 2460 CurDAG->RemoveDeadNode(Node); 2461 } 2462 2463 return Res; 2464 } 2465 2466 /// CheckSame - Implements OP_CheckSame. 2467 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2468 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2469 SDValue N, 2470 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { 2471 // Accept if it is exactly the same as a previously recorded node. 2472 unsigned RecNo = MatcherTable[MatcherIndex++]; 2473 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); 2474 return N == RecordedNodes[RecNo].first; 2475 } 2476 2477 /// CheckChildSame - Implements OP_CheckChildXSame. 2478 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2479 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2480 SDValue N, 2481 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes, 2482 unsigned ChildNo) { 2483 if (ChildNo >= N.getNumOperands()) 2484 return false; // Match fails if out of range child #. 2485 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), 2486 RecordedNodes); 2487 } 2488 2489 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. 2490 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2491 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2492 const SelectionDAGISel &SDISel) { 2493 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); 2494 } 2495 2496 /// CheckNodePredicate - Implements OP_CheckNodePredicate. 2497 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2498 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2499 const SelectionDAGISel &SDISel, SDNode *N) { 2500 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); 2501 } 2502 2503 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2504 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2505 SDNode *N) { 2506 uint16_t Opc = MatcherTable[MatcherIndex++]; 2507 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 2508 return N->getOpcode() == Opc; 2509 } 2510 2511 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2512 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, 2513 const TargetLowering *TLI, const DataLayout &DL) { 2514 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2515 if (N.getValueType() == VT) return true; 2516 2517 // Handle the case when VT is iPTR. 2518 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); 2519 } 2520 2521 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2522 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2523 SDValue N, const TargetLowering *TLI, const DataLayout &DL, 2524 unsigned ChildNo) { 2525 if (ChildNo >= N.getNumOperands()) 2526 return false; // Match fails if out of range child #. 2527 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, 2528 DL); 2529 } 2530 2531 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2532 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2533 SDValue N) { 2534 return cast<CondCodeSDNode>(N)->get() == 2535 (ISD::CondCode)MatcherTable[MatcherIndex++]; 2536 } 2537 2538 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2539 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2540 SDValue N, const TargetLowering *TLI, const DataLayout &DL) { 2541 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2542 if (cast<VTSDNode>(N)->getVT() == VT) 2543 return true; 2544 2545 // Handle the case when VT is iPTR. 2546 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); 2547 } 2548 2549 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2550 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2551 SDValue N) { 2552 int64_t Val = MatcherTable[MatcherIndex++]; 2553 if (Val & 128) 2554 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2555 2556 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 2557 return C && C->getSExtValue() == Val; 2558 } 2559 2560 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2561 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2562 SDValue N, unsigned ChildNo) { 2563 if (ChildNo >= N.getNumOperands()) 2564 return false; // Match fails if out of range child #. 2565 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); 2566 } 2567 2568 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2569 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2570 SDValue N, const SelectionDAGISel &SDISel) { 2571 int64_t Val = MatcherTable[MatcherIndex++]; 2572 if (Val & 128) 2573 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2574 2575 if (N->getOpcode() != ISD::AND) return false; 2576 2577 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2578 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); 2579 } 2580 2581 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2582 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2583 SDValue N, const SelectionDAGISel &SDISel) { 2584 int64_t Val = MatcherTable[MatcherIndex++]; 2585 if (Val & 128) 2586 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2587 2588 if (N->getOpcode() != ISD::OR) return false; 2589 2590 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2591 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); 2592 } 2593 2594 /// IsPredicateKnownToFail - If we know how and can do so without pushing a 2595 /// scope, evaluate the current node. If the current predicate is known to 2596 /// fail, set Result=true and return anything. If the current predicate is 2597 /// known to pass, set Result=false and return the MatcherIndex to continue 2598 /// with. If the current predicate is unknown, set Result=false and return the 2599 /// MatcherIndex to continue with. 2600 static unsigned IsPredicateKnownToFail(const unsigned char *Table, 2601 unsigned Index, SDValue N, 2602 bool &Result, 2603 const SelectionDAGISel &SDISel, 2604 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { 2605 switch (Table[Index++]) { 2606 default: 2607 Result = false; 2608 return Index-1; // Could not evaluate this predicate. 2609 case SelectionDAGISel::OPC_CheckSame: 2610 Result = !::CheckSame(Table, Index, N, RecordedNodes); 2611 return Index; 2612 case SelectionDAGISel::OPC_CheckChild0Same: 2613 case SelectionDAGISel::OPC_CheckChild1Same: 2614 case SelectionDAGISel::OPC_CheckChild2Same: 2615 case SelectionDAGISel::OPC_CheckChild3Same: 2616 Result = !::CheckChildSame(Table, Index, N, RecordedNodes, 2617 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); 2618 return Index; 2619 case SelectionDAGISel::OPC_CheckPatternPredicate: 2620 Result = !::CheckPatternPredicate(Table, Index, SDISel); 2621 return Index; 2622 case SelectionDAGISel::OPC_CheckPredicate: 2623 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); 2624 return Index; 2625 case SelectionDAGISel::OPC_CheckOpcode: 2626 Result = !::CheckOpcode(Table, Index, N.getNode()); 2627 return Index; 2628 case SelectionDAGISel::OPC_CheckType: 2629 Result = !::CheckType(Table, Index, N, SDISel.TLI, 2630 SDISel.CurDAG->getDataLayout()); 2631 return Index; 2632 case SelectionDAGISel::OPC_CheckChild0Type: 2633 case SelectionDAGISel::OPC_CheckChild1Type: 2634 case SelectionDAGISel::OPC_CheckChild2Type: 2635 case SelectionDAGISel::OPC_CheckChild3Type: 2636 case SelectionDAGISel::OPC_CheckChild4Type: 2637 case SelectionDAGISel::OPC_CheckChild5Type: 2638 case SelectionDAGISel::OPC_CheckChild6Type: 2639 case SelectionDAGISel::OPC_CheckChild7Type: 2640 Result = !::CheckChildType( 2641 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), 2642 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); 2643 return Index; 2644 case SelectionDAGISel::OPC_CheckCondCode: 2645 Result = !::CheckCondCode(Table, Index, N); 2646 return Index; 2647 case SelectionDAGISel::OPC_CheckValueType: 2648 Result = !::CheckValueType(Table, Index, N, SDISel.TLI, 2649 SDISel.CurDAG->getDataLayout()); 2650 return Index; 2651 case SelectionDAGISel::OPC_CheckInteger: 2652 Result = !::CheckInteger(Table, Index, N); 2653 return Index; 2654 case SelectionDAGISel::OPC_CheckChild0Integer: 2655 case SelectionDAGISel::OPC_CheckChild1Integer: 2656 case SelectionDAGISel::OPC_CheckChild2Integer: 2657 case SelectionDAGISel::OPC_CheckChild3Integer: 2658 case SelectionDAGISel::OPC_CheckChild4Integer: 2659 Result = !::CheckChildInteger(Table, Index, N, 2660 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); 2661 return Index; 2662 case SelectionDAGISel::OPC_CheckAndImm: 2663 Result = !::CheckAndImm(Table, Index, N, SDISel); 2664 return Index; 2665 case SelectionDAGISel::OPC_CheckOrImm: 2666 Result = !::CheckOrImm(Table, Index, N, SDISel); 2667 return Index; 2668 } 2669 } 2670 2671 namespace { 2672 struct MatchScope { 2673 /// FailIndex - If this match fails, this is the index to continue with. 2674 unsigned FailIndex; 2675 2676 /// NodeStack - The node stack when the scope was formed. 2677 SmallVector<SDValue, 4> NodeStack; 2678 2679 /// NumRecordedNodes - The number of recorded nodes when the scope was formed. 2680 unsigned NumRecordedNodes; 2681 2682 /// NumMatchedMemRefs - The number of matched memref entries. 2683 unsigned NumMatchedMemRefs; 2684 2685 /// InputChain/InputGlue - The current chain/glue 2686 SDValue InputChain, InputGlue; 2687 2688 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. 2689 bool HasChainNodesMatched; 2690 }; 2691 2692 /// \\brief A DAG update listener to keep the matching state 2693 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to 2694 /// change the DAG while matching. X86 addressing mode matcher is an example 2695 /// for this. 2696 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener 2697 { 2698 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes; 2699 SmallVectorImpl<MatchScope> &MatchScopes; 2700 public: 2701 MatchStateUpdater(SelectionDAG &DAG, 2702 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN, 2703 SmallVectorImpl<MatchScope> &MS) : 2704 SelectionDAG::DAGUpdateListener(DAG), 2705 RecordedNodes(RN), MatchScopes(MS) { } 2706 2707 void NodeDeleted(SDNode *N, SDNode *E) override { 2708 // Some early-returns here to avoid the search if we deleted the node or 2709 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we 2710 // do, so it's unnecessary to update matching state at that point). 2711 // Neither of these can occur currently because we only install this 2712 // update listener during matching a complex patterns. 2713 if (!E || E->isMachineOpcode()) 2714 return; 2715 // Performing linear search here does not matter because we almost never 2716 // run this code. You'd have to have a CSE during complex pattern 2717 // matching. 2718 for (auto &I : RecordedNodes) 2719 if (I.first.getNode() == N) 2720 I.first.setNode(E); 2721 2722 for (auto &I : MatchScopes) 2723 for (auto &J : I.NodeStack) 2724 if (J.getNode() == N) 2725 J.setNode(E); 2726 } 2727 }; 2728 } // end anonymous namespace 2729 2730 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, 2731 const unsigned char *MatcherTable, 2732 unsigned TableSize) { 2733 // FIXME: Should these even be selected? Handle these cases in the caller? 2734 switch (NodeToMatch->getOpcode()) { 2735 default: 2736 break; 2737 case ISD::EntryToken: // These nodes remain the same. 2738 case ISD::BasicBlock: 2739 case ISD::Register: 2740 case ISD::RegisterMask: 2741 case ISD::HANDLENODE: 2742 case ISD::MDNODE_SDNODE: 2743 case ISD::TargetConstant: 2744 case ISD::TargetConstantFP: 2745 case ISD::TargetConstantPool: 2746 case ISD::TargetFrameIndex: 2747 case ISD::TargetExternalSymbol: 2748 case ISD::MCSymbol: 2749 case ISD::TargetBlockAddress: 2750 case ISD::TargetJumpTable: 2751 case ISD::TargetGlobalTLSAddress: 2752 case ISD::TargetGlobalAddress: 2753 case ISD::TokenFactor: 2754 case ISD::CopyFromReg: 2755 case ISD::CopyToReg: 2756 case ISD::EH_LABEL: 2757 case ISD::LIFETIME_START: 2758 case ISD::LIFETIME_END: 2759 NodeToMatch->setNodeId(-1); // Mark selected. 2760 return; 2761 case ISD::AssertSext: 2762 case ISD::AssertZext: 2763 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0), 2764 NodeToMatch->getOperand(0)); 2765 CurDAG->RemoveDeadNode(NodeToMatch); 2766 return; 2767 case ISD::INLINEASM: 2768 Select_INLINEASM(NodeToMatch); 2769 return; 2770 case ISD::READ_REGISTER: 2771 Select_READ_REGISTER(NodeToMatch); 2772 return; 2773 case ISD::WRITE_REGISTER: 2774 Select_WRITE_REGISTER(NodeToMatch); 2775 return; 2776 case ISD::UNDEF: 2777 Select_UNDEF(NodeToMatch); 2778 return; 2779 } 2780 2781 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); 2782 2783 // Set up the node stack with NodeToMatch as the only node on the stack. 2784 SmallVector<SDValue, 8> NodeStack; 2785 SDValue N = SDValue(NodeToMatch, 0); 2786 NodeStack.push_back(N); 2787 2788 // MatchScopes - Scopes used when matching, if a match failure happens, this 2789 // indicates where to continue checking. 2790 SmallVector<MatchScope, 8> MatchScopes; 2791 2792 // RecordedNodes - This is the set of nodes that have been recorded by the 2793 // state machine. The second value is the parent of the node, or null if the 2794 // root is recorded. 2795 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; 2796 2797 // MatchedMemRefs - This is the set of MemRef's we've seen in the input 2798 // pattern. 2799 SmallVector<MachineMemOperand*, 2> MatchedMemRefs; 2800 2801 // These are the current input chain and glue for use when generating nodes. 2802 // Various Emit operations change these. For example, emitting a copytoreg 2803 // uses and updates these. 2804 SDValue InputChain, InputGlue; 2805 2806 // ChainNodesMatched - If a pattern matches nodes that have input/output 2807 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates 2808 // which ones they are. The result is captured into this list so that we can 2809 // update the chain results when the pattern is complete. 2810 SmallVector<SDNode*, 3> ChainNodesMatched; 2811 2812 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: "; 2813 NodeToMatch->dump(CurDAG); 2814 dbgs() << '\n'); 2815 2816 // Determine where to start the interpreter. Normally we start at opcode #0, 2817 // but if the state machine starts with an OPC_SwitchOpcode, then we 2818 // accelerate the first lookup (which is guaranteed to be hot) with the 2819 // OpcodeOffset table. 2820 unsigned MatcherIndex = 0; 2821 2822 if (!OpcodeOffset.empty()) { 2823 // Already computed the OpcodeOffset table, just index into it. 2824 if (N.getOpcode() < OpcodeOffset.size()) 2825 MatcherIndex = OpcodeOffset[N.getOpcode()]; 2826 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); 2827 2828 } else if (MatcherTable[0] == OPC_SwitchOpcode) { 2829 // Otherwise, the table isn't computed, but the state machine does start 2830 // with an OPC_SwitchOpcode instruction. Populate the table now, since this 2831 // is the first time we're selecting an instruction. 2832 unsigned Idx = 1; 2833 while (1) { 2834 // Get the size of this case. 2835 unsigned CaseSize = MatcherTable[Idx++]; 2836 if (CaseSize & 128) 2837 CaseSize = GetVBR(CaseSize, MatcherTable, Idx); 2838 if (CaseSize == 0) break; 2839 2840 // Get the opcode, add the index to the table. 2841 uint16_t Opc = MatcherTable[Idx++]; 2842 Opc |= (unsigned short)MatcherTable[Idx++] << 8; 2843 if (Opc >= OpcodeOffset.size()) 2844 OpcodeOffset.resize((Opc+1)*2); 2845 OpcodeOffset[Opc] = Idx; 2846 Idx += CaseSize; 2847 } 2848 2849 // Okay, do the lookup for the first opcode. 2850 if (N.getOpcode() < OpcodeOffset.size()) 2851 MatcherIndex = OpcodeOffset[N.getOpcode()]; 2852 } 2853 2854 while (1) { 2855 assert(MatcherIndex < TableSize && "Invalid index"); 2856 #ifndef NDEBUG 2857 unsigned CurrentOpcodeIndex = MatcherIndex; 2858 #endif 2859 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; 2860 switch (Opcode) { 2861 case OPC_Scope: { 2862 // Okay, the semantics of this operation are that we should push a scope 2863 // then evaluate the first child. However, pushing a scope only to have 2864 // the first check fail (which then pops it) is inefficient. If we can 2865 // determine immediately that the first check (or first several) will 2866 // immediately fail, don't even bother pushing a scope for them. 2867 unsigned FailIndex; 2868 2869 while (1) { 2870 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 2871 if (NumToSkip & 128) 2872 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 2873 // Found the end of the scope with no match. 2874 if (NumToSkip == 0) { 2875 FailIndex = 0; 2876 break; 2877 } 2878 2879 FailIndex = MatcherIndex+NumToSkip; 2880 2881 unsigned MatcherIndexOfPredicate = MatcherIndex; 2882 (void)MatcherIndexOfPredicate; // silence warning. 2883 2884 // If we can't evaluate this predicate without pushing a scope (e.g. if 2885 // it is a 'MoveParent') or if the predicate succeeds on this node, we 2886 // push the scope and evaluate the full predicate chain. 2887 bool Result; 2888 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, 2889 Result, *this, RecordedNodes); 2890 if (!Result) 2891 break; 2892 2893 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at " 2894 << "index " << MatcherIndexOfPredicate 2895 << ", continuing at " << FailIndex << "\n"); 2896 ++NumDAGIselRetries; 2897 2898 // Otherwise, we know that this case of the Scope is guaranteed to fail, 2899 // move to the next case. 2900 MatcherIndex = FailIndex; 2901 } 2902 2903 // If the whole scope failed to match, bail. 2904 if (FailIndex == 0) break; 2905 2906 // Push a MatchScope which indicates where to go if the first child fails 2907 // to match. 2908 MatchScope NewEntry; 2909 NewEntry.FailIndex = FailIndex; 2910 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); 2911 NewEntry.NumRecordedNodes = RecordedNodes.size(); 2912 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); 2913 NewEntry.InputChain = InputChain; 2914 NewEntry.InputGlue = InputGlue; 2915 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); 2916 MatchScopes.push_back(NewEntry); 2917 continue; 2918 } 2919 case OPC_RecordNode: { 2920 // Remember this node, it may end up being an operand in the pattern. 2921 SDNode *Parent = nullptr; 2922 if (NodeStack.size() > 1) 2923 Parent = NodeStack[NodeStack.size()-2].getNode(); 2924 RecordedNodes.push_back(std::make_pair(N, Parent)); 2925 continue; 2926 } 2927 2928 case OPC_RecordChild0: case OPC_RecordChild1: 2929 case OPC_RecordChild2: case OPC_RecordChild3: 2930 case OPC_RecordChild4: case OPC_RecordChild5: 2931 case OPC_RecordChild6: case OPC_RecordChild7: { 2932 unsigned ChildNo = Opcode-OPC_RecordChild0; 2933 if (ChildNo >= N.getNumOperands()) 2934 break; // Match fails if out of range child #. 2935 2936 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), 2937 N.getNode())); 2938 continue; 2939 } 2940 case OPC_RecordMemRef: 2941 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand()); 2942 continue; 2943 2944 case OPC_CaptureGlueInput: 2945 // If the current node has an input glue, capture it in InputGlue. 2946 if (N->getNumOperands() != 0 && 2947 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) 2948 InputGlue = N->getOperand(N->getNumOperands()-1); 2949 continue; 2950 2951 case OPC_MoveChild: { 2952 unsigned ChildNo = MatcherTable[MatcherIndex++]; 2953 if (ChildNo >= N.getNumOperands()) 2954 break; // Match fails if out of range child #. 2955 N = N.getOperand(ChildNo); 2956 NodeStack.push_back(N); 2957 continue; 2958 } 2959 2960 case OPC_MoveChild0: case OPC_MoveChild1: 2961 case OPC_MoveChild2: case OPC_MoveChild3: 2962 case OPC_MoveChild4: case OPC_MoveChild5: 2963 case OPC_MoveChild6: case OPC_MoveChild7: { 2964 unsigned ChildNo = Opcode-OPC_MoveChild0; 2965 if (ChildNo >= N.getNumOperands()) 2966 break; // Match fails if out of range child #. 2967 N = N.getOperand(ChildNo); 2968 NodeStack.push_back(N); 2969 continue; 2970 } 2971 2972 case OPC_MoveParent: 2973 // Pop the current node off the NodeStack. 2974 NodeStack.pop_back(); 2975 assert(!NodeStack.empty() && "Node stack imbalance!"); 2976 N = NodeStack.back(); 2977 continue; 2978 2979 case OPC_CheckSame: 2980 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; 2981 continue; 2982 2983 case OPC_CheckChild0Same: case OPC_CheckChild1Same: 2984 case OPC_CheckChild2Same: case OPC_CheckChild3Same: 2985 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, 2986 Opcode-OPC_CheckChild0Same)) 2987 break; 2988 continue; 2989 2990 case OPC_CheckPatternPredicate: 2991 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; 2992 continue; 2993 case OPC_CheckPredicate: 2994 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, 2995 N.getNode())) 2996 break; 2997 continue; 2998 case OPC_CheckComplexPat: { 2999 unsigned CPNum = MatcherTable[MatcherIndex++]; 3000 unsigned RecNo = MatcherTable[MatcherIndex++]; 3001 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); 3002 3003 // If target can modify DAG during matching, keep the matching state 3004 // consistent. 3005 std::unique_ptr<MatchStateUpdater> MSU; 3006 if (ComplexPatternFuncMutatesDAG()) 3007 MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes, 3008 MatchScopes)); 3009 3010 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, 3011 RecordedNodes[RecNo].first, CPNum, 3012 RecordedNodes)) 3013 break; 3014 continue; 3015 } 3016 case OPC_CheckOpcode: 3017 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; 3018 continue; 3019 3020 case OPC_CheckType: 3021 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, 3022 CurDAG->getDataLayout())) 3023 break; 3024 continue; 3025 3026 case OPC_SwitchOpcode: { 3027 unsigned CurNodeOpcode = N.getOpcode(); 3028 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3029 unsigned CaseSize; 3030 while (1) { 3031 // Get the size of this case. 3032 CaseSize = MatcherTable[MatcherIndex++]; 3033 if (CaseSize & 128) 3034 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3035 if (CaseSize == 0) break; 3036 3037 uint16_t Opc = MatcherTable[MatcherIndex++]; 3038 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3039 3040 // If the opcode matches, then we will execute this case. 3041 if (CurNodeOpcode == Opc) 3042 break; 3043 3044 // Otherwise, skip over this case. 3045 MatcherIndex += CaseSize; 3046 } 3047 3048 // If no cases matched, bail out. 3049 if (CaseSize == 0) break; 3050 3051 // Otherwise, execute the case we found. 3052 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart 3053 << " to " << MatcherIndex << "\n"); 3054 continue; 3055 } 3056 3057 case OPC_SwitchType: { 3058 MVT CurNodeVT = N.getSimpleValueType(); 3059 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3060 unsigned CaseSize; 3061 while (1) { 3062 // Get the size of this case. 3063 CaseSize = MatcherTable[MatcherIndex++]; 3064 if (CaseSize & 128) 3065 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3066 if (CaseSize == 0) break; 3067 3068 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3069 if (CaseVT == MVT::iPTR) 3070 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); 3071 3072 // If the VT matches, then we will execute this case. 3073 if (CurNodeVT == CaseVT) 3074 break; 3075 3076 // Otherwise, skip over this case. 3077 MatcherIndex += CaseSize; 3078 } 3079 3080 // If no cases matched, bail out. 3081 if (CaseSize == 0) break; 3082 3083 // Otherwise, execute the case we found. 3084 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() 3085 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n'); 3086 continue; 3087 } 3088 case OPC_CheckChild0Type: case OPC_CheckChild1Type: 3089 case OPC_CheckChild2Type: case OPC_CheckChild3Type: 3090 case OPC_CheckChild4Type: case OPC_CheckChild5Type: 3091 case OPC_CheckChild6Type: case OPC_CheckChild7Type: 3092 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, 3093 CurDAG->getDataLayout(), 3094 Opcode - OPC_CheckChild0Type)) 3095 break; 3096 continue; 3097 case OPC_CheckCondCode: 3098 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; 3099 continue; 3100 case OPC_CheckValueType: 3101 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, 3102 CurDAG->getDataLayout())) 3103 break; 3104 continue; 3105 case OPC_CheckInteger: 3106 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; 3107 continue; 3108 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: 3109 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: 3110 case OPC_CheckChild4Integer: 3111 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, 3112 Opcode-OPC_CheckChild0Integer)) break; 3113 continue; 3114 case OPC_CheckAndImm: 3115 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; 3116 continue; 3117 case OPC_CheckOrImm: 3118 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; 3119 continue; 3120 3121 case OPC_CheckFoldableChainNode: { 3122 assert(NodeStack.size() != 1 && "No parent node"); 3123 // Verify that all intermediate nodes between the root and this one have 3124 // a single use. 3125 bool HasMultipleUses = false; 3126 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) 3127 if (!NodeStack[i].hasOneUse()) { 3128 HasMultipleUses = true; 3129 break; 3130 } 3131 if (HasMultipleUses) break; 3132 3133 // Check to see that the target thinks this is profitable to fold and that 3134 // we can fold it without inducing cycles in the graph. 3135 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3136 NodeToMatch) || 3137 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3138 NodeToMatch, OptLevel, 3139 true/*We validate our own chains*/)) 3140 break; 3141 3142 continue; 3143 } 3144 case OPC_EmitInteger: { 3145 MVT::SimpleValueType VT = 3146 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3147 int64_t Val = MatcherTable[MatcherIndex++]; 3148 if (Val & 128) 3149 Val = GetVBR(Val, MatcherTable, MatcherIndex); 3150 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3151 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), 3152 VT), nullptr)); 3153 continue; 3154 } 3155 case OPC_EmitRegister: { 3156 MVT::SimpleValueType VT = 3157 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3158 unsigned RegNo = MatcherTable[MatcherIndex++]; 3159 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3160 CurDAG->getRegister(RegNo, VT), nullptr)); 3161 continue; 3162 } 3163 case OPC_EmitRegister2: { 3164 // For targets w/ more than 256 register names, the register enum 3165 // values are stored in two bytes in the matcher table (just like 3166 // opcodes). 3167 MVT::SimpleValueType VT = 3168 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3169 unsigned RegNo = MatcherTable[MatcherIndex++]; 3170 RegNo |= MatcherTable[MatcherIndex++] << 8; 3171 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3172 CurDAG->getRegister(RegNo, VT), nullptr)); 3173 continue; 3174 } 3175 3176 case OPC_EmitConvertToTarget: { 3177 // Convert from IMM/FPIMM to target version. 3178 unsigned RecNo = MatcherTable[MatcherIndex++]; 3179 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); 3180 SDValue Imm = RecordedNodes[RecNo].first; 3181 3182 if (Imm->getOpcode() == ISD::Constant) { 3183 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); 3184 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), 3185 Imm.getValueType()); 3186 } else if (Imm->getOpcode() == ISD::ConstantFP) { 3187 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); 3188 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), 3189 Imm.getValueType()); 3190 } 3191 3192 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); 3193 continue; 3194 } 3195 3196 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 3197 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 3198 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 3199 // These are space-optimized forms of OPC_EmitMergeInputChains. 3200 assert(!InputChain.getNode() && 3201 "EmitMergeInputChains should be the first chain producing node"); 3202 assert(ChainNodesMatched.empty() && 3203 "Should only have one EmitMergeInputChains per match"); 3204 3205 // Read all of the chained nodes. 3206 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; 3207 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3208 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3209 3210 // FIXME: What if other value results of the node have uses not matched 3211 // by this pattern? 3212 if (ChainNodesMatched.back() != NodeToMatch && 3213 !RecordedNodes[RecNo].first.hasOneUse()) { 3214 ChainNodesMatched.clear(); 3215 break; 3216 } 3217 3218 // Merge the input chains if they are not intra-pattern references. 3219 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3220 3221 if (!InputChain.getNode()) 3222 break; // Failed to merge. 3223 continue; 3224 } 3225 3226 case OPC_EmitMergeInputChains: { 3227 assert(!InputChain.getNode() && 3228 "EmitMergeInputChains should be the first chain producing node"); 3229 // This node gets a list of nodes we matched in the input that have 3230 // chains. We want to token factor all of the input chains to these nodes 3231 // together. However, if any of the input chains is actually one of the 3232 // nodes matched in this pattern, then we have an intra-match reference. 3233 // Ignore these because the newly token factored chain should not refer to 3234 // the old nodes. 3235 unsigned NumChains = MatcherTable[MatcherIndex++]; 3236 assert(NumChains != 0 && "Can't TF zero chains"); 3237 3238 assert(ChainNodesMatched.empty() && 3239 "Should only have one EmitMergeInputChains per match"); 3240 3241 // Read all of the chained nodes. 3242 for (unsigned i = 0; i != NumChains; ++i) { 3243 unsigned RecNo = MatcherTable[MatcherIndex++]; 3244 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3245 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3246 3247 // FIXME: What if other value results of the node have uses not matched 3248 // by this pattern? 3249 if (ChainNodesMatched.back() != NodeToMatch && 3250 !RecordedNodes[RecNo].first.hasOneUse()) { 3251 ChainNodesMatched.clear(); 3252 break; 3253 } 3254 } 3255 3256 // If the inner loop broke out, the match fails. 3257 if (ChainNodesMatched.empty()) 3258 break; 3259 3260 // Merge the input chains if they are not intra-pattern references. 3261 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3262 3263 if (!InputChain.getNode()) 3264 break; // Failed to merge. 3265 3266 continue; 3267 } 3268 3269 case OPC_EmitCopyToReg: { 3270 unsigned RecNo = MatcherTable[MatcherIndex++]; 3271 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); 3272 unsigned DestPhysReg = MatcherTable[MatcherIndex++]; 3273 3274 if (!InputChain.getNode()) 3275 InputChain = CurDAG->getEntryNode(); 3276 3277 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), 3278 DestPhysReg, RecordedNodes[RecNo].first, 3279 InputGlue); 3280 3281 InputGlue = InputChain.getValue(1); 3282 continue; 3283 } 3284 3285 case OPC_EmitNodeXForm: { 3286 unsigned XFormNo = MatcherTable[MatcherIndex++]; 3287 unsigned RecNo = MatcherTable[MatcherIndex++]; 3288 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); 3289 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); 3290 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); 3291 continue; 3292 } 3293 3294 case OPC_EmitNode: case OPC_MorphNodeTo: 3295 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: 3296 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { 3297 uint16_t TargetOpc = MatcherTable[MatcherIndex++]; 3298 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3299 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; 3300 // Get the result VT list. 3301 unsigned NumVTs; 3302 // If this is one of the compressed forms, get the number of VTs based 3303 // on the Opcode. Otherwise read the next byte from the table. 3304 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) 3305 NumVTs = Opcode - OPC_MorphNodeTo0; 3306 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) 3307 NumVTs = Opcode - OPC_EmitNode0; 3308 else 3309 NumVTs = MatcherTable[MatcherIndex++]; 3310 SmallVector<EVT, 4> VTs; 3311 for (unsigned i = 0; i != NumVTs; ++i) { 3312 MVT::SimpleValueType VT = 3313 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3314 if (VT == MVT::iPTR) 3315 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; 3316 VTs.push_back(VT); 3317 } 3318 3319 if (EmitNodeInfo & OPFL_Chain) 3320 VTs.push_back(MVT::Other); 3321 if (EmitNodeInfo & OPFL_GlueOutput) 3322 VTs.push_back(MVT::Glue); 3323 3324 // This is hot code, so optimize the two most common cases of 1 and 2 3325 // results. 3326 SDVTList VTList; 3327 if (VTs.size() == 1) 3328 VTList = CurDAG->getVTList(VTs[0]); 3329 else if (VTs.size() == 2) 3330 VTList = CurDAG->getVTList(VTs[0], VTs[1]); 3331 else 3332 VTList = CurDAG->getVTList(VTs); 3333 3334 // Get the operand list. 3335 unsigned NumOps = MatcherTable[MatcherIndex++]; 3336 SmallVector<SDValue, 8> Ops; 3337 for (unsigned i = 0; i != NumOps; ++i) { 3338 unsigned RecNo = MatcherTable[MatcherIndex++]; 3339 if (RecNo & 128) 3340 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); 3341 3342 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); 3343 Ops.push_back(RecordedNodes[RecNo].first); 3344 } 3345 3346 // If there are variadic operands to add, handle them now. 3347 if (EmitNodeInfo & OPFL_VariadicInfo) { 3348 // Determine the start index to copy from. 3349 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); 3350 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; 3351 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && 3352 "Invalid variadic node"); 3353 // Copy all of the variadic operands, not including a potential glue 3354 // input. 3355 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); 3356 i != e; ++i) { 3357 SDValue V = NodeToMatch->getOperand(i); 3358 if (V.getValueType() == MVT::Glue) break; 3359 Ops.push_back(V); 3360 } 3361 } 3362 3363 // If this has chain/glue inputs, add them. 3364 if (EmitNodeInfo & OPFL_Chain) 3365 Ops.push_back(InputChain); 3366 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) 3367 Ops.push_back(InputGlue); 3368 3369 // Create the node. 3370 SDNode *Res = nullptr; 3371 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || 3372 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); 3373 if (!IsMorphNodeTo) { 3374 // If this is a normal EmitNode command, just create the new node and 3375 // add the results to the RecordedNodes list. 3376 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), 3377 VTList, Ops); 3378 3379 // Add all the non-glue/non-chain results to the RecordedNodes list. 3380 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 3381 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; 3382 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), 3383 nullptr)); 3384 } 3385 3386 } else { 3387 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && 3388 "NodeToMatch was removed partway through selection"); 3389 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, 3390 SDNode *E) { 3391 auto &Chain = ChainNodesMatched; 3392 assert((!E || llvm::find(Chain, N) == Chain.end()) && 3393 "Chain node replaced during MorphNode"); 3394 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); 3395 }); 3396 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo); 3397 } 3398 3399 // If the node had chain/glue results, update our notion of the current 3400 // chain and glue. 3401 if (EmitNodeInfo & OPFL_GlueOutput) { 3402 InputGlue = SDValue(Res, VTs.size()-1); 3403 if (EmitNodeInfo & OPFL_Chain) 3404 InputChain = SDValue(Res, VTs.size()-2); 3405 } else if (EmitNodeInfo & OPFL_Chain) 3406 InputChain = SDValue(Res, VTs.size()-1); 3407 3408 // If the OPFL_MemRefs glue is set on this node, slap all of the 3409 // accumulated memrefs onto it. 3410 // 3411 // FIXME: This is vastly incorrect for patterns with multiple outputs 3412 // instructions that access memory and for ComplexPatterns that match 3413 // loads. 3414 if (EmitNodeInfo & OPFL_MemRefs) { 3415 // Only attach load or store memory operands if the generated 3416 // instruction may load or store. 3417 const MCInstrDesc &MCID = TII->get(TargetOpc); 3418 bool mayLoad = MCID.mayLoad(); 3419 bool mayStore = MCID.mayStore(); 3420 3421 unsigned NumMemRefs = 0; 3422 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = 3423 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { 3424 if ((*I)->isLoad()) { 3425 if (mayLoad) 3426 ++NumMemRefs; 3427 } else if ((*I)->isStore()) { 3428 if (mayStore) 3429 ++NumMemRefs; 3430 } else { 3431 ++NumMemRefs; 3432 } 3433 } 3434 3435 MachineSDNode::mmo_iterator MemRefs = 3436 MF->allocateMemRefsArray(NumMemRefs); 3437 3438 MachineSDNode::mmo_iterator MemRefsPos = MemRefs; 3439 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = 3440 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { 3441 if ((*I)->isLoad()) { 3442 if (mayLoad) 3443 *MemRefsPos++ = *I; 3444 } else if ((*I)->isStore()) { 3445 if (mayStore) 3446 *MemRefsPos++ = *I; 3447 } else { 3448 *MemRefsPos++ = *I; 3449 } 3450 } 3451 3452 cast<MachineSDNode>(Res) 3453 ->setMemRefs(MemRefs, MemRefs + NumMemRefs); 3454 } 3455 3456 DEBUG(dbgs() << " " 3457 << (IsMorphNodeTo ? "Morphed" : "Created") 3458 << " node: "; Res->dump(CurDAG); dbgs() << "\n"); 3459 3460 // If this was a MorphNodeTo then we're completely done! 3461 if (IsMorphNodeTo) { 3462 // Update chain uses. 3463 UpdateChains(Res, InputChain, ChainNodesMatched, true); 3464 return; 3465 } 3466 continue; 3467 } 3468 3469 case OPC_CompleteMatch: { 3470 // The match has been completed, and any new nodes (if any) have been 3471 // created. Patch up references to the matched dag to use the newly 3472 // created nodes. 3473 unsigned NumResults = MatcherTable[MatcherIndex++]; 3474 3475 for (unsigned i = 0; i != NumResults; ++i) { 3476 unsigned ResSlot = MatcherTable[MatcherIndex++]; 3477 if (ResSlot & 128) 3478 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); 3479 3480 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); 3481 SDValue Res = RecordedNodes[ResSlot].first; 3482 3483 assert(i < NodeToMatch->getNumValues() && 3484 NodeToMatch->getValueType(i) != MVT::Other && 3485 NodeToMatch->getValueType(i) != MVT::Glue && 3486 "Invalid number of results to complete!"); 3487 assert((NodeToMatch->getValueType(i) == Res.getValueType() || 3488 NodeToMatch->getValueType(i) == MVT::iPTR || 3489 Res.getValueType() == MVT::iPTR || 3490 NodeToMatch->getValueType(i).getSizeInBits() == 3491 Res.getValueType().getSizeInBits()) && 3492 "invalid replacement"); 3493 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res); 3494 } 3495 3496 // Update chain uses. 3497 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); 3498 3499 // If the root node defines glue, we need to update it to the glue result. 3500 // TODO: This never happens in our tests and I think it can be removed / 3501 // replaced with an assert, but if we do it this the way the change is 3502 // NFC. 3503 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == 3504 MVT::Glue && 3505 InputGlue.getNode()) 3506 CurDAG->ReplaceAllUsesOfValueWith( 3507 SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue); 3508 3509 assert(NodeToMatch->use_empty() && 3510 "Didn't replace all uses of the node?"); 3511 CurDAG->RemoveDeadNode(NodeToMatch); 3512 3513 return; 3514 } 3515 } 3516 3517 // If the code reached this point, then the match failed. See if there is 3518 // another child to try in the current 'Scope', otherwise pop it until we 3519 // find a case to check. 3520 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n"); 3521 ++NumDAGIselRetries; 3522 while (1) { 3523 if (MatchScopes.empty()) { 3524 CannotYetSelect(NodeToMatch); 3525 return; 3526 } 3527 3528 // Restore the interpreter state back to the point where the scope was 3529 // formed. 3530 MatchScope &LastScope = MatchScopes.back(); 3531 RecordedNodes.resize(LastScope.NumRecordedNodes); 3532 NodeStack.clear(); 3533 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); 3534 N = NodeStack.back(); 3535 3536 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) 3537 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); 3538 MatcherIndex = LastScope.FailIndex; 3539 3540 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); 3541 3542 InputChain = LastScope.InputChain; 3543 InputGlue = LastScope.InputGlue; 3544 if (!LastScope.HasChainNodesMatched) 3545 ChainNodesMatched.clear(); 3546 3547 // Check to see what the offset is at the new MatcherIndex. If it is zero 3548 // we have reached the end of this scope, otherwise we have another child 3549 // in the current scope to try. 3550 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3551 if (NumToSkip & 128) 3552 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3553 3554 // If we have another child in this scope to match, update FailIndex and 3555 // try it. 3556 if (NumToSkip != 0) { 3557 LastScope.FailIndex = MatcherIndex+NumToSkip; 3558 break; 3559 } 3560 3561 // End of this scope, pop it and try the next child in the containing 3562 // scope. 3563 MatchScopes.pop_back(); 3564 } 3565 } 3566 } 3567 3568 void SelectionDAGISel::CannotYetSelect(SDNode *N) { 3569 std::string msg; 3570 raw_string_ostream Msg(msg); 3571 Msg << "Cannot select: "; 3572 3573 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && 3574 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && 3575 N->getOpcode() != ISD::INTRINSIC_VOID) { 3576 N->printrFull(Msg, CurDAG); 3577 Msg << "\nIn function: " << MF->getName(); 3578 } else { 3579 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; 3580 unsigned iid = 3581 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); 3582 if (iid < Intrinsic::num_intrinsics) 3583 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid); 3584 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) 3585 Msg << "target intrinsic %" << TII->getName(iid); 3586 else 3587 Msg << "unknown intrinsic #" << iid; 3588 } 3589 report_fatal_error(Msg.str()); 3590 } 3591 3592 char SelectionDAGISel::ID = 0; 3593