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