SelectionDAGISel.cpp revision 8b797f5ab7527c243fa1d1310c083100ca6bdd9b
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#define DEBUG_TYPE "isel" 15#include "ScheduleDAGSDNodes.h" 16#include "SelectionDAGBuild.h" 17#include "llvm/CodeGen/SelectionDAGISel.h" 18#include "llvm/Analysis/AliasAnalysis.h" 19#include "llvm/Constants.h" 20#include "llvm/CallingConv.h" 21#include "llvm/DerivedTypes.h" 22#include "llvm/Function.h" 23#include "llvm/GlobalVariable.h" 24#include "llvm/InlineAsm.h" 25#include "llvm/Instructions.h" 26#include "llvm/Intrinsics.h" 27#include "llvm/IntrinsicInst.h" 28#include "llvm/CodeGen/FastISel.h" 29#include "llvm/CodeGen/GCStrategy.h" 30#include "llvm/CodeGen/GCMetadata.h" 31#include "llvm/CodeGen/MachineFunction.h" 32#include "llvm/CodeGen/MachineFunctionAnalysis.h" 33#include "llvm/CodeGen/MachineFrameInfo.h" 34#include "llvm/CodeGen/MachineInstrBuilder.h" 35#include "llvm/CodeGen/MachineJumpTableInfo.h" 36#include "llvm/CodeGen/MachineModuleInfo.h" 37#include "llvm/CodeGen/MachineRegisterInfo.h" 38#include "llvm/CodeGen/ScheduleHazardRecognizer.h" 39#include "llvm/CodeGen/SchedulerRegistry.h" 40#include "llvm/CodeGen/SelectionDAG.h" 41#include "llvm/CodeGen/DwarfWriter.h" 42#include "llvm/Target/TargetRegisterInfo.h" 43#include "llvm/Target/TargetData.h" 44#include "llvm/Target/TargetFrameInfo.h" 45#include "llvm/Target/TargetInstrInfo.h" 46#include "llvm/Target/TargetLowering.h" 47#include "llvm/Target/TargetMachine.h" 48#include "llvm/Target/TargetOptions.h" 49#include "llvm/Support/Compiler.h" 50#include "llvm/Support/Debug.h" 51#include "llvm/Support/ErrorHandling.h" 52#include "llvm/Support/MathExtras.h" 53#include "llvm/Support/Timer.h" 54#include "llvm/Support/raw_ostream.h" 55#include <algorithm> 56using namespace llvm; 57 58static cl::opt<bool> 59DisableLegalizeTypes("disable-legalize-types", cl::Hidden); 60static cl::opt<bool> 61EnableFastISelVerbose("fast-isel-verbose", cl::Hidden, 62 cl::desc("Enable verbose messages in the \"fast\" " 63 "instruction selector")); 64static cl::opt<bool> 65EnableFastISelAbort("fast-isel-abort", cl::Hidden, 66 cl::desc("Enable abort calls when \"fast\" instruction fails")); 67static cl::opt<bool> 68SchedLiveInCopies("schedule-livein-copies", 69 cl::desc("Schedule copies of livein registers"), 70 cl::init(false)); 71 72#ifndef NDEBUG 73static cl::opt<bool> 74ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, 75 cl::desc("Pop up a window to show dags before the first " 76 "dag combine pass")); 77static cl::opt<bool> 78ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, 79 cl::desc("Pop up a window to show dags before legalize types")); 80static cl::opt<bool> 81ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, 82 cl::desc("Pop up a window to show dags before legalize")); 83static cl::opt<bool> 84ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, 85 cl::desc("Pop up a window to show dags before the second " 86 "dag combine pass")); 87static cl::opt<bool> 88ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, 89 cl::desc("Pop up a window to show dags before the post legalize types" 90 " dag combine pass")); 91static cl::opt<bool> 92ViewISelDAGs("view-isel-dags", cl::Hidden, 93 cl::desc("Pop up a window to show isel dags as they are selected")); 94static cl::opt<bool> 95ViewSchedDAGs("view-sched-dags", cl::Hidden, 96 cl::desc("Pop up a window to show sched dags as they are processed")); 97static cl::opt<bool> 98ViewSUnitDAGs("view-sunit-dags", cl::Hidden, 99 cl::desc("Pop up a window to show SUnit dags after they are processed")); 100#else 101static const bool ViewDAGCombine1 = false, 102 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false, 103 ViewDAGCombine2 = false, 104 ViewDAGCombineLT = false, 105 ViewISelDAGs = false, ViewSchedDAGs = false, 106 ViewSUnitDAGs = false; 107#endif 108 109//===---------------------------------------------------------------------===// 110/// 111/// RegisterScheduler class - Track the registration of instruction schedulers. 112/// 113//===---------------------------------------------------------------------===// 114MachinePassRegistry RegisterScheduler::Registry; 115 116//===---------------------------------------------------------------------===// 117/// 118/// ISHeuristic command line option for instruction schedulers. 119/// 120//===---------------------------------------------------------------------===// 121static cl::opt<RegisterScheduler::FunctionPassCtor, false, 122 RegisterPassParser<RegisterScheduler> > 123ISHeuristic("pre-RA-sched", 124 cl::init(&createDefaultScheduler), 125 cl::desc("Instruction schedulers available (before register" 126 " allocation):")); 127 128static RegisterScheduler 129defaultListDAGScheduler("default", "Best scheduler for the target", 130 createDefaultScheduler); 131 132namespace llvm { 133 //===--------------------------------------------------------------------===// 134 /// createDefaultScheduler - This creates an instruction scheduler appropriate 135 /// for the target. 136 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS, 137 CodeGenOpt::Level OptLevel) { 138 const TargetLowering &TLI = IS->getTargetLowering(); 139 140 if (OptLevel == CodeGenOpt::None) 141 return createFastDAGScheduler(IS, OptLevel); 142 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) 143 return createTDListDAGScheduler(IS, OptLevel); 144 assert(TLI.getSchedulingPreference() == 145 TargetLowering::SchedulingForRegPressure && "Unknown sched type!"); 146 return createBURRListDAGScheduler(IS, OptLevel); 147 } 148} 149 150// EmitInstrWithCustomInserter - This method should be implemented by targets 151// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These 152// instructions are special in various ways, which require special support to 153// insert. The specified MachineInstr is created but not inserted into any 154// basic blocks, and the scheduler passes ownership of it to this method. 155MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 156 MachineBasicBlock *MBB) const { 157#ifndef NDEBUG 158 cerr << "If a target marks an instruction with " 159 "'usesCustomDAGSchedInserter', it must implement " 160 "TargetLowering::EmitInstrWithCustomInserter!"; 161#endif 162 llvm_unreachable(0); 163 return 0; 164} 165 166/// EmitLiveInCopy - Emit a copy for a live in physical register. If the 167/// physical register has only a single copy use, then coalesced the copy 168/// if possible. 169static void EmitLiveInCopy(MachineBasicBlock *MBB, 170 MachineBasicBlock::iterator &InsertPos, 171 unsigned VirtReg, unsigned PhysReg, 172 const TargetRegisterClass *RC, 173 DenseMap<MachineInstr*, unsigned> &CopyRegMap, 174 const MachineRegisterInfo &MRI, 175 const TargetRegisterInfo &TRI, 176 const TargetInstrInfo &TII) { 177 unsigned NumUses = 0; 178 MachineInstr *UseMI = NULL; 179 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg), 180 UE = MRI.use_end(); UI != UE; ++UI) { 181 UseMI = &*UI; 182 if (++NumUses > 1) 183 break; 184 } 185 186 // If the number of uses is not one, or the use is not a move instruction, 187 // don't coalesce. Also, only coalesce away a virtual register to virtual 188 // register copy. 189 bool Coalesced = false; 190 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 191 if (NumUses == 1 && 192 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) && 193 TargetRegisterInfo::isVirtualRegister(DstReg)) { 194 VirtReg = DstReg; 195 Coalesced = true; 196 } 197 198 // Now find an ideal location to insert the copy. 199 MachineBasicBlock::iterator Pos = InsertPos; 200 while (Pos != MBB->begin()) { 201 MachineInstr *PrevMI = prior(Pos); 202 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI); 203 // copyRegToReg might emit multiple instructions to do a copy. 204 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second; 205 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg)) 206 // This is what the BB looks like right now: 207 // r1024 = mov r0 208 // ... 209 // r1 = mov r1024 210 // 211 // We want to insert "r1025 = mov r1". Inserting this copy below the 212 // move to r1024 makes it impossible for that move to be coalesced. 213 // 214 // r1025 = mov r1 215 // r1024 = mov r0 216 // ... 217 // r1 = mov 1024 218 // r2 = mov 1025 219 break; // Woot! Found a good location. 220 --Pos; 221 } 222 223 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC); 224 assert(Emitted && "Unable to issue a live-in copy instruction!\n"); 225 (void) Emitted; 226 227CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg)); 228 if (Coalesced) { 229 if (&*InsertPos == UseMI) ++InsertPos; 230 MBB->erase(UseMI); 231 } 232} 233 234/// EmitLiveInCopies - If this is the first basic block in the function, 235/// and if it has live ins that need to be copied into vregs, emit the 236/// copies into the block. 237static void EmitLiveInCopies(MachineBasicBlock *EntryMBB, 238 const MachineRegisterInfo &MRI, 239 const TargetRegisterInfo &TRI, 240 const TargetInstrInfo &TII) { 241 if (SchedLiveInCopies) { 242 // Emit the copies at a heuristically-determined location in the block. 243 DenseMap<MachineInstr*, unsigned> CopyRegMap; 244 MachineBasicBlock::iterator InsertPos = EntryMBB->begin(); 245 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(), 246 E = MRI.livein_end(); LI != E; ++LI) 247 if (LI->second) { 248 const TargetRegisterClass *RC = MRI.getRegClass(LI->second); 249 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first, 250 RC, CopyRegMap, MRI, TRI, TII); 251 } 252 } else { 253 // Emit the copies into the top of the block. 254 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(), 255 E = MRI.livein_end(); LI != E; ++LI) 256 if (LI->second) { 257 const TargetRegisterClass *RC = MRI.getRegClass(LI->second); 258 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(), 259 LI->second, LI->first, RC, RC); 260 assert(Emitted && "Unable to issue a live-in copy instruction!\n"); 261 (void) Emitted; 262 } 263 } 264} 265 266//===----------------------------------------------------------------------===// 267// SelectionDAGISel code 268//===----------------------------------------------------------------------===// 269 270SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) : 271 MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()), 272 FuncInfo(new FunctionLoweringInfo(TLI)), 273 CurDAG(new SelectionDAG(TLI, *FuncInfo)), 274 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)), 275 GFI(), 276 OptLevel(OL), 277 DAGSize(0) 278{} 279 280SelectionDAGISel::~SelectionDAGISel() { 281 delete SDL; 282 delete CurDAG; 283 delete FuncInfo; 284} 285 286unsigned SelectionDAGISel::MakeReg(MVT VT) { 287 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT)); 288} 289 290void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 291 AU.addRequired<AliasAnalysis>(); 292 AU.addPreserved<AliasAnalysis>(); 293 AU.addRequired<GCModuleInfo>(); 294 AU.addPreserved<GCModuleInfo>(); 295 AU.addRequired<DwarfWriter>(); 296 AU.addPreserved<DwarfWriter>(); 297 MachineFunctionPass::getAnalysisUsage(AU); 298} 299 300bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { 301 Function &Fn = *mf.getFunction(); 302 303 // Do some sanity-checking on the command-line options. 304 assert((!EnableFastISelVerbose || EnableFastISel) && 305 "-fast-isel-verbose requires -fast-isel"); 306 assert((!EnableFastISelAbort || EnableFastISel) && 307 "-fast-isel-abort requires -fast-isel"); 308 309 // Get alias analysis for load/store combining. 310 AA = &getAnalysis<AliasAnalysis>(); 311 312 MF = &mf; 313 const TargetInstrInfo &TII = *TM.getInstrInfo(); 314 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 315 316 if (Fn.hasGC()) 317 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn); 318 else 319 GFI = 0; 320 RegInfo = &MF->getRegInfo(); 321 DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n"); 322 323 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 324 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>(); 325 CurDAG->init(*MF, MMI, DW); 326 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel); 327 SDL->init(GFI, *AA); 328 329 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 330 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator())) 331 // Mark landing pad. 332 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); 333 334 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII); 335 336 // If the first basic block in the function has live ins that need to be 337 // copied into vregs, emit the copies into the top of the block before 338 // emitting the code for the block. 339 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII); 340 341 // Add function live-ins to entry block live-in set. 342 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(), 343 E = RegInfo->livein_end(); I != E; ++I) 344 MF->begin()->addLiveIn(I->first); 345 346#ifndef NDEBUG 347 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() && 348 "Not all catch info was assigned to a landing pad!"); 349#endif 350 351 FuncInfo->clear(); 352 353 return true; 354} 355 356static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB, 357 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) { 358 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I) 359 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) { 360 // Apply the catch info to DestBB. 361 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]); 362#ifndef NDEBUG 363 if (!FLI.MBBMap[SrcBB]->isLandingPad()) 364 FLI.CatchInfoFound.insert(EHSel); 365#endif 366 } 367} 368 369/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and 370/// whether object offset >= 0. 371static bool 372IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) { 373 if (!isa<FrameIndexSDNode>(Op)) return false; 374 375 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op); 376 int FrameIdx = FrameIdxNode->getIndex(); 377 return MFI->isFixedObjectIndex(FrameIdx) && 378 MFI->getObjectOffset(FrameIdx) >= 0; 379} 380 381/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could 382/// possibly be overwritten when lowering the outgoing arguments in a tail 383/// call. Currently the implementation of this call is very conservative and 384/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with 385/// virtual registers would be overwritten by direct lowering. 386static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op, 387 MachineFrameInfo *MFI) { 388 RegisterSDNode * OpReg = NULL; 389 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS || 390 (Op.getOpcode()== ISD::CopyFromReg && 391 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) && 392 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) || 393 (Op.getOpcode() == ISD::LOAD && 394 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) || 395 (Op.getOpcode() == ISD::MERGE_VALUES && 396 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD && 397 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()). 398 getOperand(1)))) 399 return true; 400 return false; 401} 402 403/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the 404/// DAG and fixes their tailcall attribute operand. 405static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 406 const TargetLowering& TLI) { 407 SDNode * Ret = NULL; 408 SDValue Terminator = DAG.getRoot(); 409 410 // Find RET node. 411 if (Terminator.getOpcode() == ISD::RET) { 412 Ret = Terminator.getNode(); 413 } 414 415 // Fix tail call attribute of CALL nodes. 416 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(), 417 BI = DAG.allnodes_end(); BI != BE; ) { 418 --BI; 419 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) { 420 SDValue OpRet(Ret, 0); 421 SDValue OpCall(BI, 0); 422 bool isMarkedTailCall = TheCall->isTailCall(); 423 // If CALL node has tail call attribute set to true and the call is not 424 // eligible (no RET or the target rejects) the attribute is fixed to 425 // false. The TargetLowering::IsEligibleForTailCallOptimization function 426 // must correctly identify tail call optimizable calls. 427 if (!isMarkedTailCall) continue; 428 if (Ret==NULL || 429 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) { 430 // Not eligible. Mark CALL node as non tail call. Note that we 431 // can modify the call node in place since calls are not CSE'd. 432 TheCall->setNotTailCall(); 433 } else { 434 // Look for tail call clobbered arguments. Emit a series of 435 // copyto/copyfrom virtual register nodes to protect them. 436 SmallVector<SDValue, 32> Ops; 437 SDValue Chain = TheCall->getChain(), InFlag; 438 Ops.push_back(Chain); 439 Ops.push_back(TheCall->getCallee()); 440 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) { 441 SDValue Arg = TheCall->getArg(i); 442 bool isByVal = TheCall->getArgFlags(i).isByVal(); 443 MachineFunction &MF = DAG.getMachineFunction(); 444 MachineFrameInfo *MFI = MF.getFrameInfo(); 445 if (!isByVal && 446 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) { 447 MVT VT = Arg.getValueType(); 448 unsigned VReg = MF.getRegInfo(). 449 createVirtualRegister(TLI.getRegClassFor(VT)); 450 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(), 451 VReg, Arg, InFlag); 452 InFlag = Chain.getValue(1); 453 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(), 454 VReg, VT, InFlag); 455 Chain = Arg.getValue(1); 456 InFlag = Arg.getValue(2); 457 } 458 Ops.push_back(Arg); 459 Ops.push_back(TheCall->getArgFlagsVal(i)); 460 } 461 // Link in chain of CopyTo/CopyFromReg. 462 Ops[0] = Chain; 463 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size()); 464 } 465 } 466 } 467} 468 469void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, 470 BasicBlock::iterator Begin, 471 BasicBlock::iterator End) { 472 SDL->setCurrentBasicBlock(BB); 473 474 // Lower all of the non-terminator instructions. 475 for (BasicBlock::iterator I = Begin; I != End; ++I) 476 if (!isa<TerminatorInst>(I)) 477 SDL->visit(*I); 478 479 // Ensure that all instructions which are used outside of their defining 480 // blocks are available as virtual registers. Invoke is handled elsewhere. 481 for (BasicBlock::iterator I = Begin; I != End; ++I) 482 if (!isa<PHINode>(I) && !isa<InvokeInst>(I)) 483 SDL->CopyToExportRegsIfNeeded(I); 484 485 // Handle PHI nodes in successor blocks. 486 if (End == LLVMBB->end()) { 487 HandlePHINodesInSuccessorBlocks(LLVMBB); 488 489 // Lower the terminator after the copies are emitted. 490 SDL->visit(*LLVMBB->getTerminator()); 491 } 492 493 // Make sure the root of the DAG is up-to-date. 494 CurDAG->setRoot(SDL->getControlRoot()); 495 496 // Check whether calls in this block are real tail calls. Fix up CALL nodes 497 // with correct tailcall attribute so that the target can rely on the tailcall 498 // attribute indicating whether the call is really eligible for tail call 499 // optimization. 500 if (PerformTailCallOpt) 501 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI); 502 503 // Final step, emit the lowered DAG as machine code. 504 CodeGenAndEmitDAG(); 505 SDL->clear(); 506} 507 508void SelectionDAGISel::ComputeLiveOutVRegInfo() { 509 SmallPtrSet<SDNode*, 128> VisitedNodes; 510 SmallVector<SDNode*, 128> Worklist; 511 512 Worklist.push_back(CurDAG->getRoot().getNode()); 513 514 APInt Mask; 515 APInt KnownZero; 516 APInt KnownOne; 517 518 while (!Worklist.empty()) { 519 SDNode *N = Worklist.back(); 520 Worklist.pop_back(); 521 522 // If we've already seen this node, ignore it. 523 if (!VisitedNodes.insert(N)) 524 continue; 525 526 // Otherwise, add all chain operands to the worklist. 527 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 528 if (N->getOperand(i).getValueType() == MVT::Other) 529 Worklist.push_back(N->getOperand(i).getNode()); 530 531 // If this is a CopyToReg with a vreg dest, process it. 532 if (N->getOpcode() != ISD::CopyToReg) 533 continue; 534 535 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); 536 if (!TargetRegisterInfo::isVirtualRegister(DestReg)) 537 continue; 538 539 // Ignore non-scalar or non-integer values. 540 SDValue Src = N->getOperand(2); 541 MVT SrcVT = Src.getValueType(); 542 if (!SrcVT.isInteger() || SrcVT.isVector()) 543 continue; 544 545 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); 546 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits()); 547 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne); 548 549 // Only install this information if it tells us something. 550 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) { 551 DestReg -= TargetRegisterInfo::FirstVirtualRegister; 552 if (DestReg >= FuncInfo->LiveOutRegInfo.size()) 553 FuncInfo->LiveOutRegInfo.resize(DestReg+1); 554 FunctionLoweringInfo::LiveOutInfo &LOI = 555 FuncInfo->LiveOutRegInfo[DestReg]; 556 LOI.NumSignBits = NumSignBits; 557 LOI.KnownOne = KnownOne; 558 LOI.KnownZero = KnownZero; 559 } 560 } 561} 562 563void SelectionDAGISel::CodeGenAndEmitDAG() { 564 std::string GroupName; 565 if (TimePassesIsEnabled) 566 GroupName = "Instruction Selection and Scheduling"; 567 std::string BlockName; 568 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs || 569 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs || 570 ViewSUnitDAGs) 571 BlockName = MF->getFunction()->getNameStr() + ":" + 572 BB->getBasicBlock()->getNameStr(); 573 574 DOUT << "Initial selection DAG:\n"; 575 DEBUG(CurDAG->dump()); 576 577 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName); 578 579 // Run the DAG combiner in pre-legalize mode. 580 if (TimePassesIsEnabled) { 581 NamedRegionTimer T("DAG Combining 1", GroupName); 582 CurDAG->Combine(Unrestricted, *AA, OptLevel); 583 } else { 584 CurDAG->Combine(Unrestricted, *AA, OptLevel); 585 } 586 587 DOUT << "Optimized lowered selection DAG:\n"; 588 DEBUG(CurDAG->dump()); 589 590 // Second step, hack on the DAG until it only uses operations and types that 591 // the target supports. 592 if (!DisableLegalizeTypes) { 593 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " + 594 BlockName); 595 596 bool Changed; 597 if (TimePassesIsEnabled) { 598 NamedRegionTimer T("Type Legalization", GroupName); 599 Changed = CurDAG->LegalizeTypes(); 600 } else { 601 Changed = CurDAG->LegalizeTypes(); 602 } 603 604 DOUT << "Type-legalized selection DAG:\n"; 605 DEBUG(CurDAG->dump()); 606 607 if (Changed) { 608 if (ViewDAGCombineLT) 609 CurDAG->viewGraph("dag-combine-lt input for " + BlockName); 610 611 // Run the DAG combiner in post-type-legalize mode. 612 if (TimePassesIsEnabled) { 613 NamedRegionTimer T("DAG Combining after legalize types", GroupName); 614 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel); 615 } else { 616 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel); 617 } 618 619 DOUT << "Optimized type-legalized selection DAG:\n"; 620 DEBUG(CurDAG->dump()); 621 } 622 623 if (TimePassesIsEnabled) { 624 NamedRegionTimer T("Vector Legalization", GroupName); 625 Changed = CurDAG->LegalizeVectors(); 626 } else { 627 Changed = CurDAG->LegalizeVectors(); 628 } 629 630 if (Changed) { 631 if (TimePassesIsEnabled) { 632 NamedRegionTimer T("Type Legalization 2", GroupName); 633 Changed = CurDAG->LegalizeTypes(); 634 } else { 635 Changed = CurDAG->LegalizeTypes(); 636 } 637 638 if (ViewDAGCombineLT) 639 CurDAG->viewGraph("dag-combine-lv input for " + BlockName); 640 641 // Run the DAG combiner in post-type-legalize mode. 642 if (TimePassesIsEnabled) { 643 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName); 644 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel); 645 } else { 646 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel); 647 } 648 649 DOUT << "Optimized vector-legalized selection DAG:\n"; 650 DEBUG(CurDAG->dump()); 651 } 652 } 653 654 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName); 655 656 if (TimePassesIsEnabled) { 657 NamedRegionTimer T("DAG Legalization", GroupName); 658 CurDAG->Legalize(DisableLegalizeTypes, OptLevel); 659 } else { 660 CurDAG->Legalize(DisableLegalizeTypes, OptLevel); 661 } 662 663 DOUT << "Legalized selection DAG:\n"; 664 DEBUG(CurDAG->dump()); 665 666 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName); 667 668 // Run the DAG combiner in post-legalize mode. 669 if (TimePassesIsEnabled) { 670 NamedRegionTimer T("DAG Combining 2", GroupName); 671 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel); 672 } else { 673 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel); 674 } 675 676 DOUT << "Optimized legalized selection DAG:\n"; 677 DEBUG(CurDAG->dump()); 678 679 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName); 680 681 if (OptLevel != CodeGenOpt::None) 682 ComputeLiveOutVRegInfo(); 683 684 // Third, instruction select all of the operations to machine code, adding the 685 // code to the MachineBasicBlock. 686 if (TimePassesIsEnabled) { 687 NamedRegionTimer T("Instruction Selection", GroupName); 688 InstructionSelect(); 689 } else { 690 InstructionSelect(); 691 } 692 693 DOUT << "Selected selection DAG:\n"; 694 DEBUG(CurDAG->dump()); 695 696 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName); 697 698 // Schedule machine code. 699 ScheduleDAGSDNodes *Scheduler = CreateScheduler(); 700 if (TimePassesIsEnabled) { 701 NamedRegionTimer T("Instruction Scheduling", GroupName); 702 Scheduler->Run(CurDAG, BB, BB->end()); 703 } else { 704 Scheduler->Run(CurDAG, BB, BB->end()); 705 } 706 707 if (ViewSUnitDAGs) Scheduler->viewGraph(); 708 709 // Emit machine code to BB. This can change 'BB' to the last block being 710 // inserted into. 711 if (TimePassesIsEnabled) { 712 NamedRegionTimer T("Instruction Creation", GroupName); 713 BB = Scheduler->EmitSchedule(); 714 } else { 715 BB = Scheduler->EmitSchedule(); 716 } 717 718 // Free the scheduler state. 719 if (TimePassesIsEnabled) { 720 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName); 721 delete Scheduler; 722 } else { 723 delete Scheduler; 724 } 725 726 DOUT << "Selected machine code:\n"; 727 DEBUG(BB->dump()); 728} 729 730void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, 731 MachineFunction &MF, 732 MachineModuleInfo *MMI, 733 DwarfWriter *DW, 734 const TargetInstrInfo &TII) { 735 // Initialize the Fast-ISel state, if needed. 736 FastISel *FastIS = 0; 737 if (EnableFastISel) 738 FastIS = TLI.createFastISel(MF, MMI, DW, 739 FuncInfo->ValueMap, 740 FuncInfo->MBBMap, 741 FuncInfo->StaticAllocaMap 742#ifndef NDEBUG 743 , FuncInfo->CatchInfoLost 744#endif 745 ); 746 747 // Iterate over all basic blocks in the function. 748 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 749 BasicBlock *LLVMBB = &*I; 750 BB = FuncInfo->MBBMap[LLVMBB]; 751 752 BasicBlock::iterator const Begin = LLVMBB->begin(); 753 BasicBlock::iterator const End = LLVMBB->end(); 754 BasicBlock::iterator BI = Begin; 755 756 // Lower any arguments needed in this block if this is the entry block. 757 bool SuppressFastISel = false; 758 if (LLVMBB == &Fn.getEntryBlock()) { 759 LowerArguments(LLVMBB); 760 761 // If any of the arguments has the byval attribute, forgo 762 // fast-isel in the entry block. 763 if (FastIS) { 764 unsigned j = 1; 765 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 766 I != E; ++I, ++j) 767 if (Fn.paramHasAttr(j, Attribute::ByVal)) { 768 if (EnableFastISelVerbose || EnableFastISelAbort) 769 cerr << "FastISel skips entry block due to byval argument\n"; 770 SuppressFastISel = true; 771 break; 772 } 773 } 774 } 775 776 if (MMI && BB->isLandingPad()) { 777 // Add a label to mark the beginning of the landing pad. Deletion of the 778 // landing pad can thus be detected via the MachineModuleInfo. 779 unsigned LabelID = MMI->addLandingPad(BB); 780 781 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL); 782 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID); 783 784 // Mark exception register as live in. 785 unsigned Reg = TLI.getExceptionAddressRegister(); 786 if (Reg) BB->addLiveIn(Reg); 787 788 // Mark exception selector register as live in. 789 Reg = TLI.getExceptionSelectorRegister(); 790 if (Reg) BB->addLiveIn(Reg); 791 792 // FIXME: Hack around an exception handling flaw (PR1508): the personality 793 // function and list of typeids logically belong to the invoke (or, if you 794 // like, the basic block containing the invoke), and need to be associated 795 // with it in the dwarf exception handling tables. Currently however the 796 // information is provided by an intrinsic (eh.selector) that can be moved 797 // to unexpected places by the optimizers: if the unwind edge is critical, 798 // then breaking it can result in the intrinsics being in the successor of 799 // the landing pad, not the landing pad itself. This results in exceptions 800 // not being caught because no typeids are associated with the invoke. 801 // This may not be the only way things can go wrong, but it is the only way 802 // we try to work around for the moment. 803 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator()); 804 805 if (Br && Br->isUnconditional()) { // Critical edge? 806 BasicBlock::iterator I, E; 807 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I) 808 if (isa<EHSelectorInst>(I)) 809 break; 810 811 if (I == E) 812 // No catch info found - try to extract some from the successor. 813 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo); 814 } 815 } 816 817 // Before doing SelectionDAG ISel, see if FastISel has been requested. 818 if (FastIS && !SuppressFastISel) { 819 // Emit code for any incoming arguments. This must happen before 820 // beginning FastISel on the entry block. 821 if (LLVMBB == &Fn.getEntryBlock()) { 822 CurDAG->setRoot(SDL->getControlRoot()); 823 CodeGenAndEmitDAG(); 824 SDL->clear(); 825 } 826 FastIS->startNewBlock(BB); 827 // Do FastISel on as many instructions as possible. 828 for (; BI != End; ++BI) { 829 // Just before the terminator instruction, insert instructions to 830 // feed PHI nodes in successor blocks. 831 if (isa<TerminatorInst>(BI)) 832 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) { 833 if (EnableFastISelVerbose || EnableFastISelAbort) { 834 cerr << "FastISel miss: "; 835 BI->dump(); 836 } 837 assert(!EnableFastISelAbort && 838 "FastISel didn't handle a PHI in a successor"); 839 break; 840 } 841 842 // First try normal tablegen-generated "fast" selection. 843 if (FastIS->SelectInstruction(BI)) 844 continue; 845 846 // Next, try calling the target to attempt to handle the instruction. 847 if (FastIS->TargetSelectInstruction(BI)) 848 continue; 849 850 // Then handle certain instructions as single-LLVM-Instruction blocks. 851 if (isa<CallInst>(BI)) { 852 if (EnableFastISelVerbose || EnableFastISelAbort) { 853 cerr << "FastISel missed call: "; 854 BI->dump(); 855 } 856 857 if (BI->getType() != Type::VoidTy) { 858 unsigned &R = FuncInfo->ValueMap[BI]; 859 if (!R) 860 R = FuncInfo->CreateRegForValue(BI); 861 } 862 863 SDL->setCurDebugLoc(FastIS->getCurDebugLoc()); 864 SelectBasicBlock(LLVMBB, BI, next(BI)); 865 // If the instruction was codegen'd with multiple blocks, 866 // inform the FastISel object where to resume inserting. 867 FastIS->setCurrentBlock(BB); 868 continue; 869 } 870 871 // Otherwise, give up on FastISel for the rest of the block. 872 // For now, be a little lenient about non-branch terminators. 873 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) { 874 if (EnableFastISelVerbose || EnableFastISelAbort) { 875 cerr << "FastISel miss: "; 876 BI->dump(); 877 } 878 if (EnableFastISelAbort) 879 // The "fast" selector couldn't handle something and bailed. 880 // For the purpose of debugging, just abort. 881 llvm_unreachable("FastISel didn't select the entire block"); 882 } 883 break; 884 } 885 } 886 887 // Run SelectionDAG instruction selection on the remainder of the block 888 // not handled by FastISel. If FastISel is not run, this is the entire 889 // block. 890 if (BI != End) { 891 // If FastISel is run and it has known DebugLoc then use it. 892 if (FastIS && !FastIS->getCurDebugLoc().isUnknown()) 893 SDL->setCurDebugLoc(FastIS->getCurDebugLoc()); 894 SelectBasicBlock(LLVMBB, BI, End); 895 } 896 897 FinishBasicBlock(); 898 } 899 900 delete FastIS; 901} 902 903void 904SelectionDAGISel::FinishBasicBlock() { 905 906 DOUT << "Target-post-processed machine code:\n"; 907 DEBUG(BB->dump()); 908 909 DOUT << "Total amount of phi nodes to update: " 910 << SDL->PHINodesToUpdate.size() << "\n"; 911 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) 912 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first 913 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";); 914 915 // Next, now that we know what the last MBB the LLVM BB expanded is, update 916 // PHI nodes in successors. 917 if (SDL->SwitchCases.empty() && 918 SDL->JTCases.empty() && 919 SDL->BitTestCases.empty()) { 920 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) { 921 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first; 922 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 923 "This is not a machine PHI node that we are updating!"); 924 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second, 925 false)); 926 PHI->addOperand(MachineOperand::CreateMBB(BB)); 927 } 928 SDL->PHINodesToUpdate.clear(); 929 return; 930 } 931 932 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) { 933 // Lower header first, if it wasn't already lowered 934 if (!SDL->BitTestCases[i].Emitted) { 935 // Set the current basic block to the mbb we wish to insert the code into 936 BB = SDL->BitTestCases[i].Parent; 937 SDL->setCurrentBasicBlock(BB); 938 // Emit the code 939 SDL->visitBitTestHeader(SDL->BitTestCases[i]); 940 CurDAG->setRoot(SDL->getRoot()); 941 CodeGenAndEmitDAG(); 942 SDL->clear(); 943 } 944 945 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) { 946 // Set the current basic block to the mbb we wish to insert the code into 947 BB = SDL->BitTestCases[i].Cases[j].ThisBB; 948 SDL->setCurrentBasicBlock(BB); 949 // Emit the code 950 if (j+1 != ej) 951 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB, 952 SDL->BitTestCases[i].Reg, 953 SDL->BitTestCases[i].Cases[j]); 954 else 955 SDL->visitBitTestCase(SDL->BitTestCases[i].Default, 956 SDL->BitTestCases[i].Reg, 957 SDL->BitTestCases[i].Cases[j]); 958 959 960 CurDAG->setRoot(SDL->getRoot()); 961 CodeGenAndEmitDAG(); 962 SDL->clear(); 963 } 964 965 // Update PHI Nodes 966 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) { 967 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first; 968 MachineBasicBlock *PHIBB = PHI->getParent(); 969 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 970 "This is not a machine PHI node that we are updating!"); 971 // This is "default" BB. We have two jumps to it. From "header" BB and 972 // from last "case" BB. 973 if (PHIBB == SDL->BitTestCases[i].Default) { 974 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 975 false)); 976 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent)); 977 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 978 false)); 979 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases. 980 back().ThisBB)); 981 } 982 // One of "cases" BB. 983 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); 984 j != ej; ++j) { 985 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB; 986 if (cBB->succ_end() != 987 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) { 988 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 989 false)); 990 PHI->addOperand(MachineOperand::CreateMBB(cBB)); 991 } 992 } 993 } 994 } 995 SDL->BitTestCases.clear(); 996 997 // If the JumpTable record is filled in, then we need to emit a jump table. 998 // Updating the PHI nodes is tricky in this case, since we need to determine 999 // whether the PHI is a successor of the range check MBB or the jump table MBB 1000 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) { 1001 // Lower header first, if it wasn't already lowered 1002 if (!SDL->JTCases[i].first.Emitted) { 1003 // Set the current basic block to the mbb we wish to insert the code into 1004 BB = SDL->JTCases[i].first.HeaderBB; 1005 SDL->setCurrentBasicBlock(BB); 1006 // Emit the code 1007 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first); 1008 CurDAG->setRoot(SDL->getRoot()); 1009 CodeGenAndEmitDAG(); 1010 SDL->clear(); 1011 } 1012 1013 // Set the current basic block to the mbb we wish to insert the code into 1014 BB = SDL->JTCases[i].second.MBB; 1015 SDL->setCurrentBasicBlock(BB); 1016 // Emit the code 1017 SDL->visitJumpTable(SDL->JTCases[i].second); 1018 CurDAG->setRoot(SDL->getRoot()); 1019 CodeGenAndEmitDAG(); 1020 SDL->clear(); 1021 1022 // Update PHI Nodes 1023 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) { 1024 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first; 1025 MachineBasicBlock *PHIBB = PHI->getParent(); 1026 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 1027 "This is not a machine PHI node that we are updating!"); 1028 // "default" BB. We can go there only from header BB. 1029 if (PHIBB == SDL->JTCases[i].second.Default) { 1030 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 1031 false)); 1032 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB)); 1033 } 1034 // JT BB. Just iterate over successors here 1035 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) { 1036 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 1037 false)); 1038 PHI->addOperand(MachineOperand::CreateMBB(BB)); 1039 } 1040 } 1041 } 1042 SDL->JTCases.clear(); 1043 1044 // If the switch block involved a branch to one of the actual successors, we 1045 // need to update PHI nodes in that block. 1046 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) { 1047 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first; 1048 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 1049 "This is not a machine PHI node that we are updating!"); 1050 if (BB->isSuccessor(PHI->getParent())) { 1051 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second, 1052 false)); 1053 PHI->addOperand(MachineOperand::CreateMBB(BB)); 1054 } 1055 } 1056 1057 // If we generated any switch lowering information, build and codegen any 1058 // additional DAGs necessary. 1059 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) { 1060 // Set the current basic block to the mbb we wish to insert the code into 1061 BB = SDL->SwitchCases[i].ThisBB; 1062 SDL->setCurrentBasicBlock(BB); 1063 1064 // Emit the code 1065 SDL->visitSwitchCase(SDL->SwitchCases[i]); 1066 CurDAG->setRoot(SDL->getRoot()); 1067 CodeGenAndEmitDAG(); 1068 SDL->clear(); 1069 1070 // Handle any PHI nodes in successors of this chunk, as if we were coming 1071 // from the original BB before switch expansion. Note that PHI nodes can 1072 // occur multiple times in PHINodesToUpdate. We have to be very careful to 1073 // handle them the right number of times. 1074 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS. 1075 for (MachineBasicBlock::iterator Phi = BB->begin(); 1076 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){ 1077 // This value for this PHI node is recorded in PHINodesToUpdate, get it. 1078 for (unsigned pn = 0; ; ++pn) { 1079 assert(pn != SDL->PHINodesToUpdate.size() && 1080 "Didn't find PHI entry!"); 1081 if (SDL->PHINodesToUpdate[pn].first == Phi) { 1082 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn]. 1083 second, false)); 1084 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB)); 1085 break; 1086 } 1087 } 1088 } 1089 1090 // Don't process RHS if same block as LHS. 1091 if (BB == SDL->SwitchCases[i].FalseBB) 1092 SDL->SwitchCases[i].FalseBB = 0; 1093 1094 // If we haven't handled the RHS, do so now. Otherwise, we're done. 1095 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB; 1096 SDL->SwitchCases[i].FalseBB = 0; 1097 } 1098 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0); 1099 } 1100 SDL->SwitchCases.clear(); 1101 1102 SDL->PHINodesToUpdate.clear(); 1103} 1104 1105 1106/// Create the scheduler. If a specific scheduler was specified 1107/// via the SchedulerRegistry, use it, otherwise select the 1108/// one preferred by the target. 1109/// 1110ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { 1111 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault(); 1112 1113 if (!Ctor) { 1114 Ctor = ISHeuristic; 1115 RegisterScheduler::setDefault(Ctor); 1116 } 1117 1118 return Ctor(this, OptLevel); 1119} 1120 1121ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { 1122 return new ScheduleHazardRecognizer(); 1123} 1124 1125//===----------------------------------------------------------------------===// 1126// Helper functions used by the generated instruction selector. 1127//===----------------------------------------------------------------------===// 1128// Calls to these methods are generated by tblgen. 1129 1130/// CheckAndMask - The isel is trying to match something like (and X, 255). If 1131/// the dag combiner simplified the 255, we still want to match. RHS is the 1132/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 1133/// specified in the .td file (e.g. 255). 1134bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 1135 int64_t DesiredMaskS) const { 1136 const APInt &ActualMask = RHS->getAPIntValue(); 1137 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 1138 1139 // If the actual mask exactly matches, success! 1140 if (ActualMask == DesiredMask) 1141 return true; 1142 1143 // If the actual AND mask is allowing unallowed bits, this doesn't match. 1144 if (ActualMask.intersects(~DesiredMask)) 1145 return false; 1146 1147 // Otherwise, the DAG Combiner may have proven that the value coming in is 1148 // either already zero or is not demanded. Check for known zero input bits. 1149 APInt NeededMask = DesiredMask & ~ActualMask; 1150 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 1151 return true; 1152 1153 // TODO: check to see if missing bits are just not demanded. 1154 1155 // Otherwise, this pattern doesn't match. 1156 return false; 1157} 1158 1159/// CheckOrMask - The isel is trying to match something like (or X, 255). If 1160/// the dag combiner simplified the 255, we still want to match. RHS is the 1161/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 1162/// specified in the .td file (e.g. 255). 1163bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 1164 int64_t DesiredMaskS) const { 1165 const APInt &ActualMask = RHS->getAPIntValue(); 1166 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 1167 1168 // If the actual mask exactly matches, success! 1169 if (ActualMask == DesiredMask) 1170 return true; 1171 1172 // If the actual AND mask is allowing unallowed bits, this doesn't match. 1173 if (ActualMask.intersects(~DesiredMask)) 1174 return false; 1175 1176 // Otherwise, the DAG Combiner may have proven that the value coming in is 1177 // either already zero or is not demanded. Check for known zero input bits. 1178 APInt NeededMask = DesiredMask & ~ActualMask; 1179 1180 APInt KnownZero, KnownOne; 1181 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne); 1182 1183 // If all the missing bits in the or are already known to be set, match! 1184 if ((NeededMask & KnownOne) == NeededMask) 1185 return true; 1186 1187 // TODO: check to see if missing bits are just not demanded. 1188 1189 // Otherwise, this pattern doesn't match. 1190 return false; 1191} 1192 1193 1194/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 1195/// by tblgen. Others should not call it. 1196void SelectionDAGISel:: 1197SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) { 1198 std::vector<SDValue> InOps; 1199 std::swap(InOps, Ops); 1200 1201 Ops.push_back(InOps[0]); // input chain. 1202 Ops.push_back(InOps[1]); // input asm string. 1203 1204 unsigned i = 2, e = InOps.size(); 1205 if (InOps[e-1].getValueType() == MVT::Flag) 1206 --e; // Don't process a flag operand if it is here. 1207 1208 while (i != e) { 1209 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 1210 if ((Flags & 7) != 4 /*MEM*/) { 1211 // Just skip over this operand, copying the operands verbatim. 1212 Ops.insert(Ops.end(), InOps.begin()+i, 1213 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); 1214 i += InlineAsm::getNumOperandRegisters(Flags) + 1; 1215 } else { 1216 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && 1217 "Memory operand with multiple values?"); 1218 // Otherwise, this is a memory operand. Ask the target to select it. 1219 std::vector<SDValue> SelOps; 1220 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) { 1221 llvm_report_error("Could not match memory address. Inline asm" 1222 " failure!"); 1223 } 1224 1225 // Add this to the output node. 1226 MVT IntPtrTy = TLI.getPointerTy(); 1227 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3), 1228 IntPtrTy)); 1229 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 1230 i += 2; 1231 } 1232 } 1233 1234 // Add the flag input back if present. 1235 if (e != InOps.size()) 1236 Ops.push_back(InOps.back()); 1237} 1238 1239/// findFlagUse - Return use of MVT::Flag value produced by the specified 1240/// SDNode. 1241/// 1242static SDNode *findFlagUse(SDNode *N) { 1243 unsigned FlagResNo = N->getNumValues()-1; 1244 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 1245 SDUse &Use = I.getUse(); 1246 if (Use.getResNo() == FlagResNo) 1247 return Use.getUser(); 1248 } 1249 return NULL; 1250} 1251 1252/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def". 1253/// This function recursively traverses up the operand chain, ignoring 1254/// certain nodes. 1255static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse, 1256 SDNode *Root, 1257 SmallPtrSet<SDNode*, 16> &Visited) { 1258 if (Use->getNodeId() < Def->getNodeId() || 1259 !Visited.insert(Use)) 1260 return false; 1261 1262 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) { 1263 SDNode *N = Use->getOperand(i).getNode(); 1264 if (N == Def) { 1265 if (Use == ImmedUse || Use == Root) 1266 continue; // We are not looking for immediate use. 1267 assert(N != Root); 1268 return true; 1269 } 1270 1271 // Traverse up the operand chain. 1272 if (findNonImmUse(N, Def, ImmedUse, Root, Visited)) 1273 return true; 1274 } 1275 return false; 1276} 1277 1278/// isNonImmUse - Start searching from Root up the DAG to check is Def can 1279/// be reached. Return true if that's the case. However, ignore direct uses 1280/// by ImmedUse (which would be U in the example illustrated in 1281/// IsLegalAndProfitableToFold) and by Root (which can happen in the store 1282/// case). 1283/// FIXME: to be really generic, we should allow direct use by any node 1284/// that is being folded. But realisticly since we only fold loads which 1285/// have one non-chain use, we only need to watch out for load/op/store 1286/// and load/op/cmp case where the root (store / cmp) may reach the load via 1287/// its chain operand. 1288static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) { 1289 SmallPtrSet<SDNode*, 16> Visited; 1290 return findNonImmUse(Root, Def, ImmedUse, Root, Visited); 1291} 1292 1293/// IsLegalAndProfitableToFold - Returns true if the specific operand node N of 1294/// U can be folded during instruction selection that starts at Root and 1295/// folding N is profitable. 1296bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U, 1297 SDNode *Root) const { 1298 if (OptLevel == CodeGenOpt::None) return false; 1299 1300 // If Root use can somehow reach N through a path that that doesn't contain 1301 // U then folding N would create a cycle. e.g. In the following 1302 // diagram, Root can reach N through X. If N is folded into into Root, then 1303 // X is both a predecessor and a successor of U. 1304 // 1305 // [N*] // 1306 // ^ ^ // 1307 // / \ // 1308 // [U*] [X]? // 1309 // ^ ^ // 1310 // \ / // 1311 // \ / // 1312 // [Root*] // 1313 // 1314 // * indicates nodes to be folded together. 1315 // 1316 // If Root produces a flag, then it gets (even more) interesting. Since it 1317 // will be "glued" together with its flag use in the scheduler, we need to 1318 // check if it might reach N. 1319 // 1320 // [N*] // 1321 // ^ ^ // 1322 // / \ // 1323 // [U*] [X]? // 1324 // ^ ^ // 1325 // \ \ // 1326 // \ | // 1327 // [Root*] | // 1328 // ^ | // 1329 // f | // 1330 // | / // 1331 // [Y] / // 1332 // ^ / // 1333 // f / // 1334 // | / // 1335 // [FU] // 1336 // 1337 // If FU (flag use) indirectly reaches N (the load), and Root folds N 1338 // (call it Fold), then X is a predecessor of FU and a successor of 1339 // Fold. But since Fold and FU are flagged together, this will create 1340 // a cycle in the scheduling graph. 1341 1342 MVT VT = Root->getValueType(Root->getNumValues()-1); 1343 while (VT == MVT::Flag) { 1344 SDNode *FU = findFlagUse(Root); 1345 if (FU == NULL) 1346 break; 1347 Root = FU; 1348 VT = Root->getValueType(Root->getNumValues()-1); 1349 } 1350 1351 return !isNonImmUse(Root, N, U); 1352} 1353 1354 1355char SelectionDAGISel::ID = 0; 1356