SelectionDAGISel.cpp revision 7cf7e3f33f25544d08492d47cc8a1cbba25dc8d7
1//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source 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 "llvm/CodeGen/SelectionDAGISel.h" 16#include "llvm/CallingConv.h" 17#include "llvm/Constants.h" 18#include "llvm/DerivedTypes.h" 19#include "llvm/Function.h" 20#include "llvm/Instructions.h" 21#include "llvm/Intrinsics.h" 22#include "llvm/CodeGen/MachineFunction.h" 23#include "llvm/CodeGen/MachineFrameInfo.h" 24#include "llvm/CodeGen/MachineInstrBuilder.h" 25#include "llvm/CodeGen/SelectionDAG.h" 26#include "llvm/CodeGen/SSARegMap.h" 27#include "llvm/Target/TargetData.h" 28#include "llvm/Target/TargetFrameInfo.h" 29#include "llvm/Target/TargetInstrInfo.h" 30#include "llvm/Target/TargetLowering.h" 31#include "llvm/Target/TargetMachine.h" 32#include "llvm/Support/CommandLine.h" 33#include "llvm/Support/Debug.h" 34#include <map> 35#include <iostream> 36using namespace llvm; 37 38#ifndef _NDEBUG 39static cl::opt<bool> 40ViewDAGs("view-isel-dags", cl::Hidden, 41 cl::desc("Pop up a window to show isel dags as they are selected")); 42#else 43static const bool ViewDAGS = 0; 44#endif 45 46namespace llvm { 47 //===--------------------------------------------------------------------===// 48 /// FunctionLoweringInfo - This contains information that is global to a 49 /// function that is used when lowering a region of the function. 50 class FunctionLoweringInfo { 51 public: 52 TargetLowering &TLI; 53 Function &Fn; 54 MachineFunction &MF; 55 SSARegMap *RegMap; 56 57 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF); 58 59 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry. 60 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap; 61 62 /// ValueMap - Since we emit code for the function a basic block at a time, 63 /// we must remember which virtual registers hold the values for 64 /// cross-basic-block values. 65 std::map<const Value*, unsigned> ValueMap; 66 67 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in 68 /// the entry block. This allows the allocas to be efficiently referenced 69 /// anywhere in the function. 70 std::map<const AllocaInst*, int> StaticAllocaMap; 71 72 /// BlockLocalArguments - If any arguments are only used in a single basic 73 /// block, and if the target can access the arguments without side-effects, 74 /// avoid emitting CopyToReg nodes for those arguments. This map keeps 75 /// track of which arguments are local to each BB. 76 std::multimap<BasicBlock*, std::pair<Argument*, 77 unsigned> > BlockLocalArguments; 78 79 80 unsigned MakeReg(MVT::ValueType VT) { 81 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 82 } 83 84 unsigned CreateRegForValue(const Value *V) { 85 MVT::ValueType VT = TLI.getValueType(V->getType()); 86 // The common case is that we will only create one register for this 87 // value. If we have that case, create and return the virtual register. 88 unsigned NV = TLI.getNumElements(VT); 89 if (NV == 1) { 90 // If we are promoting this value, pick the next largest supported type. 91 return MakeReg(TLI.getTypeToTransformTo(VT)); 92 } 93 94 // If this value is represented with multiple target registers, make sure 95 // to create enough consequtive registers of the right (smaller) type. 96 unsigned NT = VT-1; // Find the type to use. 97 while (TLI.getNumElements((MVT::ValueType)NT) != 1) 98 --NT; 99 100 unsigned R = MakeReg((MVT::ValueType)NT); 101 for (unsigned i = 1; i != NV; ++i) 102 MakeReg((MVT::ValueType)NT); 103 return R; 104 } 105 106 unsigned InitializeRegForValue(const Value *V) { 107 unsigned &R = ValueMap[V]; 108 assert(R == 0 && "Already initialized this value register!"); 109 return R = CreateRegForValue(V); 110 } 111 }; 112} 113 114/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by 115/// PHI nodes or outside of the basic block that defines it. 116static bool isUsedOutsideOfDefiningBlock(Instruction *I) { 117 if (isa<PHINode>(I)) return true; 118 BasicBlock *BB = I->getParent(); 119 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) 120 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI)) 121 return true; 122 return false; 123} 124 125FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli, 126 Function &fn, MachineFunction &mf) 127 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) { 128 129 // Initialize the mapping of values to registers. This is only set up for 130 // instruction values that are used outside of the block that defines 131 // them. 132 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); 133 AI != E; ++AI) 134 InitializeRegForValue(AI); 135 136 Function::iterator BB = Fn.begin(), E = Fn.end(); 137 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 138 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 139 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) { 140 const Type *Ty = AI->getAllocatedType(); 141 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty); 142 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty); 143 144 // If the alignment of the value is smaller than the size of the value, 145 // and if the size of the value is particularly small (<= 8 bytes), 146 // round up to the size of the value for potentially better performance. 147 // 148 // FIXME: This could be made better with a preferred alignment hook in 149 // TargetData. It serves primarily to 8-byte align doubles for X86. 150 if (Align < TySize && TySize <= 8) Align = TySize; 151 152 TySize *= CUI->getValue(); // Get total allocated size. 153 StaticAllocaMap[AI] = 154 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align); 155 } 156 157 for (; BB != E; ++BB) 158 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I) 159 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I)) 160 if (!isa<AllocaInst>(I) || 161 !StaticAllocaMap.count(cast<AllocaInst>(I))) 162 InitializeRegForValue(I); 163 164 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This 165 // also creates the initial PHI MachineInstrs, though none of the input 166 // operands are populated. 167 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 168 MachineBasicBlock *MBB = new MachineBasicBlock(BB); 169 MBBMap[BB] = MBB; 170 MF.getBasicBlockList().push_back(MBB); 171 172 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as 173 // appropriate. 174 PHINode *PN; 175 for (BasicBlock::iterator I = BB->begin(); 176 (PN = dyn_cast<PHINode>(I)); ++I) 177 if (!PN->use_empty()) { 178 unsigned NumElements = 179 TLI.getNumElements(TLI.getValueType(PN->getType())); 180 unsigned PHIReg = ValueMap[PN]; 181 assert(PHIReg &&"PHI node does not have an assigned virtual register!"); 182 for (unsigned i = 0; i != NumElements; ++i) 183 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i); 184 } 185 } 186} 187 188 189 190//===----------------------------------------------------------------------===// 191/// SelectionDAGLowering - This is the common target-independent lowering 192/// implementation that is parameterized by a TargetLowering object. 193/// Also, targets can overload any lowering method. 194/// 195namespace llvm { 196class SelectionDAGLowering { 197 MachineBasicBlock *CurMBB; 198 199 std::map<const Value*, SDOperand> NodeMap; 200 201 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 202 /// them up and then emit token factor nodes when possible. This allows us to 203 /// get simple disambiguation between loads without worrying about alias 204 /// analysis. 205 std::vector<SDOperand> PendingLoads; 206 207public: 208 // TLI - This is information that describes the available target features we 209 // need for lowering. This indicates when operations are unavailable, 210 // implemented with a libcall, etc. 211 TargetLowering &TLI; 212 SelectionDAG &DAG; 213 const TargetData &TD; 214 215 /// FuncInfo - Information about the function as a whole. 216 /// 217 FunctionLoweringInfo &FuncInfo; 218 219 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli, 220 FunctionLoweringInfo &funcinfo) 221 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), 222 FuncInfo(funcinfo) { 223 } 224 225 /// getRoot - Return the current virtual root of the Selection DAG. 226 /// 227 SDOperand getRoot() { 228 if (PendingLoads.empty()) 229 return DAG.getRoot(); 230 231 if (PendingLoads.size() == 1) { 232 SDOperand Root = PendingLoads[0]; 233 DAG.setRoot(Root); 234 PendingLoads.clear(); 235 return Root; 236 } 237 238 // Otherwise, we have to make a token factor node. 239 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads); 240 PendingLoads.clear(); 241 DAG.setRoot(Root); 242 return Root; 243 } 244 245 void visit(Instruction &I) { visit(I.getOpcode(), I); } 246 247 void visit(unsigned Opcode, User &I) { 248 switch (Opcode) { 249 default: assert(0 && "Unknown instruction type encountered!"); 250 abort(); 251 // Build the switch statement using the Instruction.def file. 252#define HANDLE_INST(NUM, OPCODE, CLASS) \ 253 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I); 254#include "llvm/Instruction.def" 255 } 256 } 257 258 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; } 259 260 261 SDOperand getIntPtrConstant(uint64_t Val) { 262 return DAG.getConstant(Val, TLI.getPointerTy()); 263 } 264 265 SDOperand getValue(const Value *V) { 266 SDOperand &N = NodeMap[V]; 267 if (N.Val) return N; 268 269 MVT::ValueType VT = TLI.getValueType(V->getType()); 270 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) 271 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 272 visit(CE->getOpcode(), *CE); 273 assert(N.Val && "visit didn't populate the ValueMap!"); 274 return N; 275 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) { 276 return N = DAG.getGlobalAddress(GV, VT); 277 } else if (isa<ConstantPointerNull>(C)) { 278 return N = DAG.getConstant(0, TLI.getPointerTy()); 279 } else if (isa<UndefValue>(C)) { 280 return N = DAG.getNode(ISD::UNDEF, VT); 281 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 282 return N = DAG.getConstantFP(CFP->getValue(), VT); 283 } else { 284 // Canonicalize all constant ints to be unsigned. 285 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT); 286 } 287 288 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 289 std::map<const AllocaInst*, int>::iterator SI = 290 FuncInfo.StaticAllocaMap.find(AI); 291 if (SI != FuncInfo.StaticAllocaMap.end()) 292 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 293 } 294 295 std::map<const Value*, unsigned>::const_iterator VMI = 296 FuncInfo.ValueMap.find(V); 297 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!"); 298 299 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode()); 300 } 301 302 const SDOperand &setValue(const Value *V, SDOperand NewN) { 303 SDOperand &N = NodeMap[V]; 304 assert(N.Val == 0 && "Already set a value for this node!"); 305 return N = NewN; 306 } 307 308 // Terminator instructions. 309 void visitRet(ReturnInst &I); 310 void visitBr(BranchInst &I); 311 void visitUnreachable(UnreachableInst &I) { /* noop */ } 312 313 // These all get lowered before this pass. 314 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); } 315 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); } 316 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); } 317 318 // 319 void visitBinary(User &I, unsigned Opcode); 320 void visitAdd(User &I) { visitBinary(I, ISD::ADD); } 321 void visitSub(User &I); 322 void visitMul(User &I) { visitBinary(I, ISD::MUL); } 323 void visitDiv(User &I) { 324 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV); 325 } 326 void visitRem(User &I) { 327 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM); 328 } 329 void visitAnd(User &I) { visitBinary(I, ISD::AND); } 330 void visitOr (User &I) { visitBinary(I, ISD::OR); } 331 void visitXor(User &I) { visitBinary(I, ISD::XOR); } 332 void visitShl(User &I) { visitBinary(I, ISD::SHL); } 333 void visitShr(User &I) { 334 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA); 335 } 336 337 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc); 338 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); } 339 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); } 340 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); } 341 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); } 342 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); } 343 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); } 344 345 void visitGetElementPtr(User &I); 346 void visitCast(User &I); 347 void visitSelect(User &I); 348 // 349 350 void visitMalloc(MallocInst &I); 351 void visitFree(FreeInst &I); 352 void visitAlloca(AllocaInst &I); 353 void visitLoad(LoadInst &I); 354 void visitStore(StoreInst &I); 355 void visitPHI(PHINode &I) { } // PHI nodes are handled specially. 356 void visitCall(CallInst &I); 357 358 void visitVAStart(CallInst &I); 359 void visitVAArg(VAArgInst &I); 360 void visitVAEnd(CallInst &I); 361 void visitVACopy(CallInst &I); 362 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress); 363 364 void visitMemIntrinsic(CallInst &I, unsigned Op); 365 366 void visitUserOp1(Instruction &I) { 367 assert(0 && "UserOp1 should not exist at instruction selection time!"); 368 abort(); 369 } 370 void visitUserOp2(Instruction &I) { 371 assert(0 && "UserOp2 should not exist at instruction selection time!"); 372 abort(); 373 } 374}; 375} // end namespace llvm 376 377void SelectionDAGLowering::visitRet(ReturnInst &I) { 378 if (I.getNumOperands() == 0) { 379 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot())); 380 return; 381 } 382 383 SDOperand Op1 = getValue(I.getOperand(0)); 384 MVT::ValueType TmpVT; 385 386 switch (Op1.getValueType()) { 387 default: assert(0 && "Unknown value type!"); 388 case MVT::i1: 389 case MVT::i8: 390 case MVT::i16: 391 case MVT::i32: 392 // If this is a machine where 32-bits is legal or expanded, promote to 393 // 32-bits, otherwise, promote to 64-bits. 394 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote) 395 TmpVT = TLI.getTypeToTransformTo(MVT::i32); 396 else 397 TmpVT = MVT::i32; 398 399 // Extend integer types to result type. 400 if (I.getOperand(0)->getType()->isSigned()) 401 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1); 402 else 403 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1); 404 break; 405 case MVT::f32: 406 case MVT::i64: 407 case MVT::f64: 408 break; // No extension needed! 409 } 410 411 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1)); 412} 413 414void SelectionDAGLowering::visitBr(BranchInst &I) { 415 // Update machine-CFG edges. 416 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 417 418 // Figure out which block is immediately after the current one. 419 MachineBasicBlock *NextBlock = 0; 420 MachineFunction::iterator BBI = CurMBB; 421 if (++BBI != CurMBB->getParent()->end()) 422 NextBlock = BBI; 423 424 if (I.isUnconditional()) { 425 // If this is not a fall-through branch, emit the branch. 426 if (Succ0MBB != NextBlock) 427 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(), 428 DAG.getBasicBlock(Succ0MBB))); 429 } else { 430 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 431 432 SDOperand Cond = getValue(I.getCondition()); 433 if (Succ1MBB == NextBlock) { 434 // If the condition is false, fall through. This means we should branch 435 // if the condition is true to Succ #0. 436 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), 437 Cond, DAG.getBasicBlock(Succ0MBB))); 438 } else if (Succ0MBB == NextBlock) { 439 // If the condition is true, fall through. This means we should branch if 440 // the condition is false to Succ #1. Invert the condition first. 441 SDOperand True = DAG.getConstant(1, Cond.getValueType()); 442 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True); 443 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), 444 Cond, DAG.getBasicBlock(Succ1MBB))); 445 } else { 446 std::vector<SDOperand> Ops; 447 Ops.push_back(getRoot()); 448 Ops.push_back(Cond); 449 Ops.push_back(DAG.getBasicBlock(Succ0MBB)); 450 Ops.push_back(DAG.getBasicBlock(Succ1MBB)); 451 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops)); 452 } 453 } 454} 455 456void SelectionDAGLowering::visitSub(User &I) { 457 // -0.0 - X --> fneg 458 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 459 if (CFP->isExactlyValue(-0.0)) { 460 SDOperand Op2 = getValue(I.getOperand(1)); 461 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2)); 462 return; 463 } 464 465 visitBinary(I, ISD::SUB); 466} 467 468void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) { 469 SDOperand Op1 = getValue(I.getOperand(0)); 470 SDOperand Op2 = getValue(I.getOperand(1)); 471 472 if (isa<ShiftInst>(I)) 473 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2); 474 475 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2)); 476} 477 478void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode, 479 ISD::CondCode UnsignedOpcode) { 480 SDOperand Op1 = getValue(I.getOperand(0)); 481 SDOperand Op2 = getValue(I.getOperand(1)); 482 ISD::CondCode Opcode = SignedOpcode; 483 if (I.getOperand(0)->getType()->isUnsigned()) 484 Opcode = UnsignedOpcode; 485 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode)); 486} 487 488void SelectionDAGLowering::visitSelect(User &I) { 489 SDOperand Cond = getValue(I.getOperand(0)); 490 SDOperand TrueVal = getValue(I.getOperand(1)); 491 SDOperand FalseVal = getValue(I.getOperand(2)); 492 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond, 493 TrueVal, FalseVal)); 494} 495 496void SelectionDAGLowering::visitCast(User &I) { 497 SDOperand N = getValue(I.getOperand(0)); 498 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType()); 499 MVT::ValueType DestTy = TLI.getValueType(I.getType()); 500 501 if (N.getValueType() == DestTy) { 502 setValue(&I, N); // noop cast. 503 } else if (DestTy == MVT::i1) { 504 // Cast to bool is a comparison against zero, not truncation to zero. 505 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) : 506 DAG.getConstantFP(0.0, N.getValueType()); 507 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE)); 508 } else if (isInteger(SrcTy)) { 509 if (isInteger(DestTy)) { // Int -> Int cast 510 if (DestTy < SrcTy) // Truncating cast? 511 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N)); 512 else if (I.getOperand(0)->getType()->isSigned()) 513 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N)); 514 else 515 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N)); 516 } else { // Int -> FP cast 517 if (I.getOperand(0)->getType()->isSigned()) 518 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N)); 519 else 520 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N)); 521 } 522 } else { 523 assert(isFloatingPoint(SrcTy) && "Unknown value type!"); 524 if (isFloatingPoint(DestTy)) { // FP -> FP cast 525 if (DestTy < SrcTy) // Rounding cast? 526 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N)); 527 else 528 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N)); 529 } else { // FP -> Int cast. 530 if (I.getType()->isSigned()) 531 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N)); 532 else 533 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N)); 534 } 535 } 536} 537 538void SelectionDAGLowering::visitGetElementPtr(User &I) { 539 SDOperand N = getValue(I.getOperand(0)); 540 const Type *Ty = I.getOperand(0)->getType(); 541 const Type *UIntPtrTy = TD.getIntPtrType(); 542 543 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 544 OI != E; ++OI) { 545 Value *Idx = *OI; 546 if (const StructType *StTy = dyn_cast<StructType> (Ty)) { 547 unsigned Field = cast<ConstantUInt>(Idx)->getValue(); 548 if (Field) { 549 // N = N + Offset 550 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field]; 551 N = DAG.getNode(ISD::ADD, N.getValueType(), N, 552 getIntPtrConstant(Offset)); 553 } 554 Ty = StTy->getElementType(Field); 555 } else { 556 Ty = cast<SequentialType>(Ty)->getElementType(); 557 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) { 558 // N = N + Idx * ElementSize; 559 uint64_t ElementSize = TD.getTypeSize(Ty); 560 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize); 561 562 // If the index is smaller or larger than intptr_t, truncate or extend 563 // it. 564 if (IdxN.getValueType() < Scale.getValueType()) { 565 if (Idx->getType()->isSigned()) 566 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN); 567 else 568 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN); 569 } else if (IdxN.getValueType() > Scale.getValueType()) 570 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN); 571 572 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale); 573 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 574 } 575 } 576 } 577 setValue(&I, N); 578} 579 580void SelectionDAGLowering::visitAlloca(AllocaInst &I) { 581 // If this is a fixed sized alloca in the entry block of the function, 582 // allocate it statically on the stack. 583 if (FuncInfo.StaticAllocaMap.count(&I)) 584 return; // getValue will auto-populate this. 585 586 const Type *Ty = I.getAllocatedType(); 587 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty); 588 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty); 589 590 SDOperand AllocSize = getValue(I.getArraySize()); 591 MVT::ValueType IntPtr = TLI.getPointerTy(); 592 if (IntPtr < AllocSize.getValueType()) 593 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize); 594 else if (IntPtr > AllocSize.getValueType()) 595 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize); 596 597 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize, 598 getIntPtrConstant(TySize)); 599 600 // Handle alignment. If the requested alignment is less than or equal to the 601 // stack alignment, ignore it and round the size of the allocation up to the 602 // stack alignment size. If the size is greater than the stack alignment, we 603 // note this in the DYNAMIC_STACKALLOC node. 604 unsigned StackAlign = 605 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 606 if (Align <= StackAlign) { 607 Align = 0; 608 // Add SA-1 to the size. 609 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize, 610 getIntPtrConstant(StackAlign-1)); 611 // Mask out the low bits for alignment purposes. 612 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize, 613 getIntPtrConstant(~(uint64_t)(StackAlign-1))); 614 } 615 616 std::vector<MVT::ValueType> VTs; 617 VTs.push_back(AllocSize.getValueType()); 618 VTs.push_back(MVT::Other); 619 std::vector<SDOperand> Ops; 620 Ops.push_back(getRoot()); 621 Ops.push_back(AllocSize); 622 Ops.push_back(getIntPtrConstant(Align)); 623 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops); 624 DAG.setRoot(setValue(&I, DSA).getValue(1)); 625 626 // Inform the Frame Information that we have just allocated a variable-sized 627 // object. 628 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject(); 629} 630 631 632void SelectionDAGLowering::visitLoad(LoadInst &I) { 633 SDOperand Ptr = getValue(I.getOperand(0)); 634 635 SDOperand Root; 636 if (I.isVolatile()) 637 Root = getRoot(); 638 else { 639 // Do not serialize non-volatile loads against each other. 640 Root = DAG.getRoot(); 641 } 642 643 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr, 644 DAG.getSrcValue(I.getOperand(0))); 645 setValue(&I, L); 646 647 if (I.isVolatile()) 648 DAG.setRoot(L.getValue(1)); 649 else 650 PendingLoads.push_back(L.getValue(1)); 651} 652 653 654void SelectionDAGLowering::visitStore(StoreInst &I) { 655 Value *SrcV = I.getOperand(0); 656 SDOperand Src = getValue(SrcV); 657 SDOperand Ptr = getValue(I.getOperand(1)); 658 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr, 659 DAG.getSrcValue(I.getOperand(1)))); 660} 661 662void SelectionDAGLowering::visitCall(CallInst &I) { 663 const char *RenameFn = 0; 664 SDOperand Tmp; 665 if (Function *F = I.getCalledFunction()) 666 if (F->isExternal()) 667 switch (F->getIntrinsicID()) { 668 case 0: // Not an LLVM intrinsic. 669 if (F->getName() == "fabs" || F->getName() == "fabsf") { 670 if (I.getNumOperands() == 2 && // Basic sanity checks. 671 I.getOperand(1)->getType()->isFloatingPoint() && 672 I.getType() == I.getOperand(1)->getType()) { 673 Tmp = getValue(I.getOperand(1)); 674 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp)); 675 return; 676 } 677 } 678 else if (F->getName() == "sin" || F->getName() == "sinf") { 679 if (I.getNumOperands() == 2 && // Basic sanity checks. 680 I.getOperand(1)->getType()->isFloatingPoint() && 681 I.getType() == I.getOperand(1)->getType()) { 682 Tmp = getValue(I.getOperand(1)); 683 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp)); 684 return; 685 } 686 } 687 else if (F->getName() == "cos" || F->getName() == "cosf") { 688 if (I.getNumOperands() == 2 && // Basic sanity checks. 689 I.getOperand(1)->getType()->isFloatingPoint() && 690 I.getType() == I.getOperand(1)->getType()) { 691 Tmp = getValue(I.getOperand(1)); 692 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp)); 693 return; 694 } 695 } 696 break; 697 case Intrinsic::vastart: visitVAStart(I); return; 698 case Intrinsic::vaend: visitVAEnd(I); return; 699 case Intrinsic::vacopy: visitVACopy(I); return; 700 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return; 701 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return; 702 703 case Intrinsic::setjmp: RenameFn = "setjmp"; break; 704 case Intrinsic::longjmp: RenameFn = "longjmp"; break; 705 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return; 706 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return; 707 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return; 708 709 case Intrinsic::readport: 710 case Intrinsic::readio: { 711 std::vector<MVT::ValueType> VTs; 712 VTs.push_back(TLI.getValueType(I.getType())); 713 VTs.push_back(MVT::Other); 714 std::vector<SDOperand> Ops; 715 Ops.push_back(getRoot()); 716 Ops.push_back(getValue(I.getOperand(1))); 717 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ? 718 ISD::READPORT : ISD::READIO, VTs, Ops); 719 720 setValue(&I, Tmp); 721 DAG.setRoot(Tmp.getValue(1)); 722 return; 723 } 724 case Intrinsic::writeport: 725 case Intrinsic::writeio: 726 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ? 727 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other, 728 getRoot(), getValue(I.getOperand(1)), 729 getValue(I.getOperand(2)))); 730 return; 731 case Intrinsic::dbg_stoppoint: 732 case Intrinsic::dbg_region_start: 733 case Intrinsic::dbg_region_end: 734 case Intrinsic::dbg_func_start: 735 case Intrinsic::dbg_declare: 736 if (I.getType() != Type::VoidTy) 737 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()))); 738 return; 739 740 case Intrinsic::isunordered: 741 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)), 742 getValue(I.getOperand(2)), ISD::SETUO)); 743 return; 744 745 case Intrinsic::sqrt: 746 setValue(&I, DAG.getNode(ISD::FSQRT, 747 getValue(I.getOperand(1)).getValueType(), 748 getValue(I.getOperand(1)))); 749 return; 750 751 case Intrinsic::pcmarker: 752 Tmp = getValue(I.getOperand(1)); 753 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp)); 754 return; 755 case Intrinsic::cttz: 756 setValue(&I, DAG.getNode(ISD::CTTZ, 757 getValue(I.getOperand(1)).getValueType(), 758 getValue(I.getOperand(1)))); 759 return; 760 case Intrinsic::ctlz: 761 setValue(&I, DAG.getNode(ISD::CTLZ, 762 getValue(I.getOperand(1)).getValueType(), 763 getValue(I.getOperand(1)))); 764 return; 765 case Intrinsic::ctpop: 766 setValue(&I, DAG.getNode(ISD::CTPOP, 767 getValue(I.getOperand(1)).getValueType(), 768 getValue(I.getOperand(1)))); 769 return; 770 default: 771 std::cerr << I; 772 assert(0 && "This intrinsic is not implemented yet!"); 773 return; 774 } 775 776 SDOperand Callee; 777 if (!RenameFn) 778 Callee = getValue(I.getOperand(0)); 779 else 780 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 781 std::vector<std::pair<SDOperand, const Type*> > Args; 782 783 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 784 Value *Arg = I.getOperand(i); 785 SDOperand ArgNode = getValue(Arg); 786 Args.push_back(std::make_pair(ArgNode, Arg->getType())); 787 } 788 789 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType()); 790 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 791 792 std::pair<SDOperand,SDOperand> Result = 793 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(), 794 I.isTailCall(), Callee, Args, DAG); 795 if (I.getType() != Type::VoidTy) 796 setValue(&I, Result.first); 797 DAG.setRoot(Result.second); 798} 799 800void SelectionDAGLowering::visitMalloc(MallocInst &I) { 801 SDOperand Src = getValue(I.getOperand(0)); 802 803 MVT::ValueType IntPtr = TLI.getPointerTy(); 804 805 if (IntPtr < Src.getValueType()) 806 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src); 807 else if (IntPtr > Src.getValueType()) 808 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src); 809 810 // Scale the source by the type size. 811 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType()); 812 Src = DAG.getNode(ISD::MUL, Src.getValueType(), 813 Src, getIntPtrConstant(ElementSize)); 814 815 std::vector<std::pair<SDOperand, const Type*> > Args; 816 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType())); 817 818 std::pair<SDOperand,SDOperand> Result = 819 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true, 820 DAG.getExternalSymbol("malloc", IntPtr), 821 Args, DAG); 822 setValue(&I, Result.first); // Pointers always fit in registers 823 DAG.setRoot(Result.second); 824} 825 826void SelectionDAGLowering::visitFree(FreeInst &I) { 827 std::vector<std::pair<SDOperand, const Type*> > Args; 828 Args.push_back(std::make_pair(getValue(I.getOperand(0)), 829 TLI.getTargetData().getIntPtrType())); 830 MVT::ValueType IntPtr = TLI.getPointerTy(); 831 std::pair<SDOperand,SDOperand> Result = 832 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true, 833 DAG.getExternalSymbol("free", IntPtr), Args, DAG); 834 DAG.setRoot(Result.second); 835} 836 837SDOperand TargetLowering::LowerVAStart(SDOperand Chain, 838 SDOperand VAListP, Value *VAListV, 839 SelectionDAG &DAG) { 840 // We have no sane default behavior, just emit a useful error message and bail 841 // out. 842 std::cerr << "Variable arguments handling not implemented on this target!\n"; 843 abort(); 844 return SDOperand(); 845} 846 847SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV, 848 SelectionDAG &DAG) { 849 // Default to a noop. 850 return Chain; 851} 852 853SDOperand TargetLowering::LowerVACopy(SDOperand Chain, 854 SDOperand SrcP, Value *SrcV, 855 SDOperand DestP, Value *DestV, 856 SelectionDAG &DAG) { 857 // Default to copying the input list. 858 SDOperand Val = DAG.getLoad(getPointerTy(), Chain, 859 SrcP, DAG.getSrcValue(SrcV)); 860 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1), 861 Val, DestP, DAG.getSrcValue(DestV)); 862 return Result; 863} 864 865std::pair<SDOperand,SDOperand> 866TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV, 867 const Type *ArgTy, SelectionDAG &DAG) { 868 // We have no sane default behavior, just emit a useful error message and bail 869 // out. 870 std::cerr << "Variable arguments handling not implemented on this target!\n"; 871 abort(); 872 return std::make_pair(SDOperand(), SDOperand()); 873} 874 875 876void SelectionDAGLowering::visitVAStart(CallInst &I) { 877 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)), 878 I.getOperand(1), DAG)); 879} 880 881void SelectionDAGLowering::visitVAArg(VAArgInst &I) { 882 std::pair<SDOperand,SDOperand> Result = 883 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0), 884 I.getType(), DAG); 885 setValue(&I, Result.first); 886 DAG.setRoot(Result.second); 887} 888 889void SelectionDAGLowering::visitVAEnd(CallInst &I) { 890 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), 891 I.getOperand(1), DAG)); 892} 893 894void SelectionDAGLowering::visitVACopy(CallInst &I) { 895 SDOperand Result = 896 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2), 897 getValue(I.getOperand(1)), I.getOperand(1), DAG); 898 DAG.setRoot(Result); 899} 900 901 902// It is always conservatively correct for llvm.returnaddress and 903// llvm.frameaddress to return 0. 904std::pair<SDOperand, SDOperand> 905TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, 906 unsigned Depth, SelectionDAG &DAG) { 907 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain); 908} 909 910SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) { 911 assert(0 && "LowerOperation not implemented for this target!"); 912 abort(); 913 return SDOperand(); 914} 915 916void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) { 917 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue(); 918 std::pair<SDOperand,SDOperand> Result = 919 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG); 920 setValue(&I, Result.first); 921 DAG.setRoot(Result.second); 922} 923 924void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) { 925 std::vector<SDOperand> Ops; 926 Ops.push_back(getRoot()); 927 Ops.push_back(getValue(I.getOperand(1))); 928 Ops.push_back(getValue(I.getOperand(2))); 929 Ops.push_back(getValue(I.getOperand(3))); 930 Ops.push_back(getValue(I.getOperand(4))); 931 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops)); 932} 933 934//===----------------------------------------------------------------------===// 935// SelectionDAGISel code 936//===----------------------------------------------------------------------===// 937 938unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) { 939 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 940} 941 942 943 944bool SelectionDAGISel::runOnFunction(Function &Fn) { 945 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine()); 946 RegMap = MF.getSSARegMap(); 947 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n"); 948 949 FunctionLoweringInfo FuncInfo(TLI, Fn, MF); 950 951 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 952 SelectBasicBlock(I, MF, FuncInfo); 953 954 return true; 955} 956 957 958SDOperand SelectionDAGISel:: 959CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) { 960 SelectionDAG &DAG = SDL.DAG; 961 SDOperand Op = SDL.getValue(V); 962 assert((Op.getOpcode() != ISD::CopyFromReg || 963 cast<RegSDNode>(Op)->getReg() != Reg) && 964 "Copy from a reg to the same reg!"); 965 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg); 966} 967 968/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a 969/// single basic block, return that block. Otherwise, return a null pointer. 970static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) { 971 if (A->use_empty()) return 0; 972 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent(); 973 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; 974 ++UI) 975 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB) 976 return 0; // Disagreement among the users? 977 978 // Okay, there is a single BB user. Only permit this optimization if this is 979 // the entry block, otherwise, we might sink argument loads into loops and 980 // stuff. Later, when we have global instruction selection, this won't be an 981 // issue clearly. 982 if (BB == BB->getParent()->begin()) 983 return BB; 984 return 0; 985} 986 987void SelectionDAGISel:: 988LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL, 989 std::vector<SDOperand> &UnorderedChains) { 990 // If this is the entry block, emit arguments. 991 Function &F = *BB->getParent(); 992 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo; 993 994 if (BB == &F.front()) { 995 SDOperand OldRoot = SDL.DAG.getRoot(); 996 997 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG); 998 999 // If there were side effects accessing the argument list, do not do 1000 // anything special. 1001 if (OldRoot != SDL.DAG.getRoot()) { 1002 unsigned a = 0; 1003 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 1004 AI != E; ++AI,++a) 1005 if (!AI->use_empty()) { 1006 SDL.setValue(AI, Args[a]); 1007 SDOperand Copy = 1008 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]); 1009 UnorderedChains.push_back(Copy); 1010 } 1011 } else { 1012 // Otherwise, if any argument is only accessed in a single basic block, 1013 // emit that argument only to that basic block. 1014 unsigned a = 0; 1015 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 1016 AI != E; ++AI,++a) 1017 if (!AI->use_empty()) { 1018 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) { 1019 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU, 1020 std::make_pair(AI, a))); 1021 } else { 1022 SDL.setValue(AI, Args[a]); 1023 SDOperand Copy = 1024 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]); 1025 UnorderedChains.push_back(Copy); 1026 } 1027 } 1028 } 1029 1030 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction()); 1031 } 1032 1033 // See if there are any block-local arguments that need to be emitted in this 1034 // block. 1035 1036 if (!FuncInfo.BlockLocalArguments.empty()) { 1037 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI = 1038 FuncInfo.BlockLocalArguments.lower_bound(BB); 1039 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) { 1040 // Lower the arguments into this block. 1041 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG); 1042 1043 // Set up the value mapping for the local arguments. 1044 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB; 1045 ++BLAI) 1046 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]); 1047 1048 // Any dead arguments will just be ignored here. 1049 } 1050 } 1051} 1052 1053 1054void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB, 1055 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate, 1056 FunctionLoweringInfo &FuncInfo) { 1057 SelectionDAGLowering SDL(DAG, TLI, FuncInfo); 1058 1059 std::vector<SDOperand> UnorderedChains; 1060 1061 // Lower any arguments needed in this block. 1062 LowerArguments(LLVMBB, SDL, UnorderedChains); 1063 1064 BB = FuncInfo.MBBMap[LLVMBB]; 1065 SDL.setCurrentBasicBlock(BB); 1066 1067 // Lower all of the non-terminator instructions. 1068 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end(); 1069 I != E; ++I) 1070 SDL.visit(*I); 1071 1072 // Ensure that all instructions which are used outside of their defining 1073 // blocks are available as virtual registers. 1074 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I) 1075 if (!I->use_empty() && !isa<PHINode>(I)) { 1076 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I); 1077 if (VMI != FuncInfo.ValueMap.end()) 1078 UnorderedChains.push_back( 1079 CopyValueToVirtualRegister(SDL, I, VMI->second)); 1080 } 1081 1082 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 1083 // ensure constants are generated when needed. Remember the virtual registers 1084 // that need to be added to the Machine PHI nodes as input. We cannot just 1085 // directly add them, because expansion might result in multiple MBB's for one 1086 // BB. As such, the start of the BB might correspond to a different MBB than 1087 // the end. 1088 // 1089 1090 // Emit constants only once even if used by multiple PHI nodes. 1091 std::map<Constant*, unsigned> ConstantsOut; 1092 1093 // Check successor nodes PHI nodes that expect a constant to be available from 1094 // this block. 1095 TerminatorInst *TI = LLVMBB->getTerminator(); 1096 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 1097 BasicBlock *SuccBB = TI->getSuccessor(succ); 1098 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin(); 1099 PHINode *PN; 1100 1101 // At this point we know that there is a 1-1 correspondence between LLVM PHI 1102 // nodes and Machine PHI nodes, but the incoming operands have not been 1103 // emitted yet. 1104 for (BasicBlock::iterator I = SuccBB->begin(); 1105 (PN = dyn_cast<PHINode>(I)); ++I) 1106 if (!PN->use_empty()) { 1107 unsigned Reg; 1108 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 1109 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 1110 unsigned &RegOut = ConstantsOut[C]; 1111 if (RegOut == 0) { 1112 RegOut = FuncInfo.CreateRegForValue(C); 1113 UnorderedChains.push_back( 1114 CopyValueToVirtualRegister(SDL, C, RegOut)); 1115 } 1116 Reg = RegOut; 1117 } else { 1118 Reg = FuncInfo.ValueMap[PHIOp]; 1119 if (Reg == 0) { 1120 assert(isa<AllocaInst>(PHIOp) && 1121 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 1122 "Didn't codegen value into a register!??"); 1123 Reg = FuncInfo.CreateRegForValue(PHIOp); 1124 UnorderedChains.push_back( 1125 CopyValueToVirtualRegister(SDL, PHIOp, Reg)); 1126 } 1127 } 1128 1129 // Remember that this register needs to added to the machine PHI node as 1130 // the input for this MBB. 1131 unsigned NumElements = 1132 TLI.getNumElements(TLI.getValueType(PN->getType())); 1133 for (unsigned i = 0, e = NumElements; i != e; ++i) 1134 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 1135 } 1136 } 1137 ConstantsOut.clear(); 1138 1139 // Turn all of the unordered chains into one factored node. 1140 if (!UnorderedChains.empty()) { 1141 UnorderedChains.push_back(SDL.getRoot()); 1142 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains)); 1143 } 1144 1145 // Lower the terminator after the copies are emitted. 1146 SDL.visit(*LLVMBB->getTerminator()); 1147 1148 // Make sure the root of the DAG is up-to-date. 1149 DAG.setRoot(SDL.getRoot()); 1150} 1151 1152void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF, 1153 FunctionLoweringInfo &FuncInfo) { 1154 SelectionDAG DAG(TLI, MF); 1155 CurDAG = &DAG; 1156 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate; 1157 1158 // First step, lower LLVM code to some DAG. This DAG may use operations and 1159 // types that are not supported by the target. 1160 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo); 1161 1162 DEBUG(std::cerr << "Lowered selection DAG:\n"); 1163 DEBUG(DAG.dump()); 1164 1165 // Second step, hack on the DAG until it only uses operations and types that 1166 // the target supports. 1167 DAG.Legalize(); 1168 1169 DEBUG(std::cerr << "Legalized selection DAG:\n"); 1170 DEBUG(DAG.dump()); 1171 1172 // Third, instruction select all of the operations to machine code, adding the 1173 // code to the MachineBasicBlock. 1174 InstructionSelectBasicBlock(DAG); 1175 1176 if (ViewDAGs) DAG.viewGraph(); 1177 1178 DEBUG(std::cerr << "Selected machine code:\n"); 1179 DEBUG(BB->dump()); 1180 1181 // Next, now that we know what the last MBB the LLVM BB expanded is, update 1182 // PHI nodes in successors. 1183 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 1184 MachineInstr *PHI = PHINodesToUpdate[i].first; 1185 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 1186 "This is not a machine PHI node that we are updating!"); 1187 PHI->addRegOperand(PHINodesToUpdate[i].second); 1188 PHI->addMachineBasicBlockOperand(BB); 1189 } 1190 1191 // Finally, add the CFG edges from the last selected MBB to the successor 1192 // MBBs. 1193 TerminatorInst *TI = LLVMBB->getTerminator(); 1194 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1195 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)]; 1196 BB->addSuccessor(Succ0MBB); 1197 } 1198} 1199