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