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