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