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