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