SelectionDAGISel.cpp revision 51eaa86758338d5935c0eff0469c418b1256aba7
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/ADT/BitVector.h" 16#include "llvm/Analysis/AliasAnalysis.h" 17#include "llvm/CodeGen/SelectionDAGISel.h" 18#include "llvm/CodeGen/ScheduleDAG.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/ParameterAttributes.h" 29#include "llvm/CodeGen/MachineModuleInfo.h" 30#include "llvm/CodeGen/MachineFunction.h" 31#include "llvm/CodeGen/MachineFrameInfo.h" 32#include "llvm/CodeGen/MachineJumpTableInfo.h" 33#include "llvm/CodeGen/MachineInstrBuilder.h" 34#include "llvm/CodeGen/SchedulerRegistry.h" 35#include "llvm/CodeGen/SelectionDAG.h" 36#include "llvm/CodeGen/SSARegMap.h" 37#include "llvm/Target/MRegisterInfo.h" 38#include "llvm/Target/TargetData.h" 39#include "llvm/Target/TargetFrameInfo.h" 40#include "llvm/Target/TargetInstrInfo.h" 41#include "llvm/Target/TargetLowering.h" 42#include "llvm/Target/TargetMachine.h" 43#include "llvm/Target/TargetOptions.h" 44#include "llvm/Support/MathExtras.h" 45#include "llvm/Support/Debug.h" 46#include "llvm/Support/Compiler.h" 47#include <algorithm> 48using namespace llvm; 49 50#ifndef NDEBUG 51static cl::opt<bool> 52ViewISelDAGs("view-isel-dags", cl::Hidden, 53 cl::desc("Pop up a window to show isel dags as they are selected")); 54static cl::opt<bool> 55ViewSchedDAGs("view-sched-dags", cl::Hidden, 56 cl::desc("Pop up a window to show sched dags as they are processed")); 57#else 58static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0; 59#endif 60 61//===---------------------------------------------------------------------===// 62/// 63/// RegisterScheduler class - Track the registration of instruction schedulers. 64/// 65//===---------------------------------------------------------------------===// 66MachinePassRegistry RegisterScheduler::Registry; 67 68//===---------------------------------------------------------------------===// 69/// 70/// ISHeuristic command line option for instruction schedulers. 71/// 72//===---------------------------------------------------------------------===// 73namespace { 74 cl::opt<RegisterScheduler::FunctionPassCtor, false, 75 RegisterPassParser<RegisterScheduler> > 76 ISHeuristic("sched", 77 cl::init(&createDefaultScheduler), 78 cl::desc("Instruction schedulers available:")); 79 80 static RegisterScheduler 81 defaultListDAGScheduler("default", " Best scheduler for the target", 82 createDefaultScheduler); 83} // namespace 84 85namespace { struct AsmOperandInfo; } 86 87namespace { 88 /// RegsForValue - This struct represents the physical registers that a 89 /// particular value is assigned and the type information about the value. 90 /// This is needed because values can be promoted into larger registers and 91 /// expanded into multiple smaller registers than the value. 92 struct VISIBILITY_HIDDEN RegsForValue { 93 /// Regs - This list hold the register (for legal and promoted values) 94 /// or register set (for expanded values) that the value should be assigned 95 /// to. 96 std::vector<unsigned> Regs; 97 98 /// RegVT - The value type of each register. 99 /// 100 MVT::ValueType RegVT; 101 102 /// ValueVT - The value type of the LLVM value, which may be promoted from 103 /// RegVT or made from merging the two expanded parts. 104 MVT::ValueType ValueVT; 105 106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {} 107 108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt) 109 : RegVT(regvt), ValueVT(valuevt) { 110 Regs.push_back(Reg); 111 } 112 RegsForValue(const std::vector<unsigned> ®s, 113 MVT::ValueType regvt, MVT::ValueType valuevt) 114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) { 115 } 116 117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 118 /// this value and returns the result as a ValueVT value. This uses 119 /// Chain/Flag as the input and updates them for the output Chain/Flag. 120 SDOperand getCopyFromRegs(SelectionDAG &DAG, 121 SDOperand &Chain, SDOperand &Flag) const; 122 123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 124 /// specified value into the registers specified by this object. This uses 125 /// Chain/Flag as the input and updates them for the output Chain/Flag. 126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 127 SDOperand &Chain, SDOperand &Flag, 128 MVT::ValueType PtrVT) const; 129 130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 131 /// operand list. This adds the code marker and includes the number of 132 /// values added into it. 133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 134 std::vector<SDOperand> &Ops) const; 135 }; 136} 137 138namespace llvm { 139 //===--------------------------------------------------------------------===// 140 /// createDefaultScheduler - This creates an instruction scheduler appropriate 141 /// for the target. 142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS, 143 SelectionDAG *DAG, 144 MachineBasicBlock *BB) { 145 TargetLowering &TLI = IS->getTargetLowering(); 146 147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) { 148 return createTDListDAGScheduler(IS, DAG, BB); 149 } else { 150 assert(TLI.getSchedulingPreference() == 151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!"); 152 return createBURRListDAGScheduler(IS, DAG, BB); 153 } 154 } 155 156 157 //===--------------------------------------------------------------------===// 158 /// FunctionLoweringInfo - This contains information that is global to a 159 /// function that is used when lowering a region of the function. 160 class FunctionLoweringInfo { 161 public: 162 TargetLowering &TLI; 163 Function &Fn; 164 MachineFunction &MF; 165 SSARegMap *RegMap; 166 167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF); 168 169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry. 170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap; 171 172 /// ValueMap - Since we emit code for the function a basic block at a time, 173 /// we must remember which virtual registers hold the values for 174 /// cross-basic-block values. 175 DenseMap<const Value*, unsigned> ValueMap; 176 177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in 178 /// the entry block. This allows the allocas to be efficiently referenced 179 /// anywhere in the function. 180 std::map<const AllocaInst*, int> StaticAllocaMap; 181 182 unsigned MakeReg(MVT::ValueType VT) { 183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 184 } 185 186 /// isExportedInst - Return true if the specified value is an instruction 187 /// exported from its block. 188 bool isExportedInst(const Value *V) { 189 return ValueMap.count(V); 190 } 191 192 unsigned CreateRegForValue(const Value *V); 193 194 unsigned InitializeRegForValue(const Value *V) { 195 unsigned &R = ValueMap[V]; 196 assert(R == 0 && "Already initialized this value register!"); 197 return R = CreateRegForValue(V); 198 } 199 }; 200} 201 202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by 203/// PHI nodes or outside of the basic block that defines it, or used by a 204/// switch instruction, which may expand to multiple basic blocks. 205static bool isUsedOutsideOfDefiningBlock(Instruction *I) { 206 if (isa<PHINode>(I)) return true; 207 BasicBlock *BB = I->getParent(); 208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) 209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) || 210 // FIXME: Remove switchinst special case. 211 isa<SwitchInst>(*UI)) 212 return true; 213 return false; 214} 215 216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the 217/// entry block, return true. This includes arguments used by switches, since 218/// the switch may expand into multiple basic blocks. 219static bool isOnlyUsedInEntryBlock(Argument *A) { 220 BasicBlock *Entry = A->getParent()->begin(); 221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI) 222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI)) 223 return false; // Use not in entry block. 224 return true; 225} 226 227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli, 228 Function &fn, MachineFunction &mf) 229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) { 230 231 // Create a vreg for each argument register that is not dead and is used 232 // outside of the entry block for the function. 233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); 234 AI != E; ++AI) 235 if (!isOnlyUsedInEntryBlock(AI)) 236 InitializeRegForValue(AI); 237 238 // Initialize the mapping of values to registers. This is only set up for 239 // instruction values that are used outside of the block that defines 240 // them. 241 Function::iterator BB = Fn.begin(), EB = Fn.end(); 242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) { 245 const Type *Ty = AI->getAllocatedType(); 246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty); 247 unsigned Align = 248 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 249 AI->getAlignment()); 250 251 TySize *= CUI->getZExtValue(); // Get total allocated size. 252 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. 253 StaticAllocaMap[AI] = 254 MF.getFrameInfo()->CreateStackObject(TySize, Align); 255 } 256 257 for (; BB != EB; ++BB) 258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 259 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I)) 260 if (!isa<AllocaInst>(I) || 261 !StaticAllocaMap.count(cast<AllocaInst>(I))) 262 InitializeRegForValue(I); 263 264 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This 265 // also creates the initial PHI MachineInstrs, though none of the input 266 // operands are populated. 267 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) { 268 MachineBasicBlock *MBB = new MachineBasicBlock(BB); 269 MBBMap[BB] = MBB; 270 MF.getBasicBlockList().push_back(MBB); 271 272 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as 273 // appropriate. 274 PHINode *PN; 275 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){ 276 if (PN->use_empty()) continue; 277 278 MVT::ValueType VT = TLI.getValueType(PN->getType()); 279 unsigned NumElements; 280 if (VT != MVT::Vector) 281 NumElements = TLI.getNumElements(VT); 282 else { 283 MVT::ValueType VT1,VT2; 284 NumElements = 285 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()), 286 VT1, VT2); 287 } 288 unsigned PHIReg = ValueMap[PN]; 289 assert(PHIReg && "PHI node does not have an assigned virtual register!"); 290 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo(); 291 for (unsigned i = 0; i != NumElements; ++i) 292 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i); 293 } 294 } 295} 296 297/// CreateRegForValue - Allocate the appropriate number of virtual registers of 298/// the correctly promoted or expanded types. Assign these registers 299/// consecutive vreg numbers and return the first assigned number. 300unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) { 301 MVT::ValueType VT = TLI.getValueType(V->getType()); 302 303 // The number of multiples of registers that we need, to, e.g., split up 304 // a <2 x int64> -> 4 x i32 registers. 305 unsigned NumVectorRegs = 1; 306 307 // If this is a vector type, figure out what type it will decompose into 308 // and how many of the elements it will use. 309 if (VT == MVT::Vector) { 310 const VectorType *PTy = cast<VectorType>(V->getType()); 311 unsigned NumElts = PTy->getNumElements(); 312 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType()); 313 MVT::ValueType VecTy = MVT::getVectorType(EltTy, NumElts); 314 315 // Divide the input until we get to a supported size. This will always 316 // end with a scalar if the target doesn't support vectors. 317 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) { 318 NumElts >>= 1; 319 NumVectorRegs <<= 1; 320 VecTy = MVT::getVectorType(EltTy, NumElts); 321 } 322 323 // Check that VecTy isn't a 1-element vector. 324 if (NumElts == 1 && VecTy == MVT::Other) 325 VT = EltTy; 326 else 327 VT = VecTy; 328 } 329 330 // The common case is that we will only create one register for this 331 // value. If we have that case, create and return the virtual register. 332 unsigned NV = TLI.getNumElements(VT); 333 if (NV == 1) { 334 // If we are promoting this value, pick the next largest supported type. 335 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT); 336 unsigned Reg = MakeReg(PromotedType); 337 // If this is a vector of supported or promoted types (e.g. 4 x i16), 338 // create all of the registers. 339 for (unsigned i = 1; i != NumVectorRegs; ++i) 340 MakeReg(PromotedType); 341 return Reg; 342 } 343 344 // If this value is represented with multiple target registers, make sure 345 // to create enough consecutive registers of the right (smaller) type. 346 VT = TLI.getTypeToExpandTo(VT); 347 unsigned R = MakeReg(VT); 348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i) 349 MakeReg(VT); 350 return R; 351} 352 353//===----------------------------------------------------------------------===// 354/// SelectionDAGLowering - This is the common target-independent lowering 355/// implementation that is parameterized by a TargetLowering object. 356/// Also, targets can overload any lowering method. 357/// 358namespace llvm { 359class SelectionDAGLowering { 360 MachineBasicBlock *CurMBB; 361 362 DenseMap<const Value*, SDOperand> NodeMap; 363 364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 365 /// them up and then emit token factor nodes when possible. This allows us to 366 /// get simple disambiguation between loads without worrying about alias 367 /// analysis. 368 std::vector<SDOperand> PendingLoads; 369 370 /// Case - A struct to record the Value for a switch case, and the 371 /// case's target basic block. 372 struct Case { 373 Constant* Low; 374 Constant* High; 375 MachineBasicBlock* BB; 376 377 Case() : Low(0), High(0), BB(0) { } 378 Case(Constant* low, Constant* high, MachineBasicBlock* bb) : 379 Low(low), High(high), BB(bb) { } 380 uint64_t size() const { 381 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue(); 382 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue(); 383 return (rHigh - rLow + 1ULL); 384 } 385 }; 386 387 struct CaseBits { 388 uint64_t Mask; 389 MachineBasicBlock* BB; 390 unsigned Bits; 391 392 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits): 393 Mask(mask), BB(bb), Bits(bits) { } 394 }; 395 396 typedef std::vector<Case> CaseVector; 397 typedef std::vector<CaseBits> CaseBitsVector; 398 typedef CaseVector::iterator CaseItr; 399 typedef std::pair<CaseItr, CaseItr> CaseRange; 400 401 /// CaseRec - A struct with ctor used in lowering switches to a binary tree 402 /// of conditional branches. 403 struct CaseRec { 404 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) : 405 CaseBB(bb), LT(lt), GE(ge), Range(r) {} 406 407 /// CaseBB - The MBB in which to emit the compare and branch 408 MachineBasicBlock *CaseBB; 409 /// LT, GE - If nonzero, we know the current case value must be less-than or 410 /// greater-than-or-equal-to these Constants. 411 Constant *LT; 412 Constant *GE; 413 /// Range - A pair of iterators representing the range of case values to be 414 /// processed at this point in the binary search tree. 415 CaseRange Range; 416 }; 417 418 typedef std::vector<CaseRec> CaseRecVector; 419 420 /// The comparison function for sorting the switch case values in the vector. 421 /// WARNING: Case ranges should be disjoint! 422 struct CaseCmp { 423 bool operator () (const Case& C1, const Case& C2) { 424 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High)); 425 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low); 426 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High); 427 return CI1->getValue().slt(CI2->getValue()); 428 } 429 }; 430 431 struct CaseBitsCmp { 432 bool operator () (const CaseBits& C1, const CaseBits& C2) { 433 return C1.Bits > C2.Bits; 434 } 435 }; 436 437 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI); 438 439public: 440 // TLI - This is information that describes the available target features we 441 // need for lowering. This indicates when operations are unavailable, 442 // implemented with a libcall, etc. 443 TargetLowering &TLI; 444 SelectionDAG &DAG; 445 const TargetData *TD; 446 447 /// SwitchCases - Vector of CaseBlock structures used to communicate 448 /// SwitchInst code generation information. 449 std::vector<SelectionDAGISel::CaseBlock> SwitchCases; 450 /// JTCases - Vector of JumpTable structures used to communicate 451 /// SwitchInst code generation information. 452 std::vector<SelectionDAGISel::JumpTableBlock> JTCases; 453 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases; 454 455 /// FuncInfo - Information about the function as a whole. 456 /// 457 FunctionLoweringInfo &FuncInfo; 458 459 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli, 460 FunctionLoweringInfo &funcinfo) 461 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), 462 FuncInfo(funcinfo) { 463 } 464 465 /// getRoot - Return the current virtual root of the Selection DAG. 466 /// 467 SDOperand getRoot() { 468 if (PendingLoads.empty()) 469 return DAG.getRoot(); 470 471 if (PendingLoads.size() == 1) { 472 SDOperand Root = PendingLoads[0]; 473 DAG.setRoot(Root); 474 PendingLoads.clear(); 475 return Root; 476 } 477 478 // Otherwise, we have to make a token factor node. 479 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, 480 &PendingLoads[0], PendingLoads.size()); 481 PendingLoads.clear(); 482 DAG.setRoot(Root); 483 return Root; 484 } 485 486 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg); 487 488 void visit(Instruction &I) { visit(I.getOpcode(), I); } 489 490 void visit(unsigned Opcode, User &I) { 491 // Note: this doesn't use InstVisitor, because it has to work with 492 // ConstantExpr's in addition to instructions. 493 switch (Opcode) { 494 default: assert(0 && "Unknown instruction type encountered!"); 495 abort(); 496 // Build the switch statement using the Instruction.def file. 497#define HANDLE_INST(NUM, OPCODE, CLASS) \ 498 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I); 499#include "llvm/Instruction.def" 500 } 501 } 502 503 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; } 504 505 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr, 506 const Value *SV, SDOperand Root, 507 bool isVolatile, unsigned Alignment); 508 509 SDOperand getIntPtrConstant(uint64_t Val) { 510 return DAG.getConstant(Val, TLI.getPointerTy()); 511 } 512 513 SDOperand getValue(const Value *V); 514 515 void setValue(const Value *V, SDOperand NewN) { 516 SDOperand &N = NodeMap[V]; 517 assert(N.Val == 0 && "Already set a value for this node!"); 518 N = NewN; 519 } 520 521 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber, 522 std::set<unsigned> &OutputRegs, 523 std::set<unsigned> &InputRegs); 524 525 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB, 526 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 527 unsigned Opc); 528 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB); 529 void ExportFromCurrentBlock(Value *V); 530 void LowerCallTo(Instruction &I, 531 const Type *CalledValueTy, unsigned CallingConv, 532 bool IsTailCall, SDOperand Callee, unsigned OpIdx, 533 MachineBasicBlock *LandingPad = NULL); 534 535 // Terminator instructions. 536 void visitRet(ReturnInst &I); 537 void visitBr(BranchInst &I); 538 void visitSwitch(SwitchInst &I); 539 void visitUnreachable(UnreachableInst &I) { /* noop */ } 540 541 // Helpers for visitSwitch 542 bool handleSmallSwitchRange(CaseRec& CR, 543 CaseRecVector& WorkList, 544 Value* SV, 545 MachineBasicBlock* Default); 546 bool handleJTSwitchCase(CaseRec& CR, 547 CaseRecVector& WorkList, 548 Value* SV, 549 MachineBasicBlock* Default); 550 bool handleBTSplitSwitchCase(CaseRec& CR, 551 CaseRecVector& WorkList, 552 Value* SV, 553 MachineBasicBlock* Default); 554 bool handleBitTestsSwitchCase(CaseRec& CR, 555 CaseRecVector& WorkList, 556 Value* SV, 557 MachineBasicBlock* Default); 558 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB); 559 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B); 560 void visitBitTestCase(MachineBasicBlock* NextMBB, 561 unsigned Reg, 562 SelectionDAGISel::BitTestCase &B); 563 void visitJumpTable(SelectionDAGISel::JumpTable &JT); 564 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT, 565 SelectionDAGISel::JumpTableHeader &JTH); 566 567 // These all get lowered before this pass. 568 void visitInvoke(InvokeInst &I); 569 void visitUnwind(UnwindInst &I); 570 571 void visitScalarBinary(User &I, unsigned OpCode); 572 void visitVectorBinary(User &I, unsigned OpCode); 573 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp); 574 void visitShift(User &I, unsigned Opcode); 575 void visitAdd(User &I) { 576 if (isa<VectorType>(I.getType())) 577 visitVectorBinary(I, ISD::VADD); 578 else if (I.getType()->isFloatingPoint()) 579 visitScalarBinary(I, ISD::FADD); 580 else 581 visitScalarBinary(I, ISD::ADD); 582 } 583 void visitSub(User &I); 584 void visitMul(User &I) { 585 if (isa<VectorType>(I.getType())) 586 visitVectorBinary(I, ISD::VMUL); 587 else if (I.getType()->isFloatingPoint()) 588 visitScalarBinary(I, ISD::FMUL); 589 else 590 visitScalarBinary(I, ISD::MUL); 591 } 592 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); } 593 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); } 594 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); } 595 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); } 596 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); } 597 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); } 598 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); } 599 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); } 600 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); } 601 void visitShl (User &I) { visitShift(I, ISD::SHL); } 602 void visitLShr(User &I) { visitShift(I, ISD::SRL); } 603 void visitAShr(User &I) { visitShift(I, ISD::SRA); } 604 void visitICmp(User &I); 605 void visitFCmp(User &I); 606 // Visit the conversion instructions 607 void visitTrunc(User &I); 608 void visitZExt(User &I); 609 void visitSExt(User &I); 610 void visitFPTrunc(User &I); 611 void visitFPExt(User &I); 612 void visitFPToUI(User &I); 613 void visitFPToSI(User &I); 614 void visitUIToFP(User &I); 615 void visitSIToFP(User &I); 616 void visitPtrToInt(User &I); 617 void visitIntToPtr(User &I); 618 void visitBitCast(User &I); 619 620 void visitExtractElement(User &I); 621 void visitInsertElement(User &I); 622 void visitShuffleVector(User &I); 623 624 void visitGetElementPtr(User &I); 625 void visitSelect(User &I); 626 627 void visitMalloc(MallocInst &I); 628 void visitFree(FreeInst &I); 629 void visitAlloca(AllocaInst &I); 630 void visitLoad(LoadInst &I); 631 void visitStore(StoreInst &I); 632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially. 633 void visitCall(CallInst &I); 634 void visitInlineAsm(CallInst &I); 635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic); 636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic); 637 638 void visitVAStart(CallInst &I); 639 void visitVAArg(VAArgInst &I); 640 void visitVAEnd(CallInst &I); 641 void visitVACopy(CallInst &I); 642 643 void visitMemIntrinsic(CallInst &I, unsigned Op); 644 645 void visitUserOp1(Instruction &I) { 646 assert(0 && "UserOp1 should not exist at instruction selection time!"); 647 abort(); 648 } 649 void visitUserOp2(Instruction &I) { 650 assert(0 && "UserOp2 should not exist at instruction selection time!"); 651 abort(); 652 } 653}; 654} // end namespace llvm 655 656SDOperand SelectionDAGLowering::getValue(const Value *V) { 657 SDOperand &N = NodeMap[V]; 658 if (N.Val) return N; 659 660 const Type *VTy = V->getType(); 661 MVT::ValueType VT = TLI.getValueType(VTy); 662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) { 663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 664 visit(CE->getOpcode(), *CE); 665 SDOperand N1 = NodeMap[V]; 666 assert(N1.Val && "visit didn't populate the ValueMap!"); 667 return N1; 668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) { 669 return N = DAG.getGlobalAddress(GV, VT); 670 } else if (isa<ConstantPointerNull>(C)) { 671 return N = DAG.getConstant(0, TLI.getPointerTy()); 672 } else if (isa<UndefValue>(C)) { 673 if (!isa<VectorType>(VTy)) 674 return N = DAG.getNode(ISD::UNDEF, VT); 675 676 // Create a VBUILD_VECTOR of undef nodes. 677 const VectorType *PTy = cast<VectorType>(VTy); 678 unsigned NumElements = PTy->getNumElements(); 679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 680 681 SmallVector<SDOperand, 8> Ops; 682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT)); 683 684 // Create a VConstant node with generic Vector type. 685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32)); 686 Ops.push_back(DAG.getValueType(PVT)); 687 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, 688 &Ops[0], Ops.size()); 689 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 690 return N = DAG.getConstantFP(CFP->getValue(), VT); 691 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) { 692 unsigned NumElements = PTy->getNumElements(); 693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 694 695 // Now that we know the number and type of the elements, push a 696 // Constant or ConstantFP node onto the ops list for each element of 697 // the packed constant. 698 SmallVector<SDOperand, 8> Ops; 699 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 700 for (unsigned i = 0; i != NumElements; ++i) 701 Ops.push_back(getValue(CP->getOperand(i))); 702 } else { 703 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!"); 704 SDOperand Op; 705 if (MVT::isFloatingPoint(PVT)) 706 Op = DAG.getConstantFP(0, PVT); 707 else 708 Op = DAG.getConstant(0, PVT); 709 Ops.assign(NumElements, Op); 710 } 711 712 // Create a VBUILD_VECTOR node with generic Vector type. 713 Ops.push_back(DAG.getConstant(NumElements, MVT::i32)); 714 Ops.push_back(DAG.getValueType(PVT)); 715 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], 716 Ops.size()); 717 } else { 718 // Canonicalize all constant ints to be unsigned. 719 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT); 720 } 721 } 722 723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 724 std::map<const AllocaInst*, int>::iterator SI = 725 FuncInfo.StaticAllocaMap.find(AI); 726 if (SI != FuncInfo.StaticAllocaMap.end()) 727 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 728 } 729 730 unsigned InReg = FuncInfo.ValueMap[V]; 731 assert(InReg && "Value not in map!"); 732 733 // If this type is not legal, make it so now. 734 if (VT != MVT::Vector) { 735 if (TLI.getTypeAction(VT) == TargetLowering::Expand) { 736 // Source must be expanded. This input value is actually coming from the 737 // register pair InReg and InReg+1. 738 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT); 739 unsigned NumVals = TLI.getNumElements(VT); 740 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT); 741 if (NumVals == 1) 742 N = DAG.getNode(ISD::BIT_CONVERT, VT, N); 743 else { 744 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!"); 745 N = DAG.getNode(ISD::BUILD_PAIR, VT, N, 746 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT)); 747 } 748 } else { 749 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT); 750 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT); 751 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case 752 N = MVT::isFloatingPoint(VT) 753 ? DAG.getNode(ISD::FP_ROUND, VT, N) 754 : DAG.getNode(ISD::TRUNCATE, VT, N); 755 } 756 } else { 757 // Otherwise, if this is a vector, make it available as a generic vector 758 // here. 759 MVT::ValueType PTyElementVT, PTyLegalElementVT; 760 const VectorType *PTy = cast<VectorType>(VTy); 761 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT, 762 PTyLegalElementVT); 763 764 // Build a VBUILD_VECTOR or VCONCAT_VECTORS with the input registers. 765 SmallVector<SDOperand, 8> Ops; 766 if (PTyElementVT == PTyLegalElementVT) { 767 // If the value types are legal, just VBUILD the CopyFromReg nodes. 768 for (unsigned i = 0; i != NE; ++i) 769 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 770 PTyElementVT)); 771 } else if (PTyElementVT < PTyLegalElementVT) { 772 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate. 773 for (unsigned i = 0; i != NE; ++i) { 774 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 775 PTyLegalElementVT); 776 if (MVT::isFloatingPoint(PTyElementVT)) 777 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op); 778 else 779 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op); 780 Ops.push_back(Op); 781 } 782 } else { 783 // If the register was expanded, use BUILD_PAIR. 784 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!"); 785 for (unsigned i = 0; i != NE; ++i) { 786 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 787 PTyLegalElementVT); 788 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 789 PTyLegalElementVT); 790 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, PTyElementVT, Op0, Op1)); 791 } 792 } 793 794 if (MVT::isVector(PTyElementVT)) { 795 Ops.push_back(DAG.getConstant(NE * MVT::getVectorNumElements(PTyElementVT), MVT::i32)); 796 Ops.push_back(DAG.getValueType(MVT::getVectorElementType(PTyElementVT))); 797 N = DAG.getNode(ISD::VCONCAT_VECTORS, MVT::Vector, &Ops[0], Ops.size()); 798 } else { 799 Ops.push_back(DAG.getConstant(NE, MVT::i32)); 800 Ops.push_back(DAG.getValueType(PTyElementVT)); 801 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); 802 } 803 } 804 805 return N; 806} 807 808 809void SelectionDAGLowering::visitRet(ReturnInst &I) { 810 if (I.getNumOperands() == 0) { 811 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot())); 812 return; 813 } 814 SmallVector<SDOperand, 8> NewValues; 815 NewValues.push_back(getRoot()); 816 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 817 SDOperand RetOp = getValue(I.getOperand(i)); 818 819 // If this is an integer return value, we need to promote it ourselves to 820 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather 821 // than sign/zero. 822 // FIXME: C calling convention requires the return type to be promoted to 823 // at least 32-bit. But this is not necessary for non-C calling conventions. 824 if (MVT::isInteger(RetOp.getValueType()) && 825 RetOp.getValueType() < MVT::i64) { 826 MVT::ValueType TmpVT; 827 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote) 828 TmpVT = TLI.getTypeToTransformTo(MVT::i32); 829 else 830 TmpVT = MVT::i32; 831 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType(); 832 const ParamAttrsList *Attrs = FTy->getParamAttrs(); 833 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 834 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt)) 835 ExtendKind = ISD::SIGN_EXTEND; 836 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt)) 837 ExtendKind = ISD::ZERO_EXTEND; 838 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp); 839 } 840 NewValues.push_back(RetOp); 841 NewValues.push_back(DAG.getConstant(false, MVT::i32)); 842 } 843 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, 844 &NewValues[0], NewValues.size())); 845} 846 847/// ExportFromCurrentBlock - If this condition isn't known to be exported from 848/// the current basic block, add it to ValueMap now so that we'll get a 849/// CopyTo/FromReg. 850void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) { 851 // No need to export constants. 852 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 853 854 // Already exported? 855 if (FuncInfo.isExportedInst(V)) return; 856 857 unsigned Reg = FuncInfo.InitializeRegForValue(V); 858 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg)); 859} 860 861bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V, 862 const BasicBlock *FromBB) { 863 // The operands of the setcc have to be in this block. We don't know 864 // how to export them from some other block. 865 if (Instruction *VI = dyn_cast<Instruction>(V)) { 866 // Can export from current BB. 867 if (VI->getParent() == FromBB) 868 return true; 869 870 // Is already exported, noop. 871 return FuncInfo.isExportedInst(V); 872 } 873 874 // If this is an argument, we can export it if the BB is the entry block or 875 // if it is already exported. 876 if (isa<Argument>(V)) { 877 if (FromBB == &FromBB->getParent()->getEntryBlock()) 878 return true; 879 880 // Otherwise, can only export this if it is already exported. 881 return FuncInfo.isExportedInst(V); 882 } 883 884 // Otherwise, constants can always be exported. 885 return true; 886} 887 888static bool InBlock(const Value *V, const BasicBlock *BB) { 889 if (const Instruction *I = dyn_cast<Instruction>(V)) 890 return I->getParent() == BB; 891 return true; 892} 893 894/// FindMergedConditions - If Cond is an expression like 895void SelectionDAGLowering::FindMergedConditions(Value *Cond, 896 MachineBasicBlock *TBB, 897 MachineBasicBlock *FBB, 898 MachineBasicBlock *CurBB, 899 unsigned Opc) { 900 // If this node is not part of the or/and tree, emit it as a branch. 901 Instruction *BOp = dyn_cast<Instruction>(Cond); 902 903 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 904 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 905 BOp->getParent() != CurBB->getBasicBlock() || 906 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 907 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 908 const BasicBlock *BB = CurBB->getBasicBlock(); 909 910 // If the leaf of the tree is a comparison, merge the condition into 911 // the caseblock. 912 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) && 913 // The operands of the cmp have to be in this block. We don't know 914 // how to export them from some other block. If this is the first block 915 // of the sequence, no exporting is needed. 916 (CurBB == CurMBB || 917 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 918 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) { 919 BOp = cast<Instruction>(Cond); 920 ISD::CondCode Condition; 921 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 922 switch (IC->getPredicate()) { 923 default: assert(0 && "Unknown icmp predicate opcode!"); 924 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break; 925 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break; 926 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break; 927 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break; 928 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break; 929 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break; 930 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break; 931 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break; 932 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break; 933 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break; 934 } 935 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 936 ISD::CondCode FPC, FOC; 937 switch (FC->getPredicate()) { 938 default: assert(0 && "Unknown fcmp predicate opcode!"); 939 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break; 940 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break; 941 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break; 942 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break; 943 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break; 944 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break; 945 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break; 946 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break; 947 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break; 948 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break; 949 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break; 950 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break; 951 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break; 952 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break; 953 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break; 954 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break; 955 } 956 if (FiniteOnlyFPMath()) 957 Condition = FOC; 958 else 959 Condition = FPC; 960 } else { 961 Condition = ISD::SETEQ; // silence warning. 962 assert(0 && "Unknown compare instruction"); 963 } 964 965 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0), 966 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 967 SwitchCases.push_back(CB); 968 return; 969 } 970 971 // Create a CaseBlock record representing this branch. 972 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(), 973 NULL, TBB, FBB, CurBB); 974 SwitchCases.push_back(CB); 975 return; 976 } 977 978 979 // Create TmpBB after CurBB. 980 MachineFunction::iterator BBI = CurBB; 981 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock()); 982 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB); 983 984 if (Opc == Instruction::Or) { 985 // Codegen X | Y as: 986 // jmp_if_X TBB 987 // jmp TmpBB 988 // TmpBB: 989 // jmp_if_Y TBB 990 // jmp FBB 991 // 992 993 // Emit the LHS condition. 994 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc); 995 996 // Emit the RHS condition into TmpBB. 997 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 998 } else { 999 assert(Opc == Instruction::And && "Unknown merge op!"); 1000 // Codegen X & Y as: 1001 // jmp_if_X TmpBB 1002 // jmp FBB 1003 // TmpBB: 1004 // jmp_if_Y TBB 1005 // jmp FBB 1006 // 1007 // This requires creation of TmpBB after CurBB. 1008 1009 // Emit the LHS condition. 1010 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc); 1011 1012 // Emit the RHS condition into TmpBB. 1013 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 1014 } 1015} 1016 1017/// If the set of cases should be emitted as a series of branches, return true. 1018/// If we should emit this as a bunch of and/or'd together conditions, return 1019/// false. 1020static bool 1021ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) { 1022 if (Cases.size() != 2) return true; 1023 1024 // If this is two comparisons of the same values or'd or and'd together, they 1025 // will get folded into a single comparison, so don't emit two blocks. 1026 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1027 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1028 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1029 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1030 return false; 1031 } 1032 1033 return true; 1034} 1035 1036void SelectionDAGLowering::visitBr(BranchInst &I) { 1037 // Update machine-CFG edges. 1038 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1039 1040 // Figure out which block is immediately after the current one. 1041 MachineBasicBlock *NextBlock = 0; 1042 MachineFunction::iterator BBI = CurMBB; 1043 if (++BBI != CurMBB->getParent()->end()) 1044 NextBlock = BBI; 1045 1046 if (I.isUnconditional()) { 1047 // If this is not a fall-through branch, emit the branch. 1048 if (Succ0MBB != NextBlock) 1049 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(), 1050 DAG.getBasicBlock(Succ0MBB))); 1051 1052 // Update machine-CFG edges. 1053 CurMBB->addSuccessor(Succ0MBB); 1054 1055 return; 1056 } 1057 1058 // If this condition is one of the special cases we handle, do special stuff 1059 // now. 1060 Value *CondVal = I.getCondition(); 1061 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1062 1063 // If this is a series of conditions that are or'd or and'd together, emit 1064 // this as a sequence of branches instead of setcc's with and/or operations. 1065 // For example, instead of something like: 1066 // cmp A, B 1067 // C = seteq 1068 // cmp D, E 1069 // F = setle 1070 // or C, F 1071 // jnz foo 1072 // Emit: 1073 // cmp A, B 1074 // je foo 1075 // cmp D, E 1076 // jle foo 1077 // 1078 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1079 if (BOp->hasOneUse() && 1080 (BOp->getOpcode() == Instruction::And || 1081 BOp->getOpcode() == Instruction::Or)) { 1082 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode()); 1083 // If the compares in later blocks need to use values not currently 1084 // exported from this block, export them now. This block should always 1085 // be the first entry. 1086 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!"); 1087 1088 // Allow some cases to be rejected. 1089 if (ShouldEmitAsBranches(SwitchCases)) { 1090 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1091 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1092 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1093 } 1094 1095 // Emit the branch for this block. 1096 visitSwitchCase(SwitchCases[0]); 1097 SwitchCases.erase(SwitchCases.begin()); 1098 return; 1099 } 1100 1101 // Okay, we decided not to do this, remove any inserted MBB's and clear 1102 // SwitchCases. 1103 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1104 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB); 1105 1106 SwitchCases.clear(); 1107 } 1108 } 1109 1110 // Create a CaseBlock record representing this branch. 1111 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(), 1112 NULL, Succ0MBB, Succ1MBB, CurMBB); 1113 // Use visitSwitchCase to actually insert the fast branch sequence for this 1114 // cond branch. 1115 visitSwitchCase(CB); 1116} 1117 1118/// visitSwitchCase - Emits the necessary code to represent a single node in 1119/// the binary search tree resulting from lowering a switch instruction. 1120void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) { 1121 SDOperand Cond; 1122 SDOperand CondLHS = getValue(CB.CmpLHS); 1123 1124 // Build the setcc now. 1125 if (CB.CmpMHS == NULL) { 1126 // Fold "(X == true)" to X and "(X == false)" to !X to 1127 // handle common cases produced by branch lowering. 1128 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ) 1129 Cond = CondLHS; 1130 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) { 1131 SDOperand True = DAG.getConstant(1, CondLHS.getValueType()); 1132 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True); 1133 } else 1134 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1135 } else { 1136 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1137 1138 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue(); 1139 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue(); 1140 1141 SDOperand CmpOp = getValue(CB.CmpMHS); 1142 MVT::ValueType VT = CmpOp.getValueType(); 1143 1144 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1145 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE); 1146 } else { 1147 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT)); 1148 Cond = DAG.getSetCC(MVT::i1, SUB, 1149 DAG.getConstant(High-Low, VT), ISD::SETULE); 1150 } 1151 1152 } 1153 1154 // Set NextBlock to be the MBB immediately after the current one, if any. 1155 // This is used to avoid emitting unnecessary branches to the next block. 1156 MachineBasicBlock *NextBlock = 0; 1157 MachineFunction::iterator BBI = CurMBB; 1158 if (++BBI != CurMBB->getParent()->end()) 1159 NextBlock = BBI; 1160 1161 // If the lhs block is the next block, invert the condition so that we can 1162 // fall through to the lhs instead of the rhs block. 1163 if (CB.TrueBB == NextBlock) { 1164 std::swap(CB.TrueBB, CB.FalseBB); 1165 SDOperand True = DAG.getConstant(1, Cond.getValueType()); 1166 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True); 1167 } 1168 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond, 1169 DAG.getBasicBlock(CB.TrueBB)); 1170 if (CB.FalseBB == NextBlock) 1171 DAG.setRoot(BrCond); 1172 else 1173 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 1174 DAG.getBasicBlock(CB.FalseBB))); 1175 // Update successor info 1176 CurMBB->addSuccessor(CB.TrueBB); 1177 CurMBB->addSuccessor(CB.FalseBB); 1178} 1179 1180/// visitJumpTable - Emit JumpTable node in the current MBB 1181void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) { 1182 // Emit the code for the jump table 1183 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1184 MVT::ValueType PTy = TLI.getPointerTy(); 1185 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy); 1186 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy); 1187 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1), 1188 Table, Index)); 1189 return; 1190} 1191 1192/// visitJumpTableHeader - This function emits necessary code to produce index 1193/// in the JumpTable from switch case. 1194void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT, 1195 SelectionDAGISel::JumpTableHeader &JTH) { 1196 // Subtract the lowest switch case value from the value being switched on 1197 // and conditional branch to default mbb if the result is greater than the 1198 // difference between smallest and largest cases. 1199 SDOperand SwitchOp = getValue(JTH.SValue); 1200 MVT::ValueType VT = SwitchOp.getValueType(); 1201 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 1202 DAG.getConstant(JTH.First, VT)); 1203 1204 // The SDNode we just created, which holds the value being switched on 1205 // minus the the smallest case value, needs to be copied to a virtual 1206 // register so it can be used as an index into the jump table in a 1207 // subsequent basic block. This value may be smaller or larger than the 1208 // target's pointer type, and therefore require extension or truncating. 1209 if (VT > TLI.getPointerTy()) 1210 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB); 1211 else 1212 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB); 1213 1214 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1215 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp); 1216 JT.Reg = JumpTableReg; 1217 1218 // Emit the range check for the jump table, and branch to the default 1219 // block for the switch statement if the value being switched on exceeds 1220 // the largest case in the switch. 1221 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB, 1222 DAG.getConstant(JTH.Last-JTH.First,VT), 1223 ISD::SETUGT); 1224 1225 // Set NextBlock to be the MBB immediately after the current one, if any. 1226 // This is used to avoid emitting unnecessary branches to the next block. 1227 MachineBasicBlock *NextBlock = 0; 1228 MachineFunction::iterator BBI = CurMBB; 1229 if (++BBI != CurMBB->getParent()->end()) 1230 NextBlock = BBI; 1231 1232 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP, 1233 DAG.getBasicBlock(JT.Default)); 1234 1235 if (JT.MBB == NextBlock) 1236 DAG.setRoot(BrCond); 1237 else 1238 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 1239 DAG.getBasicBlock(JT.MBB))); 1240 1241 return; 1242} 1243 1244/// visitBitTestHeader - This function emits necessary code to produce value 1245/// suitable for "bit tests" 1246void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) { 1247 // Subtract the minimum value 1248 SDOperand SwitchOp = getValue(B.SValue); 1249 MVT::ValueType VT = SwitchOp.getValueType(); 1250 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 1251 DAG.getConstant(B.First, VT)); 1252 1253 // Check range 1254 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB, 1255 DAG.getConstant(B.Range, VT), 1256 ISD::SETUGT); 1257 1258 SDOperand ShiftOp; 1259 if (VT > TLI.getShiftAmountTy()) 1260 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB); 1261 else 1262 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB); 1263 1264 // Make desired shift 1265 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(), 1266 DAG.getConstant(1, TLI.getPointerTy()), 1267 ShiftOp); 1268 1269 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1270 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal); 1271 B.Reg = SwitchReg; 1272 1273 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp, 1274 DAG.getBasicBlock(B.Default)); 1275 1276 // Set NextBlock to be the MBB immediately after the current one, if any. 1277 // This is used to avoid emitting unnecessary branches to the next block. 1278 MachineBasicBlock *NextBlock = 0; 1279 MachineFunction::iterator BBI = CurMBB; 1280 if (++BBI != CurMBB->getParent()->end()) 1281 NextBlock = BBI; 1282 1283 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1284 if (MBB == NextBlock) 1285 DAG.setRoot(BrRange); 1286 else 1287 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo, 1288 DAG.getBasicBlock(MBB))); 1289 1290 CurMBB->addSuccessor(B.Default); 1291 CurMBB->addSuccessor(MBB); 1292 1293 return; 1294} 1295 1296/// visitBitTestCase - this function produces one "bit test" 1297void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB, 1298 unsigned Reg, 1299 SelectionDAGISel::BitTestCase &B) { 1300 // Emit bit tests and jumps 1301 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy()); 1302 1303 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), 1304 SwitchVal, 1305 DAG.getConstant(B.Mask, 1306 TLI.getPointerTy())); 1307 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp, 1308 DAG.getConstant(0, TLI.getPointerTy()), 1309 ISD::SETNE); 1310 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), 1311 AndCmp, DAG.getBasicBlock(B.TargetBB)); 1312 1313 // Set NextBlock to be the MBB immediately after the current one, if any. 1314 // This is used to avoid emitting unnecessary branches to the next block. 1315 MachineBasicBlock *NextBlock = 0; 1316 MachineFunction::iterator BBI = CurMBB; 1317 if (++BBI != CurMBB->getParent()->end()) 1318 NextBlock = BBI; 1319 1320 if (NextMBB == NextBlock) 1321 DAG.setRoot(BrAnd); 1322 else 1323 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd, 1324 DAG.getBasicBlock(NextMBB))); 1325 1326 CurMBB->addSuccessor(B.TargetBB); 1327 CurMBB->addSuccessor(NextMBB); 1328 1329 return; 1330} 1331 1332void SelectionDAGLowering::visitInvoke(InvokeInst &I) { 1333 // Retrieve successors. 1334 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1335 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1336 1337 LowerCallTo(I, I.getCalledValue()->getType(), 1338 I.getCallingConv(), 1339 false, 1340 getValue(I.getOperand(0)), 1341 3, LandingPad); 1342 1343 // If the value of the invoke is used outside of its defining block, make it 1344 // available as a virtual register. 1345 if (!I.use_empty()) { 1346 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I); 1347 if (VMI != FuncInfo.ValueMap.end()) 1348 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second)); 1349 } 1350 1351 // Drop into normal successor. 1352 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(), 1353 DAG.getBasicBlock(Return))); 1354 1355 // Update successor info 1356 CurMBB->addSuccessor(Return); 1357 CurMBB->addSuccessor(LandingPad); 1358} 1359 1360void SelectionDAGLowering::visitUnwind(UnwindInst &I) { 1361} 1362 1363/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1364/// small case ranges). 1365bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR, 1366 CaseRecVector& WorkList, 1367 Value* SV, 1368 MachineBasicBlock* Default) { 1369 Case& BackCase = *(CR.Range.second-1); 1370 1371 // Size is the number of Cases represented by this range. 1372 unsigned Size = CR.Range.second - CR.Range.first; 1373 if (Size > 3) 1374 return false; 1375 1376 // Get the MachineFunction which holds the current MBB. This is used when 1377 // inserting any additional MBBs necessary to represent the switch. 1378 MachineFunction *CurMF = CurMBB->getParent(); 1379 1380 // Figure out which block is immediately after the current one. 1381 MachineBasicBlock *NextBlock = 0; 1382 MachineFunction::iterator BBI = CR.CaseBB; 1383 1384 if (++BBI != CurMBB->getParent()->end()) 1385 NextBlock = BBI; 1386 1387 // TODO: If any two of the cases has the same destination, and if one value 1388 // is the same as the other, but has one bit unset that the other has set, 1389 // use bit manipulation to do two compares at once. For example: 1390 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1391 1392 // Rearrange the case blocks so that the last one falls through if possible. 1393 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1394 // The last case block won't fall through into 'NextBlock' if we emit the 1395 // branches in this order. See if rearranging a case value would help. 1396 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1397 if (I->BB == NextBlock) { 1398 std::swap(*I, BackCase); 1399 break; 1400 } 1401 } 1402 } 1403 1404 // Create a CaseBlock record representing a conditional branch to 1405 // the Case's target mbb if the value being switched on SV is equal 1406 // to C. 1407 MachineBasicBlock *CurBlock = CR.CaseBB; 1408 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1409 MachineBasicBlock *FallThrough; 1410 if (I != E-1) { 1411 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock()); 1412 CurMF->getBasicBlockList().insert(BBI, FallThrough); 1413 } else { 1414 // If the last case doesn't match, go to the default block. 1415 FallThrough = Default; 1416 } 1417 1418 Value *RHS, *LHS, *MHS; 1419 ISD::CondCode CC; 1420 if (I->High == I->Low) { 1421 // This is just small small case range :) containing exactly 1 case 1422 CC = ISD::SETEQ; 1423 LHS = SV; RHS = I->High; MHS = NULL; 1424 } else { 1425 CC = ISD::SETLE; 1426 LHS = I->Low; MHS = SV; RHS = I->High; 1427 } 1428 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS, 1429 I->BB, FallThrough, CurBlock); 1430 1431 // If emitting the first comparison, just call visitSwitchCase to emit the 1432 // code into the current block. Otherwise, push the CaseBlock onto the 1433 // vector to be later processed by SDISel, and insert the node's MBB 1434 // before the next MBB. 1435 if (CurBlock == CurMBB) 1436 visitSwitchCase(CB); 1437 else 1438 SwitchCases.push_back(CB); 1439 1440 CurBlock = FallThrough; 1441 } 1442 1443 return true; 1444} 1445 1446static inline bool areJTsAllowed(const TargetLowering &TLI) { 1447 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) || 1448 TLI.isOperationLegal(ISD::BRIND, MVT::Other)); 1449} 1450 1451/// handleJTSwitchCase - Emit jumptable for current switch case range 1452bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR, 1453 CaseRecVector& WorkList, 1454 Value* SV, 1455 MachineBasicBlock* Default) { 1456 Case& FrontCase = *CR.Range.first; 1457 Case& BackCase = *(CR.Range.second-1); 1458 1459 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue(); 1460 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue(); 1461 1462 uint64_t TSize = 0; 1463 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1464 I!=E; ++I) 1465 TSize += I->size(); 1466 1467 if (!areJTsAllowed(TLI) || TSize <= 3) 1468 return false; 1469 1470 double Density = (double)TSize / (double)((Last - First) + 1ULL); 1471 if (Density < 0.4) 1472 return false; 1473 1474 DOUT << "Lowering jump table\n" 1475 << "First entry: " << First << ". Last entry: " << Last << "\n" 1476 << "Size: " << TSize << ". Density: " << Density << "\n\n"; 1477 1478 // Get the MachineFunction which holds the current MBB. This is used when 1479 // inserting any additional MBBs necessary to represent the switch. 1480 MachineFunction *CurMF = CurMBB->getParent(); 1481 1482 // Figure out which block is immediately after the current one. 1483 MachineBasicBlock *NextBlock = 0; 1484 MachineFunction::iterator BBI = CR.CaseBB; 1485 1486 if (++BBI != CurMBB->getParent()->end()) 1487 NextBlock = BBI; 1488 1489 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1490 1491 // Create a new basic block to hold the code for loading the address 1492 // of the jump table, and jumping to it. Update successor information; 1493 // we will either branch to the default case for the switch, or the jump 1494 // table. 1495 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB); 1496 CurMF->getBasicBlockList().insert(BBI, JumpTableBB); 1497 CR.CaseBB->addSuccessor(Default); 1498 CR.CaseBB->addSuccessor(JumpTableBB); 1499 1500 // Build a vector of destination BBs, corresponding to each target 1501 // of the jump table. If the value of the jump table slot corresponds to 1502 // a case statement, push the case's BB onto the vector, otherwise, push 1503 // the default BB. 1504 std::vector<MachineBasicBlock*> DestBBs; 1505 int64_t TEI = First; 1506 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 1507 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue(); 1508 int64_t High = cast<ConstantInt>(I->High)->getSExtValue(); 1509 1510 if ((Low <= TEI) && (TEI <= High)) { 1511 DestBBs.push_back(I->BB); 1512 if (TEI==High) 1513 ++I; 1514 } else { 1515 DestBBs.push_back(Default); 1516 } 1517 } 1518 1519 // Update successor info. Add one edge to each unique successor. 1520 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 1521 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 1522 E = DestBBs.end(); I != E; ++I) { 1523 if (!SuccsHandled[(*I)->getNumber()]) { 1524 SuccsHandled[(*I)->getNumber()] = true; 1525 JumpTableBB->addSuccessor(*I); 1526 } 1527 } 1528 1529 // Create a jump table index for this jump table, or return an existing 1530 // one. 1531 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs); 1532 1533 // Set the jump table information so that we can codegen it as a second 1534 // MachineBasicBlock 1535 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default); 1536 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB, 1537 (CR.CaseBB == CurMBB)); 1538 if (CR.CaseBB == CurMBB) 1539 visitJumpTableHeader(JT, JTH); 1540 1541 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT)); 1542 1543 return true; 1544} 1545 1546/// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1547/// 2 subtrees. 1548bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR, 1549 CaseRecVector& WorkList, 1550 Value* SV, 1551 MachineBasicBlock* Default) { 1552 // Get the MachineFunction which holds the current MBB. This is used when 1553 // inserting any additional MBBs necessary to represent the switch. 1554 MachineFunction *CurMF = CurMBB->getParent(); 1555 1556 // Figure out which block is immediately after the current one. 1557 MachineBasicBlock *NextBlock = 0; 1558 MachineFunction::iterator BBI = CR.CaseBB; 1559 1560 if (++BBI != CurMBB->getParent()->end()) 1561 NextBlock = BBI; 1562 1563 Case& FrontCase = *CR.Range.first; 1564 Case& BackCase = *(CR.Range.second-1); 1565 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1566 1567 // Size is the number of Cases represented by this range. 1568 unsigned Size = CR.Range.second - CR.Range.first; 1569 1570 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue(); 1571 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue(); 1572 double FMetric = 0; 1573 CaseItr Pivot = CR.Range.first + Size/2; 1574 1575 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1576 // (heuristically) allow us to emit JumpTable's later. 1577 uint64_t TSize = 0; 1578 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1579 I!=E; ++I) 1580 TSize += I->size(); 1581 1582 uint64_t LSize = FrontCase.size(); 1583 uint64_t RSize = TSize-LSize; 1584 DOUT << "Selecting best pivot: \n" 1585 << "First: " << First << ", Last: " << Last <<"\n" 1586 << "LSize: " << LSize << ", RSize: " << RSize << "\n"; 1587 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 1588 J!=E; ++I, ++J) { 1589 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue(); 1590 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue(); 1591 assert((RBegin-LEnd>=1) && "Invalid case distance"); 1592 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL); 1593 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL); 1594 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity); 1595 // Should always split in some non-trivial place 1596 DOUT <<"=>Step\n" 1597 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n" 1598 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n" 1599 << "Metric: " << Metric << "\n"; 1600 if (FMetric < Metric) { 1601 Pivot = J; 1602 FMetric = Metric; 1603 DOUT << "Current metric set to: " << FMetric << "\n"; 1604 } 1605 1606 LSize += J->size(); 1607 RSize -= J->size(); 1608 } 1609 if (areJTsAllowed(TLI)) { 1610 // If our case is dense we *really* should handle it earlier! 1611 assert((FMetric > 0) && "Should handle dense range earlier!"); 1612 } else { 1613 Pivot = CR.Range.first + Size/2; 1614 } 1615 1616 CaseRange LHSR(CR.Range.first, Pivot); 1617 CaseRange RHSR(Pivot, CR.Range.second); 1618 Constant *C = Pivot->Low; 1619 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 1620 1621 // We know that we branch to the LHS if the Value being switched on is 1622 // less than the Pivot value, C. We use this to optimize our binary 1623 // tree a bit, by recognizing that if SV is greater than or equal to the 1624 // LHS's Case Value, and that Case Value is exactly one less than the 1625 // Pivot's Value, then we can branch directly to the LHS's Target, 1626 // rather than creating a leaf node for it. 1627 if ((LHSR.second - LHSR.first) == 1 && 1628 LHSR.first->High == CR.GE && 1629 cast<ConstantInt>(C)->getSExtValue() == 1630 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) { 1631 TrueBB = LHSR.first->BB; 1632 } else { 1633 TrueBB = new MachineBasicBlock(LLVMBB); 1634 CurMF->getBasicBlockList().insert(BBI, TrueBB); 1635 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 1636 } 1637 1638 // Similar to the optimization above, if the Value being switched on is 1639 // known to be less than the Constant CR.LT, and the current Case Value 1640 // is CR.LT - 1, then we can branch directly to the target block for 1641 // the current Case Value, rather than emitting a RHS leaf node for it. 1642 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 1643 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() == 1644 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) { 1645 FalseBB = RHSR.first->BB; 1646 } else { 1647 FalseBB = new MachineBasicBlock(LLVMBB); 1648 CurMF->getBasicBlockList().insert(BBI, FalseBB); 1649 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 1650 } 1651 1652 // Create a CaseBlock record representing a conditional branch to 1653 // the LHS node if the value being switched on SV is less than C. 1654 // Otherwise, branch to LHS. 1655 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL, 1656 TrueBB, FalseBB, CR.CaseBB); 1657 1658 if (CR.CaseBB == CurMBB) 1659 visitSwitchCase(CB); 1660 else 1661 SwitchCases.push_back(CB); 1662 1663 return true; 1664} 1665 1666/// handleBitTestsSwitchCase - if current case range has few destination and 1667/// range span less, than machine word bitwidth, encode case range into series 1668/// of masks and emit bit tests with these masks. 1669bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR, 1670 CaseRecVector& WorkList, 1671 Value* SV, 1672 MachineBasicBlock* Default){ 1673 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy()); 1674 1675 Case& FrontCase = *CR.Range.first; 1676 Case& BackCase = *(CR.Range.second-1); 1677 1678 // Get the MachineFunction which holds the current MBB. This is used when 1679 // inserting any additional MBBs necessary to represent the switch. 1680 MachineFunction *CurMF = CurMBB->getParent(); 1681 1682 unsigned numCmps = 0; 1683 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1684 I!=E; ++I) { 1685 // Single case counts one, case range - two. 1686 if (I->Low == I->High) 1687 numCmps +=1; 1688 else 1689 numCmps +=2; 1690 } 1691 1692 // Count unique destinations 1693 SmallSet<MachineBasicBlock*, 4> Dests; 1694 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1695 Dests.insert(I->BB); 1696 if (Dests.size() > 3) 1697 // Don't bother the code below, if there are too much unique destinations 1698 return false; 1699 } 1700 DOUT << "Total number of unique destinations: " << Dests.size() << "\n" 1701 << "Total number of comparisons: " << numCmps << "\n"; 1702 1703 // Compute span of values. 1704 Constant* minValue = FrontCase.Low; 1705 Constant* maxValue = BackCase.High; 1706 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() - 1707 cast<ConstantInt>(minValue)->getSExtValue(); 1708 DOUT << "Compare range: " << range << "\n" 1709 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n" 1710 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n"; 1711 1712 if (range>=IntPtrBits || 1713 (!(Dests.size() == 1 && numCmps >= 3) && 1714 !(Dests.size() == 2 && numCmps >= 5) && 1715 !(Dests.size() >= 3 && numCmps >= 6))) 1716 return false; 1717 1718 DOUT << "Emitting bit tests\n"; 1719 int64_t lowBound = 0; 1720 1721 // Optimize the case where all the case values fit in a 1722 // word without having to subtract minValue. In this case, 1723 // we can optimize away the subtraction. 1724 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 && 1725 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) { 1726 range = cast<ConstantInt>(maxValue)->getSExtValue(); 1727 } else { 1728 lowBound = cast<ConstantInt>(minValue)->getSExtValue(); 1729 } 1730 1731 CaseBitsVector CasesBits; 1732 unsigned i, count = 0; 1733 1734 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1735 MachineBasicBlock* Dest = I->BB; 1736 for (i = 0; i < count; ++i) 1737 if (Dest == CasesBits[i].BB) 1738 break; 1739 1740 if (i == count) { 1741 assert((count < 3) && "Too much destinations to test!"); 1742 CasesBits.push_back(CaseBits(0, Dest, 0)); 1743 count++; 1744 } 1745 1746 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound; 1747 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound; 1748 1749 for (uint64_t j = lo; j <= hi; j++) { 1750 CasesBits[i].Mask |= 1ULL << j; 1751 CasesBits[i].Bits++; 1752 } 1753 1754 } 1755 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 1756 1757 SelectionDAGISel::BitTestInfo BTC; 1758 1759 // Figure out which block is immediately after the current one. 1760 MachineFunction::iterator BBI = CR.CaseBB; 1761 ++BBI; 1762 1763 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1764 1765 DOUT << "Cases:\n"; 1766 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 1767 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits 1768 << ", BB: " << CasesBits[i].BB << "\n"; 1769 1770 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB); 1771 CurMF->getBasicBlockList().insert(BBI, CaseBB); 1772 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask, 1773 CaseBB, 1774 CasesBits[i].BB)); 1775 } 1776 1777 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV, 1778 -1U, (CR.CaseBB == CurMBB), 1779 CR.CaseBB, Default, BTC); 1780 1781 if (CR.CaseBB == CurMBB) 1782 visitBitTestHeader(BTB); 1783 1784 BitTestCases.push_back(BTB); 1785 1786 return true; 1787} 1788 1789 1790// Clusterify - Transform simple list of Cases into list of CaseRange's 1791unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases, 1792 const SwitchInst& SI) { 1793 unsigned numCmps = 0; 1794 1795 // Start with "simple" cases 1796 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) { 1797 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 1798 Cases.push_back(Case(SI.getSuccessorValue(i), 1799 SI.getSuccessorValue(i), 1800 SMBB)); 1801 } 1802 sort(Cases.begin(), Cases.end(), CaseCmp()); 1803 1804 // Merge case into clusters 1805 if (Cases.size()>=2) 1806 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) { 1807 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue(); 1808 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue(); 1809 MachineBasicBlock* nextBB = J->BB; 1810 MachineBasicBlock* currentBB = I->BB; 1811 1812 // If the two neighboring cases go to the same destination, merge them 1813 // into a single case. 1814 if ((nextValue-currentValue==1) && (currentBB == nextBB)) { 1815 I->High = J->High; 1816 J = Cases.erase(J); 1817 } else { 1818 I = J++; 1819 } 1820 } 1821 1822 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 1823 if (I->Low != I->High) 1824 // A range counts double, since it requires two compares. 1825 ++numCmps; 1826 } 1827 1828 return numCmps; 1829} 1830 1831void SelectionDAGLowering::visitSwitch(SwitchInst &SI) { 1832 // Figure out which block is immediately after the current one. 1833 MachineBasicBlock *NextBlock = 0; 1834 MachineFunction::iterator BBI = CurMBB; 1835 1836 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 1837 1838 // If there is only the default destination, branch to it if it is not the 1839 // next basic block. Otherwise, just fall through. 1840 if (SI.getNumOperands() == 2) { 1841 // Update machine-CFG edges. 1842 1843 // If this is not a fall-through branch, emit the branch. 1844 if (Default != NextBlock) 1845 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(), 1846 DAG.getBasicBlock(Default))); 1847 1848 CurMBB->addSuccessor(Default); 1849 return; 1850 } 1851 1852 // If there are any non-default case statements, create a vector of Cases 1853 // representing each one, and sort the vector so that we can efficiently 1854 // create a binary search tree from them. 1855 CaseVector Cases; 1856 unsigned numCmps = Clusterify(Cases, SI); 1857 DOUT << "Clusterify finished. Total clusters: " << Cases.size() 1858 << ". Total compares: " << numCmps << "\n"; 1859 1860 // Get the Value to be switched on and default basic blocks, which will be 1861 // inserted into CaseBlock records, representing basic blocks in the binary 1862 // search tree. 1863 Value *SV = SI.getOperand(0); 1864 1865 // Push the initial CaseRec onto the worklist 1866 CaseRecVector WorkList; 1867 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end()))); 1868 1869 while (!WorkList.empty()) { 1870 // Grab a record representing a case range to process off the worklist 1871 CaseRec CR = WorkList.back(); 1872 WorkList.pop_back(); 1873 1874 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default)) 1875 continue; 1876 1877 // If the range has few cases (two or less) emit a series of specific 1878 // tests. 1879 if (handleSmallSwitchRange(CR, WorkList, SV, Default)) 1880 continue; 1881 1882 // If the switch has more than 5 blocks, and at least 40% dense, and the 1883 // target supports indirect branches, then emit a jump table rather than 1884 // lowering the switch to a binary tree of conditional branches. 1885 if (handleJTSwitchCase(CR, WorkList, SV, Default)) 1886 continue; 1887 1888 // Emit binary tree. We need to pick a pivot, and push left and right ranges 1889 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 1890 handleBTSplitSwitchCase(CR, WorkList, SV, Default); 1891 } 1892} 1893 1894 1895void SelectionDAGLowering::visitSub(User &I) { 1896 // -0.0 - X --> fneg 1897 const Type *Ty = I.getType(); 1898 if (isa<VectorType>(Ty)) { 1899 visitVectorBinary(I, ISD::VSUB); 1900 } else if (Ty->isFloatingPoint()) { 1901 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 1902 if (CFP->isExactlyValue(-0.0)) { 1903 SDOperand Op2 = getValue(I.getOperand(1)); 1904 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2)); 1905 return; 1906 } 1907 visitScalarBinary(I, ISD::FSUB); 1908 } else 1909 visitScalarBinary(I, ISD::SUB); 1910} 1911 1912void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) { 1913 SDOperand Op1 = getValue(I.getOperand(0)); 1914 SDOperand Op2 = getValue(I.getOperand(1)); 1915 1916 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2)); 1917} 1918 1919void 1920SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) { 1921 assert(isa<VectorType>(I.getType())); 1922 const VectorType *Ty = cast<VectorType>(I.getType()); 1923 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType())); 1924 1925 setValue(&I, DAG.getNode(OpCode, MVT::Vector, 1926 getValue(I.getOperand(0)), 1927 getValue(I.getOperand(1)), 1928 DAG.getConstant(Ty->getNumElements(), MVT::i32), 1929 Typ)); 1930} 1931 1932void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp, 1933 unsigned VectorOp) { 1934 if (isa<VectorType>(I.getType())) 1935 visitVectorBinary(I, VectorOp); 1936 else 1937 visitScalarBinary(I, ScalarOp); 1938} 1939 1940void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) { 1941 SDOperand Op1 = getValue(I.getOperand(0)); 1942 SDOperand Op2 = getValue(I.getOperand(1)); 1943 1944 if (TLI.getShiftAmountTy() < Op2.getValueType()) 1945 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2); 1946 else if (TLI.getShiftAmountTy() > Op2.getValueType()) 1947 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2); 1948 1949 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2)); 1950} 1951 1952void SelectionDAGLowering::visitICmp(User &I) { 1953 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 1954 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 1955 predicate = IC->getPredicate(); 1956 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 1957 predicate = ICmpInst::Predicate(IC->getPredicate()); 1958 SDOperand Op1 = getValue(I.getOperand(0)); 1959 SDOperand Op2 = getValue(I.getOperand(1)); 1960 ISD::CondCode Opcode; 1961 switch (predicate) { 1962 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break; 1963 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break; 1964 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break; 1965 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break; 1966 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break; 1967 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break; 1968 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break; 1969 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break; 1970 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break; 1971 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break; 1972 default: 1973 assert(!"Invalid ICmp predicate value"); 1974 Opcode = ISD::SETEQ; 1975 break; 1976 } 1977 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode)); 1978} 1979 1980void SelectionDAGLowering::visitFCmp(User &I) { 1981 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 1982 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 1983 predicate = FC->getPredicate(); 1984 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 1985 predicate = FCmpInst::Predicate(FC->getPredicate()); 1986 SDOperand Op1 = getValue(I.getOperand(0)); 1987 SDOperand Op2 = getValue(I.getOperand(1)); 1988 ISD::CondCode Condition, FOC, FPC; 1989 switch (predicate) { 1990 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break; 1991 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break; 1992 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break; 1993 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break; 1994 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break; 1995 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break; 1996 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break; 1997 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break; 1998 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break; 1999 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break; 2000 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break; 2001 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break; 2002 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break; 2003 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break; 2004 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break; 2005 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break; 2006 default: 2007 assert(!"Invalid FCmp predicate value"); 2008 FOC = FPC = ISD::SETFALSE; 2009 break; 2010 } 2011 if (FiniteOnlyFPMath()) 2012 Condition = FOC; 2013 else 2014 Condition = FPC; 2015 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition)); 2016} 2017 2018void SelectionDAGLowering::visitSelect(User &I) { 2019 SDOperand Cond = getValue(I.getOperand(0)); 2020 SDOperand TrueVal = getValue(I.getOperand(1)); 2021 SDOperand FalseVal = getValue(I.getOperand(2)); 2022 if (!isa<VectorType>(I.getType())) { 2023 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond, 2024 TrueVal, FalseVal)); 2025 } else { 2026 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal, 2027 *(TrueVal.Val->op_end()-2), 2028 *(TrueVal.Val->op_end()-1))); 2029 } 2030} 2031 2032 2033void SelectionDAGLowering::visitTrunc(User &I) { 2034 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2035 SDOperand N = getValue(I.getOperand(0)); 2036 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2037 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N)); 2038} 2039 2040void SelectionDAGLowering::visitZExt(User &I) { 2041 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2042 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2043 SDOperand N = getValue(I.getOperand(0)); 2044 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2045 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N)); 2046} 2047 2048void SelectionDAGLowering::visitSExt(User &I) { 2049 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2050 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2051 SDOperand N = getValue(I.getOperand(0)); 2052 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2053 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N)); 2054} 2055 2056void SelectionDAGLowering::visitFPTrunc(User &I) { 2057 // FPTrunc is never a no-op cast, no need to check 2058 SDOperand N = getValue(I.getOperand(0)); 2059 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2060 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N)); 2061} 2062 2063void SelectionDAGLowering::visitFPExt(User &I){ 2064 // FPTrunc is never a no-op cast, no need to check 2065 SDOperand N = getValue(I.getOperand(0)); 2066 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2067 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N)); 2068} 2069 2070void SelectionDAGLowering::visitFPToUI(User &I) { 2071 // FPToUI is never a no-op cast, no need to check 2072 SDOperand N = getValue(I.getOperand(0)); 2073 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2074 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N)); 2075} 2076 2077void SelectionDAGLowering::visitFPToSI(User &I) { 2078 // FPToSI is never a no-op cast, no need to check 2079 SDOperand N = getValue(I.getOperand(0)); 2080 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2081 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N)); 2082} 2083 2084void SelectionDAGLowering::visitUIToFP(User &I) { 2085 // UIToFP is never a no-op cast, no need to check 2086 SDOperand N = getValue(I.getOperand(0)); 2087 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2088 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N)); 2089} 2090 2091void SelectionDAGLowering::visitSIToFP(User &I){ 2092 // UIToFP is never a no-op cast, no need to check 2093 SDOperand N = getValue(I.getOperand(0)); 2094 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2095 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N)); 2096} 2097 2098void SelectionDAGLowering::visitPtrToInt(User &I) { 2099 // What to do depends on the size of the integer and the size of the pointer. 2100 // We can either truncate, zero extend, or no-op, accordingly. 2101 SDOperand N = getValue(I.getOperand(0)); 2102 MVT::ValueType SrcVT = N.getValueType(); 2103 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2104 SDOperand Result; 2105 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT)) 2106 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N); 2107 else 2108 // Note: ZERO_EXTEND can handle cases where the sizes are equal too 2109 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N); 2110 setValue(&I, Result); 2111} 2112 2113void SelectionDAGLowering::visitIntToPtr(User &I) { 2114 // What to do depends on the size of the integer and the size of the pointer. 2115 // We can either truncate, zero extend, or no-op, accordingly. 2116 SDOperand N = getValue(I.getOperand(0)); 2117 MVT::ValueType SrcVT = N.getValueType(); 2118 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2119 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT)) 2120 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N)); 2121 else 2122 // Note: ZERO_EXTEND can handle cases where the sizes are equal too 2123 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N)); 2124} 2125 2126void SelectionDAGLowering::visitBitCast(User &I) { 2127 SDOperand N = getValue(I.getOperand(0)); 2128 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2129 if (DestVT == MVT::Vector) { 2130 // This is a cast to a vector from something else. 2131 // Get information about the output vector. 2132 const VectorType *DestTy = cast<VectorType>(I.getType()); 2133 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType()); 2134 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N, 2135 DAG.getConstant(DestTy->getNumElements(),MVT::i32), 2136 DAG.getValueType(EltVT))); 2137 return; 2138 } 2139 MVT::ValueType SrcVT = N.getValueType(); 2140 if (SrcVT == MVT::Vector) { 2141 // This is a cast from a vctor to something else. 2142 // Get information about the input vector. 2143 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N)); 2144 return; 2145 } 2146 2147 // BitCast assures us that source and destination are the same size so this 2148 // is either a BIT_CONVERT or a no-op. 2149 if (DestVT != N.getValueType()) 2150 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types 2151 else 2152 setValue(&I, N); // noop cast. 2153} 2154 2155void SelectionDAGLowering::visitInsertElement(User &I) { 2156 SDOperand InVec = getValue(I.getOperand(0)); 2157 SDOperand InVal = getValue(I.getOperand(1)); 2158 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), 2159 getValue(I.getOperand(2))); 2160 2161 SDOperand Num = *(InVec.Val->op_end()-2); 2162 SDOperand Typ = *(InVec.Val->op_end()-1); 2163 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector, 2164 InVec, InVal, InIdx, Num, Typ)); 2165} 2166 2167void SelectionDAGLowering::visitExtractElement(User &I) { 2168 SDOperand InVec = getValue(I.getOperand(0)); 2169 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), 2170 getValue(I.getOperand(1))); 2171 SDOperand Typ = *(InVec.Val->op_end()-1); 2172 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, 2173 TLI.getValueType(I.getType()), InVec, InIdx)); 2174} 2175 2176void SelectionDAGLowering::visitShuffleVector(User &I) { 2177 SDOperand V1 = getValue(I.getOperand(0)); 2178 SDOperand V2 = getValue(I.getOperand(1)); 2179 SDOperand Mask = getValue(I.getOperand(2)); 2180 2181 SDOperand Num = *(V1.Val->op_end()-2); 2182 SDOperand Typ = *(V2.Val->op_end()-1); 2183 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, 2184 V1, V2, Mask, Num, Typ)); 2185} 2186 2187 2188void SelectionDAGLowering::visitGetElementPtr(User &I) { 2189 SDOperand N = getValue(I.getOperand(0)); 2190 const Type *Ty = I.getOperand(0)->getType(); 2191 2192 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 2193 OI != E; ++OI) { 2194 Value *Idx = *OI; 2195 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2196 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2197 if (Field) { 2198 // N = N + Offset 2199 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2200 N = DAG.getNode(ISD::ADD, N.getValueType(), N, 2201 getIntPtrConstant(Offset)); 2202 } 2203 Ty = StTy->getElementType(Field); 2204 } else { 2205 Ty = cast<SequentialType>(Ty)->getElementType(); 2206 2207 // If this is a constant subscript, handle it quickly. 2208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2209 if (CI->getZExtValue() == 0) continue; 2210 uint64_t Offs = 2211 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2212 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs)); 2213 continue; 2214 } 2215 2216 // N = N + Idx * ElementSize; 2217 uint64_t ElementSize = TD->getTypeSize(Ty); 2218 SDOperand IdxN = getValue(Idx); 2219 2220 // If the index is smaller or larger than intptr_t, truncate or extend 2221 // it. 2222 if (IdxN.getValueType() < N.getValueType()) { 2223 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN); 2224 } else if (IdxN.getValueType() > N.getValueType()) 2225 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN); 2226 2227 // If this is a multiply by a power of two, turn it into a shl 2228 // immediately. This is a very common case. 2229 if (isPowerOf2_64(ElementSize)) { 2230 unsigned Amt = Log2_64(ElementSize); 2231 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN, 2232 DAG.getConstant(Amt, TLI.getShiftAmountTy())); 2233 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 2234 continue; 2235 } 2236 2237 SDOperand Scale = getIntPtrConstant(ElementSize); 2238 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale); 2239 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 2240 } 2241 } 2242 setValue(&I, N); 2243} 2244 2245void SelectionDAGLowering::visitAlloca(AllocaInst &I) { 2246 // If this is a fixed sized alloca in the entry block of the function, 2247 // allocate it statically on the stack. 2248 if (FuncInfo.StaticAllocaMap.count(&I)) 2249 return; // getValue will auto-populate this. 2250 2251 const Type *Ty = I.getAllocatedType(); 2252 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty); 2253 unsigned Align = 2254 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2255 I.getAlignment()); 2256 2257 SDOperand AllocSize = getValue(I.getArraySize()); 2258 MVT::ValueType IntPtr = TLI.getPointerTy(); 2259 if (IntPtr < AllocSize.getValueType()) 2260 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize); 2261 else if (IntPtr > AllocSize.getValueType()) 2262 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize); 2263 2264 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize, 2265 getIntPtrConstant(TySize)); 2266 2267 // Handle alignment. If the requested alignment is less than or equal to the 2268 // stack alignment, ignore it and round the size of the allocation up to the 2269 // stack alignment size. If the size is greater than the stack alignment, we 2270 // note this in the DYNAMIC_STACKALLOC node. 2271 unsigned StackAlign = 2272 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 2273 if (Align <= StackAlign) { 2274 Align = 0; 2275 // Add SA-1 to the size. 2276 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize, 2277 getIntPtrConstant(StackAlign-1)); 2278 // Mask out the low bits for alignment purposes. 2279 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize, 2280 getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2281 } 2282 2283 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) }; 2284 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(), 2285 MVT::Other); 2286 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3); 2287 setValue(&I, DSA); 2288 DAG.setRoot(DSA.getValue(1)); 2289 2290 // Inform the Frame Information that we have just allocated a variable-sized 2291 // object. 2292 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject(); 2293} 2294 2295void SelectionDAGLowering::visitLoad(LoadInst &I) { 2296 SDOperand Ptr = getValue(I.getOperand(0)); 2297 2298 SDOperand Root; 2299 if (I.isVolatile()) 2300 Root = getRoot(); 2301 else { 2302 // Do not serialize non-volatile loads against each other. 2303 Root = DAG.getRoot(); 2304 } 2305 2306 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0), 2307 Root, I.isVolatile(), I.getAlignment())); 2308} 2309 2310SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr, 2311 const Value *SV, SDOperand Root, 2312 bool isVolatile, 2313 unsigned Alignment) { 2314 SDOperand L; 2315 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) { 2316 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 2317 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, 2318 DAG.getSrcValue(SV)); 2319 } else { 2320 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, 2321 isVolatile, Alignment); 2322 } 2323 2324 if (isVolatile) 2325 DAG.setRoot(L.getValue(1)); 2326 else 2327 PendingLoads.push_back(L.getValue(1)); 2328 2329 return L; 2330} 2331 2332 2333void SelectionDAGLowering::visitStore(StoreInst &I) { 2334 Value *SrcV = I.getOperand(0); 2335 SDOperand Src = getValue(SrcV); 2336 SDOperand Ptr = getValue(I.getOperand(1)); 2337 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0, 2338 I.isVolatile(), I.getAlignment())); 2339} 2340 2341/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot 2342/// access memory and has no other side effects at all. 2343static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) { 2344#define GET_NO_MEMORY_INTRINSICS 2345#include "llvm/Intrinsics.gen" 2346#undef GET_NO_MEMORY_INTRINSICS 2347 return false; 2348} 2349 2350// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't 2351// have any side-effects or if it only reads memory. 2352static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) { 2353#define GET_SIDE_EFFECT_INFO 2354#include "llvm/Intrinsics.gen" 2355#undef GET_SIDE_EFFECT_INFO 2356 return false; 2357} 2358 2359/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 2360/// node. 2361void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 2362 unsigned Intrinsic) { 2363 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic); 2364 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic); 2365 2366 // Build the operand list. 2367 SmallVector<SDOperand, 8> Ops; 2368 if (HasChain) { // If this intrinsic has side-effects, chainify it. 2369 if (OnlyLoad) { 2370 // We don't need to serialize loads against other loads. 2371 Ops.push_back(DAG.getRoot()); 2372 } else { 2373 Ops.push_back(getRoot()); 2374 } 2375 } 2376 2377 // Add the intrinsic ID as an integer operand. 2378 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 2379 2380 // Add all operands of the call to the operand list. 2381 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 2382 SDOperand Op = getValue(I.getOperand(i)); 2383 2384 // If this is a vector type, force it to the right vector type. 2385 if (Op.getValueType() == MVT::Vector) { 2386 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType()); 2387 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType()); 2388 2389 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements()); 2390 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?"); 2391 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op); 2392 } 2393 2394 assert(TLI.isTypeLegal(Op.getValueType()) && 2395 "Intrinsic uses a non-legal type?"); 2396 Ops.push_back(Op); 2397 } 2398 2399 std::vector<MVT::ValueType> VTs; 2400 if (I.getType() != Type::VoidTy) { 2401 MVT::ValueType VT = TLI.getValueType(I.getType()); 2402 if (VT == MVT::Vector) { 2403 const VectorType *DestTy = cast<VectorType>(I.getType()); 2404 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType()); 2405 2406 VT = MVT::getVectorType(EltVT, DestTy->getNumElements()); 2407 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?"); 2408 } 2409 2410 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?"); 2411 VTs.push_back(VT); 2412 } 2413 if (HasChain) 2414 VTs.push_back(MVT::Other); 2415 2416 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs); 2417 2418 // Create the node. 2419 SDOperand Result; 2420 if (!HasChain) 2421 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(), 2422 &Ops[0], Ops.size()); 2423 else if (I.getType() != Type::VoidTy) 2424 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(), 2425 &Ops[0], Ops.size()); 2426 else 2427 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(), 2428 &Ops[0], Ops.size()); 2429 2430 if (HasChain) { 2431 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1); 2432 if (OnlyLoad) 2433 PendingLoads.push_back(Chain); 2434 else 2435 DAG.setRoot(Chain); 2436 } 2437 if (I.getType() != Type::VoidTy) { 2438 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 2439 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType()); 2440 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result, 2441 DAG.getConstant(PTy->getNumElements(), MVT::i32), 2442 DAG.getValueType(EVT)); 2443 } 2444 setValue(&I, Result); 2445 } 2446} 2447 2448/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one 2449/// (possibly constant folded), return it. Otherwise return NULL. 2450static GlobalVariable *ExtractGlobalVariable (Constant *C) { 2451 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 2452 return GV; 2453 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2454 if (CE->getOpcode() == Instruction::BitCast) 2455 return dyn_cast<GlobalVariable>(CE->getOperand(0)); 2456 else if (CE->getOpcode() == Instruction::GetElementPtr) { 2457 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 2458 if (!CE->getOperand(i)->isNullValue()) 2459 return NULL; 2460 return dyn_cast<GlobalVariable>(CE->getOperand(0)); 2461 } 2462 } 2463 return NULL; 2464} 2465 2466/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 2467/// we want to emit this as a call to a named external function, return the name 2468/// otherwise lower it and return null. 2469const char * 2470SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) { 2471 switch (Intrinsic) { 2472 default: 2473 // By default, turn this into a target intrinsic node. 2474 visitTargetIntrinsic(I, Intrinsic); 2475 return 0; 2476 case Intrinsic::vastart: visitVAStart(I); return 0; 2477 case Intrinsic::vaend: visitVAEnd(I); return 0; 2478 case Intrinsic::vacopy: visitVACopy(I); return 0; 2479 case Intrinsic::returnaddress: 2480 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(), 2481 getValue(I.getOperand(1)))); 2482 return 0; 2483 case Intrinsic::frameaddress: 2484 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(), 2485 getValue(I.getOperand(1)))); 2486 return 0; 2487 case Intrinsic::setjmp: 2488 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 2489 break; 2490 case Intrinsic::longjmp: 2491 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 2492 break; 2493 case Intrinsic::memcpy_i32: 2494 case Intrinsic::memcpy_i64: 2495 visitMemIntrinsic(I, ISD::MEMCPY); 2496 return 0; 2497 case Intrinsic::memset_i32: 2498 case Intrinsic::memset_i64: 2499 visitMemIntrinsic(I, ISD::MEMSET); 2500 return 0; 2501 case Intrinsic::memmove_i32: 2502 case Intrinsic::memmove_i64: 2503 visitMemIntrinsic(I, ISD::MEMMOVE); 2504 return 0; 2505 2506 case Intrinsic::dbg_stoppoint: { 2507 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2508 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I); 2509 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) { 2510 SDOperand Ops[5]; 2511 2512 Ops[0] = getRoot(); 2513 Ops[1] = getValue(SPI.getLineValue()); 2514 Ops[2] = getValue(SPI.getColumnValue()); 2515 2516 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext()); 2517 assert(DD && "Not a debug information descriptor"); 2518 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD); 2519 2520 Ops[3] = DAG.getString(CompileUnit->getFileName()); 2521 Ops[4] = DAG.getString(CompileUnit->getDirectory()); 2522 2523 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5)); 2524 } 2525 2526 return 0; 2527 } 2528 case Intrinsic::dbg_region_start: { 2529 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2530 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I); 2531 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) { 2532 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext()); 2533 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 2534 DAG.getConstant(LabelID, MVT::i32))); 2535 } 2536 2537 return 0; 2538 } 2539 case Intrinsic::dbg_region_end: { 2540 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2541 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I); 2542 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) { 2543 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext()); 2544 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, 2545 getRoot(), DAG.getConstant(LabelID, MVT::i32))); 2546 } 2547 2548 return 0; 2549 } 2550 case Intrinsic::dbg_func_start: { 2551 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2552 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I); 2553 if (MMI && FSI.getSubprogram() && 2554 MMI->Verify(FSI.getSubprogram())) { 2555 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram()); 2556 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, 2557 getRoot(), DAG.getConstant(LabelID, MVT::i32))); 2558 } 2559 2560 return 0; 2561 } 2562 case Intrinsic::dbg_declare: { 2563 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2564 DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 2565 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) { 2566 SDOperand AddressOp = getValue(DI.getAddress()); 2567 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) 2568 MMI->RecordVariable(DI.getVariable(), FI->getIndex()); 2569 } 2570 2571 return 0; 2572 } 2573 2574 case Intrinsic::eh_exception: { 2575 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2576 2577 if (ExceptionHandling && MMI) { 2578 // Mark exception register as live in. 2579 unsigned Reg = TLI.getExceptionAddressRegister(); 2580 if (Reg) CurMBB->addLiveIn(Reg); 2581 2582 // Insert the EXCEPTIONADDR instruction. 2583 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 2584 SDOperand Ops[1]; 2585 Ops[0] = DAG.getRoot(); 2586 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1); 2587 setValue(&I, Op); 2588 DAG.setRoot(Op.getValue(1)); 2589 } else { 2590 setValue(&I, DAG.getConstant(0, TLI.getPointerTy())); 2591 } 2592 return 0; 2593 } 2594 2595 case Intrinsic::eh_selector: 2596 case Intrinsic::eh_filter:{ 2597 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2598 2599 if (ExceptionHandling && MMI) { 2600 // Inform the MachineModuleInfo of the personality for this landing pad. 2601 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2)); 2602 assert(CE && CE->getOpcode() == Instruction::BitCast && 2603 isa<Function>(CE->getOperand(0)) && 2604 "Personality should be a function"); 2605 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0))); 2606 2607 // Gather all the type infos for this landing pad and pass them along to 2608 // MachineModuleInfo. 2609 std::vector<GlobalVariable *> TyInfo; 2610 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) { 2611 Constant *C = cast<Constant>(I.getOperand(i)); 2612 GlobalVariable *GV = ExtractGlobalVariable(C); 2613 assert (GV || isa<ConstantPointerNull>(C) && 2614 "TypeInfo must be a global variable or NULL"); 2615 TyInfo.push_back(GV); 2616 } 2617 if (Intrinsic == Intrinsic::eh_filter) 2618 MMI->addFilterTypeInfo(CurMBB, TyInfo); 2619 else 2620 MMI->addCatchTypeInfo(CurMBB, TyInfo); 2621 2622 // Mark exception selector register as live in. 2623 unsigned Reg = TLI.getExceptionSelectorRegister(); 2624 if (Reg) CurMBB->addLiveIn(Reg); 2625 2626 // Insert the EHSELECTION instruction. 2627 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 2628 SDOperand Ops[2]; 2629 Ops[0] = getValue(I.getOperand(1)); 2630 Ops[1] = getRoot(); 2631 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2); 2632 setValue(&I, Op); 2633 DAG.setRoot(Op.getValue(1)); 2634 } else { 2635 setValue(&I, DAG.getConstant(0, TLI.getPointerTy())); 2636 } 2637 2638 return 0; 2639 } 2640 2641 case Intrinsic::eh_typeid_for: { 2642 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2643 2644 if (MMI) { 2645 // Find the type id for the given typeinfo. 2646 Constant *C = cast<Constant>(I.getOperand(1)); 2647 GlobalVariable *GV = ExtractGlobalVariable(C); 2648 assert (GV || isa<ConstantPointerNull>(C) && 2649 "TypeInfo must be a global variable or NULL"); 2650 2651 unsigned TypeID = MMI->getTypeIDFor(GV); 2652 setValue(&I, DAG.getConstant(TypeID, MVT::i32)); 2653 } else { 2654 setValue(&I, DAG.getConstant(0, MVT::i32)); 2655 } 2656 2657 return 0; 2658 } 2659 2660 case Intrinsic::sqrt_f32: 2661 case Intrinsic::sqrt_f64: 2662 setValue(&I, DAG.getNode(ISD::FSQRT, 2663 getValue(I.getOperand(1)).getValueType(), 2664 getValue(I.getOperand(1)))); 2665 return 0; 2666 case Intrinsic::powi_f32: 2667 case Intrinsic::powi_f64: 2668 setValue(&I, DAG.getNode(ISD::FPOWI, 2669 getValue(I.getOperand(1)).getValueType(), 2670 getValue(I.getOperand(1)), 2671 getValue(I.getOperand(2)))); 2672 return 0; 2673 case Intrinsic::pcmarker: { 2674 SDOperand Tmp = getValue(I.getOperand(1)); 2675 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp)); 2676 return 0; 2677 } 2678 case Intrinsic::readcyclecounter: { 2679 SDOperand Op = getRoot(); 2680 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, 2681 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2, 2682 &Op, 1); 2683 setValue(&I, Tmp); 2684 DAG.setRoot(Tmp.getValue(1)); 2685 return 0; 2686 } 2687 case Intrinsic::part_select: { 2688 // Currently not implemented: just abort 2689 assert(0 && "part_select intrinsic not implemented"); 2690 abort(); 2691 } 2692 case Intrinsic::part_set: { 2693 // Currently not implemented: just abort 2694 assert(0 && "part_set intrinsic not implemented"); 2695 abort(); 2696 } 2697 case Intrinsic::bswap: 2698 setValue(&I, DAG.getNode(ISD::BSWAP, 2699 getValue(I.getOperand(1)).getValueType(), 2700 getValue(I.getOperand(1)))); 2701 return 0; 2702 case Intrinsic::cttz: { 2703 SDOperand Arg = getValue(I.getOperand(1)); 2704 MVT::ValueType Ty = Arg.getValueType(); 2705 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg); 2706 if (Ty < MVT::i32) 2707 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result); 2708 else if (Ty > MVT::i32) 2709 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result); 2710 setValue(&I, result); 2711 return 0; 2712 } 2713 case Intrinsic::ctlz: { 2714 SDOperand Arg = getValue(I.getOperand(1)); 2715 MVT::ValueType Ty = Arg.getValueType(); 2716 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg); 2717 if (Ty < MVT::i32) 2718 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result); 2719 else if (Ty > MVT::i32) 2720 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result); 2721 setValue(&I, result); 2722 return 0; 2723 } 2724 case Intrinsic::ctpop: { 2725 SDOperand Arg = getValue(I.getOperand(1)); 2726 MVT::ValueType Ty = Arg.getValueType(); 2727 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg); 2728 if (Ty < MVT::i32) 2729 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result); 2730 else if (Ty > MVT::i32) 2731 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result); 2732 setValue(&I, result); 2733 return 0; 2734 } 2735 case Intrinsic::stacksave: { 2736 SDOperand Op = getRoot(); 2737 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, 2738 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1); 2739 setValue(&I, Tmp); 2740 DAG.setRoot(Tmp.getValue(1)); 2741 return 0; 2742 } 2743 case Intrinsic::stackrestore: { 2744 SDOperand Tmp = getValue(I.getOperand(1)); 2745 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp)); 2746 return 0; 2747 } 2748 case Intrinsic::prefetch: 2749 // FIXME: Currently discarding prefetches. 2750 return 0; 2751 } 2752} 2753 2754 2755void SelectionDAGLowering::LowerCallTo(Instruction &I, 2756 const Type *CalledValueTy, 2757 unsigned CallingConv, 2758 bool IsTailCall, 2759 SDOperand Callee, unsigned OpIdx, 2760 MachineBasicBlock *LandingPad) { 2761 const PointerType *PT = cast<PointerType>(CalledValueTy); 2762 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 2763 const ParamAttrsList *Attrs = FTy->getParamAttrs(); 2764 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2765 unsigned BeginLabel = 0, EndLabel = 0; 2766 2767 TargetLowering::ArgListTy Args; 2768 TargetLowering::ArgListEntry Entry; 2769 Args.reserve(I.getNumOperands()); 2770 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) { 2771 Value *Arg = I.getOperand(i); 2772 SDOperand ArgNode = getValue(Arg); 2773 Entry.Node = ArgNode; Entry.Ty = Arg->getType(); 2774 2775 unsigned attrInd = i - OpIdx + 1; 2776 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt); 2777 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt); 2778 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg); 2779 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet); 2780 Args.push_back(Entry); 2781 } 2782 2783 if (ExceptionHandling && MMI) { 2784 // Insert a label before the invoke call to mark the try range. This can be 2785 // used to detect deletion of the invoke via the MachineModuleInfo. 2786 BeginLabel = MMI->NextLabelID(); 2787 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 2788 DAG.getConstant(BeginLabel, MVT::i32))); 2789 } 2790 2791 std::pair<SDOperand,SDOperand> Result = 2792 TLI.LowerCallTo(getRoot(), I.getType(), 2793 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), 2794 FTy->isVarArg(), CallingConv, IsTailCall, 2795 Callee, Args, DAG); 2796 if (I.getType() != Type::VoidTy) 2797 setValue(&I, Result.first); 2798 DAG.setRoot(Result.second); 2799 2800 if (ExceptionHandling && MMI) { 2801 // Insert a label at the end of the invoke call to mark the try range. This 2802 // can be used to detect deletion of the invoke via the MachineModuleInfo. 2803 EndLabel = MMI->NextLabelID(); 2804 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 2805 DAG.getConstant(EndLabel, MVT::i32))); 2806 2807 // Inform MachineModuleInfo of range. 2808 MMI->addInvoke(LandingPad, BeginLabel, EndLabel); 2809 } 2810} 2811 2812 2813void SelectionDAGLowering::visitCall(CallInst &I) { 2814 const char *RenameFn = 0; 2815 if (Function *F = I.getCalledFunction()) { 2816 if (F->isDeclaration()) 2817 if (unsigned IID = F->getIntrinsicID()) { 2818 RenameFn = visitIntrinsicCall(I, IID); 2819 if (!RenameFn) 2820 return; 2821 } else { // Not an LLVM intrinsic. 2822 const std::string &Name = F->getName(); 2823 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) { 2824 if (I.getNumOperands() == 3 && // Basic sanity checks. 2825 I.getOperand(1)->getType()->isFloatingPoint() && 2826 I.getType() == I.getOperand(1)->getType() && 2827 I.getType() == I.getOperand(2)->getType()) { 2828 SDOperand LHS = getValue(I.getOperand(1)); 2829 SDOperand RHS = getValue(I.getOperand(2)); 2830 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(), 2831 LHS, RHS)); 2832 return; 2833 } 2834 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) { 2835 if (I.getNumOperands() == 2 && // Basic sanity checks. 2836 I.getOperand(1)->getType()->isFloatingPoint() && 2837 I.getType() == I.getOperand(1)->getType()) { 2838 SDOperand Tmp = getValue(I.getOperand(1)); 2839 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp)); 2840 return; 2841 } 2842 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) { 2843 if (I.getNumOperands() == 2 && // Basic sanity checks. 2844 I.getOperand(1)->getType()->isFloatingPoint() && 2845 I.getType() == I.getOperand(1)->getType()) { 2846 SDOperand Tmp = getValue(I.getOperand(1)); 2847 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp)); 2848 return; 2849 } 2850 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) { 2851 if (I.getNumOperands() == 2 && // Basic sanity checks. 2852 I.getOperand(1)->getType()->isFloatingPoint() && 2853 I.getType() == I.getOperand(1)->getType()) { 2854 SDOperand Tmp = getValue(I.getOperand(1)); 2855 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp)); 2856 return; 2857 } 2858 } 2859 } 2860 } else if (isa<InlineAsm>(I.getOperand(0))) { 2861 visitInlineAsm(I); 2862 return; 2863 } 2864 2865 SDOperand Callee; 2866 if (!RenameFn) 2867 Callee = getValue(I.getOperand(0)); 2868 else 2869 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 2870 2871 LowerCallTo(I, I.getCalledValue()->getType(), 2872 I.getCallingConv(), 2873 I.isTailCall(), 2874 Callee, 2875 1); 2876} 2877 2878 2879SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 2880 SDOperand &Chain, SDOperand &Flag)const{ 2881 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag); 2882 Chain = Val.getValue(1); 2883 Flag = Val.getValue(2); 2884 2885 // If the result was expanded, copy from the top part. 2886 if (Regs.size() > 1) { 2887 assert(Regs.size() == 2 && 2888 "Cannot expand to more than 2 elts yet!"); 2889 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag); 2890 Chain = Hi.getValue(1); 2891 Flag = Hi.getValue(2); 2892 if (DAG.getTargetLoweringInfo().isLittleEndian()) 2893 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi); 2894 else 2895 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val); 2896 } 2897 2898 // Otherwise, if the return value was promoted or extended, truncate it to the 2899 // appropriate type. 2900 if (RegVT == ValueVT) 2901 return Val; 2902 2903 if (MVT::isVector(RegVT)) { 2904 assert(ValueVT == MVT::Vector && "Unknown vector conversion!"); 2905 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val, 2906 DAG.getConstant(MVT::getVectorNumElements(RegVT), 2907 MVT::i32), 2908 DAG.getValueType(MVT::getVectorElementType(RegVT))); 2909 } 2910 2911 if (MVT::isInteger(RegVT)) { 2912 if (ValueVT < RegVT) 2913 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val); 2914 else 2915 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val); 2916 } 2917 2918 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT)); 2919 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val); 2920} 2921 2922/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 2923/// specified value into the registers specified by this object. This uses 2924/// Chain/Flag as the input and updates them for the output Chain/Flag. 2925void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 2926 SDOperand &Chain, SDOperand &Flag, 2927 MVT::ValueType PtrVT) const { 2928 if (Regs.size() == 1) { 2929 // If there is a single register and the types differ, this must be 2930 // a promotion. 2931 if (RegVT != ValueVT) { 2932 if (MVT::isVector(RegVT)) { 2933 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?"); 2934 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val); 2935 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) { 2936 if (RegVT < ValueVT) 2937 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val); 2938 else 2939 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val); 2940 } else if (MVT::isFloatingPoint(RegVT) && 2941 MVT::isFloatingPoint(Val.getValueType())) { 2942 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val); 2943 } else if (MVT::getSizeInBits(RegVT) == 2944 MVT::getSizeInBits(Val.getValueType())) { 2945 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val); 2946 } else { 2947 assert(0 && "Unknown mismatch!"); 2948 } 2949 } 2950 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag); 2951 Flag = Chain.getValue(1); 2952 } else { 2953 std::vector<unsigned> R(Regs); 2954 if (!DAG.getTargetLoweringInfo().isLittleEndian()) 2955 std::reverse(R.begin(), R.end()); 2956 2957 for (unsigned i = 0, e = R.size(); i != e; ++i) { 2958 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val, 2959 DAG.getConstant(i, PtrVT)); 2960 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag); 2961 Flag = Chain.getValue(1); 2962 } 2963 } 2964} 2965 2966/// AddInlineAsmOperands - Add this value to the specified inlineasm node 2967/// operand list. This adds the code marker and includes the number of 2968/// values added into it. 2969void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 2970 std::vector<SDOperand> &Ops) const { 2971 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy(); 2972 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy)); 2973 for (unsigned i = 0, e = Regs.size(); i != e; ++i) 2974 Ops.push_back(DAG.getRegister(Regs[i], RegVT)); 2975} 2976 2977/// isAllocatableRegister - If the specified register is safe to allocate, 2978/// i.e. it isn't a stack pointer or some other special register, return the 2979/// register class for the register. Otherwise, return null. 2980static const TargetRegisterClass * 2981isAllocatableRegister(unsigned Reg, MachineFunction &MF, 2982 const TargetLowering &TLI, const MRegisterInfo *MRI) { 2983 MVT::ValueType FoundVT = MVT::Other; 2984 const TargetRegisterClass *FoundRC = 0; 2985 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(), 2986 E = MRI->regclass_end(); RCI != E; ++RCI) { 2987 MVT::ValueType ThisVT = MVT::Other; 2988 2989 const TargetRegisterClass *RC = *RCI; 2990 // If none of the the value types for this register class are valid, we 2991 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2992 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 2993 I != E; ++I) { 2994 if (TLI.isTypeLegal(*I)) { 2995 // If we have already found this register in a different register class, 2996 // choose the one with the largest VT specified. For example, on 2997 // PowerPC, we favor f64 register classes over f32. 2998 if (FoundVT == MVT::Other || 2999 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) { 3000 ThisVT = *I; 3001 break; 3002 } 3003 } 3004 } 3005 3006 if (ThisVT == MVT::Other) continue; 3007 3008 // NOTE: This isn't ideal. In particular, this might allocate the 3009 // frame pointer in functions that need it (due to them not being taken 3010 // out of allocation, because a variable sized allocation hasn't been seen 3011 // yet). This is a slight code pessimization, but should still work. 3012 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 3013 E = RC->allocation_order_end(MF); I != E; ++I) 3014 if (*I == Reg) { 3015 // We found a matching register class. Keep looking at others in case 3016 // we find one with larger registers that this physreg is also in. 3017 FoundRC = RC; 3018 FoundVT = ThisVT; 3019 break; 3020 } 3021 } 3022 return FoundRC; 3023} 3024 3025 3026namespace { 3027/// AsmOperandInfo - This contains information for each constraint that we are 3028/// lowering. 3029struct AsmOperandInfo : public InlineAsm::ConstraintInfo { 3030 /// ConstraintCode - This contains the actual string for the code, like "m". 3031 std::string ConstraintCode; 3032 3033 /// ConstraintType - Information about the constraint code, e.g. Register, 3034 /// RegisterClass, Memory, Other, Unknown. 3035 TargetLowering::ConstraintType ConstraintType; 3036 3037 /// CallOperand/CallOperandval - If this is the result output operand or a 3038 /// clobber, this is null, otherwise it is the incoming operand to the 3039 /// CallInst. This gets modified as the asm is processed. 3040 SDOperand CallOperand; 3041 Value *CallOperandVal; 3042 3043 /// ConstraintVT - The ValueType for the operand value. 3044 MVT::ValueType ConstraintVT; 3045 3046 /// AssignedRegs - If this is a register or register class operand, this 3047 /// contains the set of register corresponding to the operand. 3048 RegsForValue AssignedRegs; 3049 3050 AsmOperandInfo(const InlineAsm::ConstraintInfo &info) 3051 : InlineAsm::ConstraintInfo(info), 3052 ConstraintType(TargetLowering::C_Unknown), 3053 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) { 3054 } 3055 3056 void ComputeConstraintToUse(const TargetLowering &TLI); 3057 3058 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 3059 /// busy in OutputRegs/InputRegs. 3060 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 3061 std::set<unsigned> &OutputRegs, 3062 std::set<unsigned> &InputRegs) const { 3063 if (isOutReg) 3064 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end()); 3065 if (isInReg) 3066 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end()); 3067 } 3068}; 3069} // end anon namespace. 3070 3071/// getConstraintGenerality - Return an integer indicating how general CT is. 3072static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 3073 switch (CT) { 3074 default: assert(0 && "Unknown constraint type!"); 3075 case TargetLowering::C_Other: 3076 case TargetLowering::C_Unknown: 3077 return 0; 3078 case TargetLowering::C_Register: 3079 return 1; 3080 case TargetLowering::C_RegisterClass: 3081 return 2; 3082 case TargetLowering::C_Memory: 3083 return 3; 3084 } 3085} 3086 3087void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) { 3088 assert(!Codes.empty() && "Must have at least one constraint"); 3089 3090 std::string *Current = &Codes[0]; 3091 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current); 3092 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common. 3093 ConstraintCode = *Current; 3094 ConstraintType = CurType; 3095 return; 3096 } 3097 3098 unsigned CurGenerality = getConstraintGenerality(CurType); 3099 3100 // If we have multiple constraints, try to pick the most general one ahead 3101 // of time. This isn't a wonderful solution, but handles common cases. 3102 for (unsigned j = 1, e = Codes.size(); j != e; ++j) { 3103 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]); 3104 unsigned ThisGenerality = getConstraintGenerality(ThisType); 3105 if (ThisGenerality > CurGenerality) { 3106 // This constraint letter is more general than the previous one, 3107 // use it. 3108 CurType = ThisType; 3109 Current = &Codes[j]; 3110 CurGenerality = ThisGenerality; 3111 } 3112 } 3113 3114 ConstraintCode = *Current; 3115 ConstraintType = CurType; 3116} 3117 3118 3119void SelectionDAGLowering:: 3120GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber, 3121 std::set<unsigned> &OutputRegs, 3122 std::set<unsigned> &InputRegs) { 3123 // Compute whether this value requires an input register, an output register, 3124 // or both. 3125 bool isOutReg = false; 3126 bool isInReg = false; 3127 switch (OpInfo.Type) { 3128 case InlineAsm::isOutput: 3129 isOutReg = true; 3130 3131 // If this is an early-clobber output, or if there is an input 3132 // constraint that matches this, we need to reserve the input register 3133 // so no other inputs allocate to it. 3134 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput; 3135 break; 3136 case InlineAsm::isInput: 3137 isInReg = true; 3138 isOutReg = false; 3139 break; 3140 case InlineAsm::isClobber: 3141 isOutReg = true; 3142 isInReg = true; 3143 break; 3144 } 3145 3146 3147 MachineFunction &MF = DAG.getMachineFunction(); 3148 std::vector<unsigned> Regs; 3149 3150 // If this is a constraint for a single physreg, or a constraint for a 3151 // register class, find it. 3152 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 3153 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 3154 OpInfo.ConstraintVT); 3155 3156 unsigned NumRegs = 1; 3157 if (OpInfo.ConstraintVT != MVT::Other) 3158 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT); 3159 MVT::ValueType RegVT; 3160 MVT::ValueType ValueVT = OpInfo.ConstraintVT; 3161 3162 3163 // If this is a constraint for a specific physical register, like {r17}, 3164 // assign it now. 3165 if (PhysReg.first) { 3166 if (OpInfo.ConstraintVT == MVT::Other) 3167 ValueVT = *PhysReg.second->vt_begin(); 3168 3169 // Get the actual register value type. This is important, because the user 3170 // may have asked for (e.g.) the AX register in i32 type. We need to 3171 // remember that AX is actually i16 to get the right extension. 3172 RegVT = *PhysReg.second->vt_begin(); 3173 3174 // This is a explicit reference to a physical register. 3175 Regs.push_back(PhysReg.first); 3176 3177 // If this is an expanded reference, add the rest of the regs to Regs. 3178 if (NumRegs != 1) { 3179 TargetRegisterClass::iterator I = PhysReg.second->begin(); 3180 TargetRegisterClass::iterator E = PhysReg.second->end(); 3181 for (; *I != PhysReg.first; ++I) 3182 assert(I != E && "Didn't find reg!"); 3183 3184 // Already added the first reg. 3185 --NumRegs; ++I; 3186 for (; NumRegs; --NumRegs, ++I) { 3187 assert(I != E && "Ran out of registers to allocate!"); 3188 Regs.push_back(*I); 3189 } 3190 } 3191 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 3192 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs); 3193 return; 3194 } 3195 3196 // Otherwise, if this was a reference to an LLVM register class, create vregs 3197 // for this reference. 3198 std::vector<unsigned> RegClassRegs; 3199 if (PhysReg.second) { 3200 // If this is an early clobber or tied register, our regalloc doesn't know 3201 // how to maintain the constraint. If it isn't, go ahead and create vreg 3202 // and let the regalloc do the right thing. 3203 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber && 3204 // If there is some other early clobber and this is an input register, 3205 // then we are forced to pre-allocate the input reg so it doesn't 3206 // conflict with the earlyclobber. 3207 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) { 3208 RegVT = *PhysReg.second->vt_begin(); 3209 3210 if (OpInfo.ConstraintVT == MVT::Other) 3211 ValueVT = RegVT; 3212 3213 // Create the appropriate number of virtual registers. 3214 SSARegMap *RegMap = MF.getSSARegMap(); 3215 for (; NumRegs; --NumRegs) 3216 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second)); 3217 3218 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 3219 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs); 3220 return; 3221 } 3222 3223 // Otherwise, we can't allocate it. Let the code below figure out how to 3224 // maintain these constraints. 3225 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end()); 3226 3227 } else { 3228 // This is a reference to a register class that doesn't directly correspond 3229 // to an LLVM register class. Allocate NumRegs consecutive, available, 3230 // registers from the class. 3231 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 3232 OpInfo.ConstraintVT); 3233 } 3234 3235 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo(); 3236 unsigned NumAllocated = 0; 3237 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 3238 unsigned Reg = RegClassRegs[i]; 3239 // See if this register is available. 3240 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 3241 (isInReg && InputRegs.count(Reg))) { // Already used. 3242 // Make sure we find consecutive registers. 3243 NumAllocated = 0; 3244 continue; 3245 } 3246 3247 // Check to see if this register is allocatable (i.e. don't give out the 3248 // stack pointer). 3249 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI); 3250 if (!RC) { 3251 // Make sure we find consecutive registers. 3252 NumAllocated = 0; 3253 continue; 3254 } 3255 3256 // Okay, this register is good, we can use it. 3257 ++NumAllocated; 3258 3259 // If we allocated enough consecutive registers, succeed. 3260 if (NumAllocated == NumRegs) { 3261 unsigned RegStart = (i-NumAllocated)+1; 3262 unsigned RegEnd = i+1; 3263 // Mark all of the allocated registers used. 3264 for (unsigned i = RegStart; i != RegEnd; ++i) 3265 Regs.push_back(RegClassRegs[i]); 3266 3267 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(), 3268 OpInfo.ConstraintVT); 3269 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs); 3270 return; 3271 } 3272 } 3273 3274 // Otherwise, we couldn't allocate enough registers for this. 3275 return; 3276} 3277 3278 3279/// visitInlineAsm - Handle a call to an InlineAsm object. 3280/// 3281void SelectionDAGLowering::visitInlineAsm(CallInst &I) { 3282 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0)); 3283 3284 /// ConstraintOperands - Information about all of the constraints. 3285 std::vector<AsmOperandInfo> ConstraintOperands; 3286 3287 SDOperand Chain = getRoot(); 3288 SDOperand Flag; 3289 3290 std::set<unsigned> OutputRegs, InputRegs; 3291 3292 // Do a prepass over the constraints, canonicalizing them, and building up the 3293 // ConstraintOperands list. 3294 std::vector<InlineAsm::ConstraintInfo> 3295 ConstraintInfos = IA->ParseConstraints(); 3296 3297 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output 3298 // constraint. If so, we can't let the register allocator allocate any input 3299 // registers, because it will not know to avoid the earlyclobbered output reg. 3300 bool SawEarlyClobber = false; 3301 3302 unsigned OpNo = 1; // OpNo - The operand of the CallInst. 3303 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 3304 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i])); 3305 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 3306 3307 MVT::ValueType OpVT = MVT::Other; 3308 3309 // Compute the value type for each operand. 3310 switch (OpInfo.Type) { 3311 case InlineAsm::isOutput: 3312 if (!OpInfo.isIndirect) { 3313 // The return value of the call is this value. As such, there is no 3314 // corresponding argument. 3315 assert(I.getType() != Type::VoidTy && "Bad inline asm!"); 3316 OpVT = TLI.getValueType(I.getType()); 3317 } else { 3318 OpInfo.CallOperandVal = I.getOperand(OpNo++); 3319 } 3320 break; 3321 case InlineAsm::isInput: 3322 OpInfo.CallOperandVal = I.getOperand(OpNo++); 3323 break; 3324 case InlineAsm::isClobber: 3325 // Nothing to do. 3326 break; 3327 } 3328 3329 // If this is an input or an indirect output, process the call argument. 3330 if (OpInfo.CallOperandVal) { 3331 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 3332 const Type *OpTy = OpInfo.CallOperandVal->getType(); 3333 // If this is an indirect operand, the operand is a pointer to the 3334 // accessed type. 3335 if (OpInfo.isIndirect) 3336 OpTy = cast<PointerType>(OpTy)->getElementType(); 3337 3338 // If OpTy is not a first-class value, it may be a struct/union that we 3339 // can tile with integers. 3340 if (!OpTy->isFirstClassType() && OpTy->isSized()) { 3341 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 3342 switch (BitSize) { 3343 default: break; 3344 case 1: 3345 case 8: 3346 case 16: 3347 case 32: 3348 case 64: 3349 OpTy = IntegerType::get(BitSize); 3350 break; 3351 } 3352 } 3353 3354 OpVT = TLI.getValueType(OpTy, true); 3355 } 3356 3357 OpInfo.ConstraintVT = OpVT; 3358 3359 // Compute the constraint code and ConstraintType to use. 3360 OpInfo.ComputeConstraintToUse(TLI); 3361 3362 // Keep track of whether we see an earlyclobber. 3363 SawEarlyClobber |= OpInfo.isEarlyClobber; 3364 3365 // If this is a memory input, and if the operand is not indirect, do what we 3366 // need to to provide an address for the memory input. 3367 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 3368 !OpInfo.isIndirect) { 3369 assert(OpInfo.Type == InlineAsm::isInput && 3370 "Can only indirectify direct input operands!"); 3371 3372 // Memory operands really want the address of the value. If we don't have 3373 // an indirect input, put it in the constpool if we can, otherwise spill 3374 // it to a stack slot. 3375 3376 // If the operand is a float, integer, or vector constant, spill to a 3377 // constant pool entry to get its address. 3378 Value *OpVal = OpInfo.CallOperandVal; 3379 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 3380 isa<ConstantVector>(OpVal)) { 3381 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 3382 TLI.getPointerTy()); 3383 } else { 3384 // Otherwise, create a stack slot and emit a store to it before the 3385 // asm. 3386 const Type *Ty = OpVal->getType(); 3387 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty); 3388 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 3389 MachineFunction &MF = DAG.getMachineFunction(); 3390 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align); 3391 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 3392 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0); 3393 OpInfo.CallOperand = StackSlot; 3394 } 3395 3396 // There is no longer a Value* corresponding to this operand. 3397 OpInfo.CallOperandVal = 0; 3398 // It is now an indirect operand. 3399 OpInfo.isIndirect = true; 3400 } 3401 3402 // If this constraint is for a specific register, allocate it before 3403 // anything else. 3404 if (OpInfo.ConstraintType == TargetLowering::C_Register) 3405 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs); 3406 } 3407 ConstraintInfos.clear(); 3408 3409 3410 // Second pass - Loop over all of the operands, assigning virtual or physregs 3411 // to registerclass operands. 3412 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 3413 AsmOperandInfo &OpInfo = ConstraintOperands[i]; 3414 3415 // C_Register operands have already been allocated, Other/Memory don't need 3416 // to be. 3417 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 3418 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs); 3419 } 3420 3421 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 3422 std::vector<SDOperand> AsmNodeOperands; 3423 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain 3424 AsmNodeOperands.push_back( 3425 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other)); 3426 3427 3428 // Loop over all of the inputs, copying the operand values into the 3429 // appropriate registers and processing the output regs. 3430 RegsForValue RetValRegs; 3431 3432 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 3433 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 3434 3435 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 3436 AsmOperandInfo &OpInfo = ConstraintOperands[i]; 3437 3438 switch (OpInfo.Type) { 3439 case InlineAsm::isOutput: { 3440 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 3441 OpInfo.ConstraintType != TargetLowering::C_Register) { 3442 // Memory output, or 'other' output (e.g. 'X' constraint). 3443 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 3444 3445 // Add information to the INLINEASM node to know about this output. 3446 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 3447 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 3448 TLI.getPointerTy())); 3449 AsmNodeOperands.push_back(OpInfo.CallOperand); 3450 break; 3451 } 3452 3453 // Otherwise, this is a register or register class output. 3454 3455 // Copy the output from the appropriate register. Find a register that 3456 // we can use. 3457 if (OpInfo.AssignedRegs.Regs.empty()) { 3458 cerr << "Couldn't allocate output reg for contraint '" 3459 << OpInfo.ConstraintCode << "'!\n"; 3460 exit(1); 3461 } 3462 3463 if (!OpInfo.isIndirect) { 3464 // This is the result value of the call. 3465 assert(RetValRegs.Regs.empty() && 3466 "Cannot have multiple output constraints yet!"); 3467 assert(I.getType() != Type::VoidTy && "Bad inline asm!"); 3468 RetValRegs = OpInfo.AssignedRegs; 3469 } else { 3470 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 3471 OpInfo.CallOperandVal)); 3472 } 3473 3474 // Add information to the INLINEASM node to know that this register is 3475 // set. 3476 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, 3477 AsmNodeOperands); 3478 break; 3479 } 3480 case InlineAsm::isInput: { 3481 SDOperand InOperandVal = OpInfo.CallOperand; 3482 3483 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint? 3484 // If this is required to match an output register we have already set, 3485 // just use its register. 3486 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str()); 3487 3488 // Scan until we find the definition we already emitted of this operand. 3489 // When we find it, create a RegsForValue operand. 3490 unsigned CurOp = 2; // The first operand. 3491 for (; OperandNo; --OperandNo) { 3492 // Advance to the next operand. 3493 unsigned NumOps = 3494 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 3495 assert(((NumOps & 7) == 2 /*REGDEF*/ || 3496 (NumOps & 7) == 4 /*MEM*/) && 3497 "Skipped past definitions?"); 3498 CurOp += (NumOps>>3)+1; 3499 } 3500 3501 unsigned NumOps = 3502 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 3503 if ((NumOps & 7) == 2 /*REGDEF*/) { 3504 // Add NumOps>>3 registers to MatchedRegs. 3505 RegsForValue MatchedRegs; 3506 MatchedRegs.ValueVT = InOperandVal.getValueType(); 3507 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType(); 3508 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) { 3509 unsigned Reg = 3510 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg(); 3511 MatchedRegs.Regs.push_back(Reg); 3512 } 3513 3514 // Use the produced MatchedRegs object to 3515 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, 3516 TLI.getPointerTy()); 3517 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands); 3518 break; 3519 } else { 3520 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!"); 3521 assert(0 && "matching constraints for memory operands unimp"); 3522 } 3523 } 3524 3525 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 3526 assert(!OpInfo.isIndirect && 3527 "Don't know how to handle indirect other inputs yet!"); 3528 3529 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal, 3530 OpInfo.ConstraintCode[0], 3531 DAG); 3532 if (!InOperandVal.Val) { 3533 cerr << "Invalid operand for inline asm constraint '" 3534 << OpInfo.ConstraintCode << "'!\n"; 3535 exit(1); 3536 } 3537 3538 // Add information to the INLINEASM node to know about this input. 3539 unsigned ResOpType = 3 /*IMM*/ | (1 << 3); 3540 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 3541 TLI.getPointerTy())); 3542 AsmNodeOperands.push_back(InOperandVal); 3543 break; 3544 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 3545 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 3546 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 3547 "Memory operands expect pointer values"); 3548 3549 // Add information to the INLINEASM node to know about this input. 3550 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 3551 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 3552 TLI.getPointerTy())); 3553 AsmNodeOperands.push_back(InOperandVal); 3554 break; 3555 } 3556 3557 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 3558 OpInfo.ConstraintType == TargetLowering::C_Register) && 3559 "Unknown constraint type!"); 3560 assert(!OpInfo.isIndirect && 3561 "Don't know how to handle indirect register inputs yet!"); 3562 3563 // Copy the input into the appropriate registers. 3564 assert(!OpInfo.AssignedRegs.Regs.empty() && 3565 "Couldn't allocate input reg!"); 3566 3567 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, 3568 TLI.getPointerTy()); 3569 3570 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, 3571 AsmNodeOperands); 3572 break; 3573 } 3574 case InlineAsm::isClobber: { 3575 // Add the clobbered value to the operand list, so that the register 3576 // allocator is aware that the physreg got clobbered. 3577 if (!OpInfo.AssignedRegs.Regs.empty()) 3578 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, 3579 AsmNodeOperands); 3580 break; 3581 } 3582 } 3583 } 3584 3585 // Finish up input operands. 3586 AsmNodeOperands[0] = Chain; 3587 if (Flag.Val) AsmNodeOperands.push_back(Flag); 3588 3589 Chain = DAG.getNode(ISD::INLINEASM, 3590 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2, 3591 &AsmNodeOperands[0], AsmNodeOperands.size()); 3592 Flag = Chain.getValue(1); 3593 3594 // If this asm returns a register value, copy the result from that register 3595 // and set it as the value of the call. 3596 if (!RetValRegs.Regs.empty()) { 3597 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag); 3598 3599 // If the result of the inline asm is a vector, it may have the wrong 3600 // width/num elts. Make sure to convert it to the right type with 3601 // vbit_convert. 3602 if (Val.getValueType() == MVT::Vector) { 3603 const VectorType *VTy = cast<VectorType>(I.getType()); 3604 unsigned DesiredNumElts = VTy->getNumElements(); 3605 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType()); 3606 3607 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val, 3608 DAG.getConstant(DesiredNumElts, MVT::i32), 3609 DAG.getValueType(DesiredEltVT)); 3610 } 3611 3612 setValue(&I, Val); 3613 } 3614 3615 std::vector<std::pair<SDOperand, Value*> > StoresToEmit; 3616 3617 // Process indirect outputs, first output all of the flagged copies out of 3618 // physregs. 3619 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 3620 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 3621 Value *Ptr = IndirectStoresToEmit[i].second; 3622 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag); 3623 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 3624 } 3625 3626 // Emit the non-flagged stores from the physregs. 3627 SmallVector<SDOperand, 8> OutChains; 3628 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) 3629 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first, 3630 getValue(StoresToEmit[i].second), 3631 StoresToEmit[i].second, 0)); 3632 if (!OutChains.empty()) 3633 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 3634 &OutChains[0], OutChains.size()); 3635 DAG.setRoot(Chain); 3636} 3637 3638 3639void SelectionDAGLowering::visitMalloc(MallocInst &I) { 3640 SDOperand Src = getValue(I.getOperand(0)); 3641 3642 MVT::ValueType IntPtr = TLI.getPointerTy(); 3643 3644 if (IntPtr < Src.getValueType()) 3645 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src); 3646 else if (IntPtr > Src.getValueType()) 3647 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src); 3648 3649 // Scale the source by the type size. 3650 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType()); 3651 Src = DAG.getNode(ISD::MUL, Src.getValueType(), 3652 Src, getIntPtrConstant(ElementSize)); 3653 3654 TargetLowering::ArgListTy Args; 3655 TargetLowering::ArgListEntry Entry; 3656 Entry.Node = Src; 3657 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 3658 Args.push_back(Entry); 3659 3660 std::pair<SDOperand,SDOperand> Result = 3661 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true, 3662 DAG.getExternalSymbol("malloc", IntPtr), 3663 Args, DAG); 3664 setValue(&I, Result.first); // Pointers always fit in registers 3665 DAG.setRoot(Result.second); 3666} 3667 3668void SelectionDAGLowering::visitFree(FreeInst &I) { 3669 TargetLowering::ArgListTy Args; 3670 TargetLowering::ArgListEntry Entry; 3671 Entry.Node = getValue(I.getOperand(0)); 3672 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 3673 Args.push_back(Entry); 3674 MVT::ValueType IntPtr = TLI.getPointerTy(); 3675 std::pair<SDOperand,SDOperand> Result = 3676 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true, 3677 DAG.getExternalSymbol("free", IntPtr), Args, DAG); 3678 DAG.setRoot(Result.second); 3679} 3680 3681// InsertAtEndOfBasicBlock - This method should be implemented by targets that 3682// mark instructions with the 'usesCustomDAGSchedInserter' flag. These 3683// instructions are special in various ways, which require special support to 3684// insert. The specified MachineInstr is created but not inserted into any 3685// basic blocks, and the scheduler passes ownership of it to this method. 3686MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI, 3687 MachineBasicBlock *MBB) { 3688 cerr << "If a target marks an instruction with " 3689 << "'usesCustomDAGSchedInserter', it must implement " 3690 << "TargetLowering::InsertAtEndOfBasicBlock!\n"; 3691 abort(); 3692 return 0; 3693} 3694 3695void SelectionDAGLowering::visitVAStart(CallInst &I) { 3696 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 3697 getValue(I.getOperand(1)), 3698 DAG.getSrcValue(I.getOperand(1)))); 3699} 3700 3701void SelectionDAGLowering::visitVAArg(VAArgInst &I) { 3702 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(), 3703 getValue(I.getOperand(0)), 3704 DAG.getSrcValue(I.getOperand(0))); 3705 setValue(&I, V); 3706 DAG.setRoot(V.getValue(1)); 3707} 3708 3709void SelectionDAGLowering::visitVAEnd(CallInst &I) { 3710 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(), 3711 getValue(I.getOperand(1)), 3712 DAG.getSrcValue(I.getOperand(1)))); 3713} 3714 3715void SelectionDAGLowering::visitVACopy(CallInst &I) { 3716 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 3717 getValue(I.getOperand(1)), 3718 getValue(I.getOperand(2)), 3719 DAG.getSrcValue(I.getOperand(1)), 3720 DAG.getSrcValue(I.getOperand(2)))); 3721} 3722 3723/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either 3724/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate. 3725static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg, 3726 unsigned &i, SelectionDAG &DAG, 3727 TargetLowering &TLI) { 3728 if (TLI.getTypeAction(VT) != TargetLowering::Expand) 3729 return SDOperand(Arg, i++); 3730 3731 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT); 3732 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT); 3733 if (NumVals == 1) { 3734 return DAG.getNode(ISD::BIT_CONVERT, VT, 3735 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI)); 3736 } else if (NumVals == 2) { 3737 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI); 3738 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI); 3739 if (!TLI.isLittleEndian()) 3740 std::swap(Lo, Hi); 3741 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi); 3742 } else { 3743 // Value scalarized into many values. Unimp for now. 3744 assert(0 && "Cannot expand i64 -> i16 yet!"); 3745 } 3746 return SDOperand(); 3747} 3748 3749/// TargetLowering::LowerArguments - This is the default LowerArguments 3750/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all 3751/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 3752/// integrated into SDISel. 3753std::vector<SDOperand> 3754TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) { 3755 const FunctionType *FTy = F.getFunctionType(); 3756 const ParamAttrsList *Attrs = FTy->getParamAttrs(); 3757 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node. 3758 std::vector<SDOperand> Ops; 3759 Ops.push_back(DAG.getRoot()); 3760 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy())); 3761 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy())); 3762 3763 // Add one result value for each formal argument. 3764 std::vector<MVT::ValueType> RetVals; 3765 unsigned j = 1; 3766 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 3767 I != E; ++I, ++j) { 3768 MVT::ValueType VT = getValueType(I->getType()); 3769 unsigned Flags = ISD::ParamFlags::NoFlagSet; 3770 unsigned OriginalAlignment = 3771 getTargetData()->getABITypeAlignment(I->getType()); 3772 3773 // FIXME: Distinguish between a formal with no [sz]ext attribute from one 3774 // that is zero extended! 3775 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt)) 3776 Flags &= ~(ISD::ParamFlags::SExt); 3777 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt)) 3778 Flags |= ISD::ParamFlags::SExt; 3779 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg)) 3780 Flags |= ISD::ParamFlags::InReg; 3781 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet)) 3782 Flags |= ISD::ParamFlags::StructReturn; 3783 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs); 3784 3785 switch (getTypeAction(VT)) { 3786 default: assert(0 && "Unknown type action!"); 3787 case Legal: 3788 RetVals.push_back(VT); 3789 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3790 break; 3791 case Promote: 3792 RetVals.push_back(getTypeToTransformTo(VT)); 3793 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3794 break; 3795 case Expand: 3796 if (VT != MVT::Vector) { 3797 // If this is a large integer, it needs to be broken up into small 3798 // integers. Figure out what the destination type is and how many small 3799 // integers it turns into. 3800 MVT::ValueType NVT = getTypeToExpandTo(VT); 3801 unsigned NumVals = getNumElements(VT); 3802 for (unsigned i = 0; i != NumVals; ++i) { 3803 RetVals.push_back(NVT); 3804 // if it isn't first piece, alignment must be 1 3805 if (i > 0) 3806 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) | 3807 (1 << ISD::ParamFlags::OrigAlignmentOffs); 3808 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3809 } 3810 } else { 3811 // Otherwise, this is a vector type. We only support legal vectors 3812 // right now. 3813 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements(); 3814 const Type *EltTy = cast<VectorType>(I->getType())->getElementType(); 3815 3816 // Figure out if there is a Packed type corresponding to this Vector 3817 // type. If so, convert to the vector type. 3818 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems); 3819 if (TVT != MVT::Other && isTypeLegal(TVT)) { 3820 RetVals.push_back(TVT); 3821 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3822 } else { 3823 assert(0 && "Don't support illegal by-val vector arguments yet!"); 3824 } 3825 } 3826 break; 3827 } 3828 } 3829 3830 RetVals.push_back(MVT::Other); 3831 3832 // Create the node. 3833 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, 3834 DAG.getNodeValueTypes(RetVals), RetVals.size(), 3835 &Ops[0], Ops.size()).Val; 3836 3837 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1)); 3838 3839 // Set up the return result vector. 3840 Ops.clear(); 3841 unsigned i = 0; 3842 unsigned Idx = 1; 3843 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 3844 ++I, ++Idx) { 3845 MVT::ValueType VT = getValueType(I->getType()); 3846 3847 switch (getTypeAction(VT)) { 3848 default: assert(0 && "Unknown type action!"); 3849 case Legal: 3850 Ops.push_back(SDOperand(Result, i++)); 3851 break; 3852 case Promote: { 3853 SDOperand Op(Result, i++); 3854 if (MVT::isInteger(VT)) { 3855 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt)) 3856 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op, 3857 DAG.getValueType(VT)); 3858 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt)) 3859 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op, 3860 DAG.getValueType(VT)); 3861 Op = DAG.getNode(ISD::TRUNCATE, VT, Op); 3862 } else { 3863 assert(MVT::isFloatingPoint(VT) && "Not int or FP?"); 3864 Op = DAG.getNode(ISD::FP_ROUND, VT, Op); 3865 } 3866 Ops.push_back(Op); 3867 break; 3868 } 3869 case Expand: 3870 if (VT != MVT::Vector) { 3871 // If this is a large integer or a floating point node that needs to be 3872 // expanded, it needs to be reassembled from small integers. Figure out 3873 // what the source elt type is and how many small integers it is. 3874 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this)); 3875 } else { 3876 // Otherwise, this is a vector type. We only support legal vectors 3877 // right now. 3878 const VectorType *PTy = cast<VectorType>(I->getType()); 3879 unsigned NumElems = PTy->getNumElements(); 3880 const Type *EltTy = PTy->getElementType(); 3881 3882 // Figure out if there is a Packed type corresponding to this Vector 3883 // type. If so, convert to the vector type. 3884 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems); 3885 if (TVT != MVT::Other && isTypeLegal(TVT)) { 3886 SDOperand N = SDOperand(Result, i++); 3887 // Handle copies from generic vectors to registers. 3888 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N, 3889 DAG.getConstant(NumElems, MVT::i32), 3890 DAG.getValueType(getValueType(EltTy))); 3891 Ops.push_back(N); 3892 } else { 3893 assert(0 && "Don't support illegal by-val vector arguments yet!"); 3894 abort(); 3895 } 3896 } 3897 break; 3898 } 3899 } 3900 return Ops; 3901} 3902 3903 3904/// ExpandScalarCallArgs - Recursively expand call argument node by 3905/// bit_converting it or extract a pair of elements from the larger node. 3906static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg, 3907 unsigned Flags, 3908 SmallVector<SDOperand, 32> &Ops, 3909 SelectionDAG &DAG, 3910 TargetLowering &TLI, 3911 bool isFirst = true) { 3912 3913 if (TLI.getTypeAction(VT) != TargetLowering::Expand) { 3914 // if it isn't first piece, alignment must be 1 3915 if (!isFirst) 3916 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) | 3917 (1 << ISD::ParamFlags::OrigAlignmentOffs); 3918 Ops.push_back(Arg); 3919 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3920 return; 3921 } 3922 3923 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT); 3924 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT); 3925 if (NumVals == 1) { 3926 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg); 3927 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst); 3928 } else if (NumVals == 2) { 3929 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg, 3930 DAG.getConstant(0, TLI.getPointerTy())); 3931 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg, 3932 DAG.getConstant(1, TLI.getPointerTy())); 3933 if (!TLI.isLittleEndian()) 3934 std::swap(Lo, Hi); 3935 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst); 3936 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false); 3937 } else { 3938 // Value scalarized into many values. Unimp for now. 3939 assert(0 && "Cannot expand i64 -> i16 yet!"); 3940 } 3941} 3942 3943/// TargetLowering::LowerCallTo - This is the default LowerCallTo 3944/// implementation, which just inserts an ISD::CALL node, which is later custom 3945/// lowered by the target to something concrete. FIXME: When all targets are 3946/// migrated to using ISD::CALL, this hook should be integrated into SDISel. 3947std::pair<SDOperand, SDOperand> 3948TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, 3949 bool RetTyIsSigned, bool isVarArg, 3950 unsigned CallingConv, bool isTailCall, 3951 SDOperand Callee, 3952 ArgListTy &Args, SelectionDAG &DAG) { 3953 SmallVector<SDOperand, 32> Ops; 3954 Ops.push_back(Chain); // Op#0 - Chain 3955 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC 3956 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg 3957 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail 3958 Ops.push_back(Callee); 3959 3960 // Handle all of the outgoing arguments. 3961 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 3962 MVT::ValueType VT = getValueType(Args[i].Ty); 3963 SDOperand Op = Args[i].Node; 3964 unsigned Flags = ISD::ParamFlags::NoFlagSet; 3965 unsigned OriginalAlignment = 3966 getTargetData()->getABITypeAlignment(Args[i].Ty); 3967 3968 if (Args[i].isSExt) 3969 Flags |= ISD::ParamFlags::SExt; 3970 if (Args[i].isZExt) 3971 Flags |= ISD::ParamFlags::ZExt; 3972 if (Args[i].isInReg) 3973 Flags |= ISD::ParamFlags::InReg; 3974 if (Args[i].isSRet) 3975 Flags |= ISD::ParamFlags::StructReturn; 3976 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs; 3977 3978 switch (getTypeAction(VT)) { 3979 default: assert(0 && "Unknown type action!"); 3980 case Legal: 3981 Ops.push_back(Op); 3982 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 3983 break; 3984 case Promote: 3985 if (MVT::isInteger(VT)) { 3986 unsigned ExtOp; 3987 if (Args[i].isSExt) 3988 ExtOp = ISD::SIGN_EXTEND; 3989 else if (Args[i].isZExt) 3990 ExtOp = ISD::ZERO_EXTEND; 3991 else 3992 ExtOp = ISD::ANY_EXTEND; 3993 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op); 3994 } else { 3995 assert(MVT::isFloatingPoint(VT) && "Not int or FP?"); 3996 // A true promotion would change the size of the argument. 3997 // Instead, pretend this is an int. If FP objects are not 3998 // passed the same as ints, the original type should be Legal 3999 // and we should not get here. 4000 Op = DAG.getNode(ISD::BIT_CONVERT, 4001 VT==MVT::f32 ? MVT::i32 : 4002 (VT==MVT::f64 ? MVT::i64 : 4003 MVT::Other), 4004 Op); 4005 } 4006 Ops.push_back(Op); 4007 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 4008 break; 4009 case Expand: 4010 if (VT != MVT::Vector) { 4011 // If this is a large integer, it needs to be broken down into small 4012 // integers. Figure out what the source elt type is and how many small 4013 // integers it is. 4014 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this); 4015 } else { 4016 // Otherwise, this is a vector type. We only support legal vectors 4017 // right now. 4018 const VectorType *PTy = cast<VectorType>(Args[i].Ty); 4019 unsigned NumElems = PTy->getNumElements(); 4020 const Type *EltTy = PTy->getElementType(); 4021 4022 // Figure out if there is a Packed type corresponding to this Vector 4023 // type. If so, convert to the vector type. 4024 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems); 4025 if (TVT != MVT::Other && isTypeLegal(TVT)) { 4026 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type. 4027 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op); 4028 Ops.push_back(Op); 4029 Ops.push_back(DAG.getConstant(Flags, MVT::i32)); 4030 } else { 4031 assert(0 && "Don't support illegal by-val vector call args yet!"); 4032 abort(); 4033 } 4034 } 4035 break; 4036 } 4037 } 4038 4039 // Figure out the result value types. 4040 SmallVector<MVT::ValueType, 4> RetTys; 4041 4042 if (RetTy != Type::VoidTy) { 4043 MVT::ValueType VT = getValueType(RetTy); 4044 switch (getTypeAction(VT)) { 4045 default: assert(0 && "Unknown type action!"); 4046 case Legal: 4047 RetTys.push_back(VT); 4048 break; 4049 case Promote: 4050 RetTys.push_back(getTypeToTransformTo(VT)); 4051 break; 4052 case Expand: 4053 if (VT != MVT::Vector) { 4054 // If this is a large integer, it needs to be reassembled from small 4055 // integers. Figure out what the source elt type is and how many small 4056 // integers it is. 4057 MVT::ValueType NVT = getTypeToExpandTo(VT); 4058 unsigned NumVals = getNumElements(VT); 4059 for (unsigned i = 0; i != NumVals; ++i) 4060 RetTys.push_back(NVT); 4061 } else { 4062 // Otherwise, this is a vector type. We only support legal vectors 4063 // right now. 4064 const VectorType *PTy = cast<VectorType>(RetTy); 4065 unsigned NumElems = PTy->getNumElements(); 4066 const Type *EltTy = PTy->getElementType(); 4067 4068 // Figure out if there is a Packed type corresponding to this Vector 4069 // type. If so, convert to the vector type. 4070 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems); 4071 if (TVT != MVT::Other && isTypeLegal(TVT)) { 4072 RetTys.push_back(TVT); 4073 } else { 4074 assert(0 && "Don't support illegal by-val vector call results yet!"); 4075 abort(); 4076 } 4077 } 4078 } 4079 } 4080 4081 RetTys.push_back(MVT::Other); // Always has a chain. 4082 4083 // Finally, create the CALL node. 4084 SDOperand Res = DAG.getNode(ISD::CALL, 4085 DAG.getVTList(&RetTys[0], RetTys.size()), 4086 &Ops[0], Ops.size()); 4087 4088 // This returns a pair of operands. The first element is the 4089 // return value for the function (if RetTy is not VoidTy). The second 4090 // element is the outgoing token chain. 4091 SDOperand ResVal; 4092 if (RetTys.size() != 1) { 4093 MVT::ValueType VT = getValueType(RetTy); 4094 if (RetTys.size() == 2) { 4095 ResVal = Res; 4096 4097 // If this value was promoted, truncate it down. 4098 if (ResVal.getValueType() != VT) { 4099 if (VT == MVT::Vector) { 4100 // Insert a VBIT_CONVERT to convert from the packed result type to the 4101 // MVT::Vector type. 4102 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements(); 4103 const Type *EltTy = cast<VectorType>(RetTy)->getElementType(); 4104 4105 // Figure out if there is a Packed type corresponding to this Vector 4106 // type. If so, convert to the vector type. 4107 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems); 4108 if (TVT != MVT::Other && isTypeLegal(TVT)) { 4109 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a 4110 // "N x PTyElementVT" MVT::Vector type. 4111 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal, 4112 DAG.getConstant(NumElems, MVT::i32), 4113 DAG.getValueType(getValueType(EltTy))); 4114 } else { 4115 abort(); 4116 } 4117 } else if (MVT::isInteger(VT)) { 4118 unsigned AssertOp = ISD::AssertSext; 4119 if (!RetTyIsSigned) 4120 AssertOp = ISD::AssertZext; 4121 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal, 4122 DAG.getValueType(VT)); 4123 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal); 4124 } else { 4125 assert(MVT::isFloatingPoint(VT)); 4126 if (getTypeAction(VT) == Expand) 4127 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal); 4128 else 4129 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal); 4130 } 4131 } 4132 } else if (RetTys.size() == 3) { 4133 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT, 4134 Res.getValue(0), Res.getValue(1)); 4135 4136 } else { 4137 assert(0 && "Case not handled yet!"); 4138 } 4139 } 4140 4141 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1)); 4142} 4143 4144SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) { 4145 assert(0 && "LowerOperation not implemented for this target!"); 4146 abort(); 4147 return SDOperand(); 4148} 4149 4150SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op, 4151 SelectionDAG &DAG) { 4152 assert(0 && "CustomPromoteOperation not implemented for this target!"); 4153 abort(); 4154 return SDOperand(); 4155} 4156 4157/// getMemsetValue - Vectorized representation of the memset value 4158/// operand. 4159static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT, 4160 SelectionDAG &DAG) { 4161 MVT::ValueType CurVT = VT; 4162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 4163 uint64_t Val = C->getValue() & 255; 4164 unsigned Shift = 8; 4165 while (CurVT != MVT::i8) { 4166 Val = (Val << Shift) | Val; 4167 Shift <<= 1; 4168 CurVT = (MVT::ValueType)((unsigned)CurVT - 1); 4169 } 4170 return DAG.getConstant(Val, VT); 4171 } else { 4172 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value); 4173 unsigned Shift = 8; 4174 while (CurVT != MVT::i8) { 4175 Value = 4176 DAG.getNode(ISD::OR, VT, 4177 DAG.getNode(ISD::SHL, VT, Value, 4178 DAG.getConstant(Shift, MVT::i8)), Value); 4179 Shift <<= 1; 4180 CurVT = (MVT::ValueType)((unsigned)CurVT - 1); 4181 } 4182 4183 return Value; 4184 } 4185} 4186 4187/// getMemsetStringVal - Similar to getMemsetValue. Except this is only 4188/// used when a memcpy is turned into a memset when the source is a constant 4189/// string ptr. 4190static SDOperand getMemsetStringVal(MVT::ValueType VT, 4191 SelectionDAG &DAG, TargetLowering &TLI, 4192 std::string &Str, unsigned Offset) { 4193 uint64_t Val = 0; 4194 unsigned MSB = MVT::getSizeInBits(VT) / 8; 4195 if (TLI.isLittleEndian()) 4196 Offset = Offset + MSB - 1; 4197 for (unsigned i = 0; i != MSB; ++i) { 4198 Val = (Val << 8) | (unsigned char)Str[Offset]; 4199 Offset += TLI.isLittleEndian() ? -1 : 1; 4200 } 4201 return DAG.getConstant(Val, VT); 4202} 4203 4204/// getMemBasePlusOffset - Returns base and offset node for the 4205static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset, 4206 SelectionDAG &DAG, TargetLowering &TLI) { 4207 MVT::ValueType VT = Base.getValueType(); 4208 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT)); 4209} 4210 4211/// MeetsMaxMemopRequirement - Determines if the number of memory ops required 4212/// to replace the memset / memcpy is below the threshold. It also returns the 4213/// types of the sequence of memory ops to perform memset / memcpy. 4214static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps, 4215 unsigned Limit, uint64_t Size, 4216 unsigned Align, TargetLowering &TLI) { 4217 MVT::ValueType VT; 4218 4219 if (TLI.allowsUnalignedMemoryAccesses()) { 4220 VT = MVT::i64; 4221 } else { 4222 switch (Align & 7) { 4223 case 0: 4224 VT = MVT::i64; 4225 break; 4226 case 4: 4227 VT = MVT::i32; 4228 break; 4229 case 2: 4230 VT = MVT::i16; 4231 break; 4232 default: 4233 VT = MVT::i8; 4234 break; 4235 } 4236 } 4237 4238 MVT::ValueType LVT = MVT::i64; 4239 while (!TLI.isTypeLegal(LVT)) 4240 LVT = (MVT::ValueType)((unsigned)LVT - 1); 4241 assert(MVT::isInteger(LVT)); 4242 4243 if (VT > LVT) 4244 VT = LVT; 4245 4246 unsigned NumMemOps = 0; 4247 while (Size != 0) { 4248 unsigned VTSize = MVT::getSizeInBits(VT) / 8; 4249 while (VTSize > Size) { 4250 VT = (MVT::ValueType)((unsigned)VT - 1); 4251 VTSize >>= 1; 4252 } 4253 assert(MVT::isInteger(VT)); 4254 4255 if (++NumMemOps > Limit) 4256 return false; 4257 MemOps.push_back(VT); 4258 Size -= VTSize; 4259 } 4260 4261 return true; 4262} 4263 4264void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) { 4265 SDOperand Op1 = getValue(I.getOperand(1)); 4266 SDOperand Op2 = getValue(I.getOperand(2)); 4267 SDOperand Op3 = getValue(I.getOperand(3)); 4268 SDOperand Op4 = getValue(I.getOperand(4)); 4269 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue(); 4270 if (Align == 0) Align = 1; 4271 4272 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) { 4273 std::vector<MVT::ValueType> MemOps; 4274 4275 // Expand memset / memcpy to a series of load / store ops 4276 // if the size operand falls below a certain threshold. 4277 SmallVector<SDOperand, 8> OutChains; 4278 switch (Op) { 4279 default: break; // Do nothing for now. 4280 case ISD::MEMSET: { 4281 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(), 4282 Size->getValue(), Align, TLI)) { 4283 unsigned NumMemOps = MemOps.size(); 4284 unsigned Offset = 0; 4285 for (unsigned i = 0; i < NumMemOps; i++) { 4286 MVT::ValueType VT = MemOps[i]; 4287 unsigned VTSize = MVT::getSizeInBits(VT) / 8; 4288 SDOperand Value = getMemsetValue(Op2, VT, DAG); 4289 SDOperand Store = DAG.getStore(getRoot(), Value, 4290 getMemBasePlusOffset(Op1, Offset, DAG, TLI), 4291 I.getOperand(1), Offset); 4292 OutChains.push_back(Store); 4293 Offset += VTSize; 4294 } 4295 } 4296 break; 4297 } 4298 case ISD::MEMCPY: { 4299 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(), 4300 Size->getValue(), Align, TLI)) { 4301 unsigned NumMemOps = MemOps.size(); 4302 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0; 4303 GlobalAddressSDNode *G = NULL; 4304 std::string Str; 4305 bool CopyFromStr = false; 4306 4307 if (Op2.getOpcode() == ISD::GlobalAddress) 4308 G = cast<GlobalAddressSDNode>(Op2); 4309 else if (Op2.getOpcode() == ISD::ADD && 4310 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress && 4311 Op2.getOperand(1).getOpcode() == ISD::Constant) { 4312 G = cast<GlobalAddressSDNode>(Op2.getOperand(0)); 4313 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue(); 4314 } 4315 if (G) { 4316 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal()); 4317 if (GV && GV->isConstant()) { 4318 Str = GV->getStringValue(false); 4319 if (!Str.empty()) { 4320 CopyFromStr = true; 4321 SrcOff += SrcDelta; 4322 } 4323 } 4324 } 4325 4326 for (unsigned i = 0; i < NumMemOps; i++) { 4327 MVT::ValueType VT = MemOps[i]; 4328 unsigned VTSize = MVT::getSizeInBits(VT) / 8; 4329 SDOperand Value, Chain, Store; 4330 4331 if (CopyFromStr) { 4332 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff); 4333 Chain = getRoot(); 4334 Store = 4335 DAG.getStore(Chain, Value, 4336 getMemBasePlusOffset(Op1, DstOff, DAG, TLI), 4337 I.getOperand(1), DstOff); 4338 } else { 4339 Value = DAG.getLoad(VT, getRoot(), 4340 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI), 4341 I.getOperand(2), SrcOff); 4342 Chain = Value.getValue(1); 4343 Store = 4344 DAG.getStore(Chain, Value, 4345 getMemBasePlusOffset(Op1, DstOff, DAG, TLI), 4346 I.getOperand(1), DstOff); 4347 } 4348 OutChains.push_back(Store); 4349 SrcOff += VTSize; 4350 DstOff += VTSize; 4351 } 4352 } 4353 break; 4354 } 4355 } 4356 4357 if (!OutChains.empty()) { 4358 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, 4359 &OutChains[0], OutChains.size())); 4360 return; 4361 } 4362 } 4363 4364 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4)); 4365} 4366 4367//===----------------------------------------------------------------------===// 4368// SelectionDAGISel code 4369//===----------------------------------------------------------------------===// 4370 4371unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) { 4372 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 4373} 4374 4375void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 4376 AU.addRequired<AliasAnalysis>(); 4377 AU.setPreservesAll(); 4378} 4379 4380 4381 4382bool SelectionDAGISel::runOnFunction(Function &Fn) { 4383 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine()); 4384 RegMap = MF.getSSARegMap(); 4385 DOUT << "\n\n\n=== " << Fn.getName() << "\n"; 4386 4387 FunctionLoweringInfo FuncInfo(TLI, Fn, MF); 4388 4389 if (ExceptionHandling) 4390 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 4391 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator())) 4392 // Mark landing pad. 4393 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); 4394 4395 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 4396 SelectBasicBlock(I, MF, FuncInfo); 4397 4398 // Add function live-ins to entry block live-in set. 4399 BasicBlock *EntryBB = &Fn.getEntryBlock(); 4400 BB = FuncInfo.MBBMap[EntryBB]; 4401 if (!MF.livein_empty()) 4402 for (MachineFunction::livein_iterator I = MF.livein_begin(), 4403 E = MF.livein_end(); I != E; ++I) 4404 BB->addLiveIn(I->first); 4405 4406 return true; 4407} 4408 4409SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, 4410 unsigned Reg) { 4411 SDOperand Op = getValue(V); 4412 assert((Op.getOpcode() != ISD::CopyFromReg || 4413 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 4414 "Copy from a reg to the same reg!"); 4415 4416 // If this type is not legal, we must make sure to not create an invalid 4417 // register use. 4418 MVT::ValueType SrcVT = Op.getValueType(); 4419 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT); 4420 if (SrcVT == DestVT) { 4421 return DAG.getCopyToReg(getRoot(), Reg, Op); 4422 } else if (SrcVT == MVT::Vector) { 4423 // Handle copies from generic vectors to registers. 4424 MVT::ValueType PTyElementVT, PTyLegalElementVT; 4425 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()), 4426 PTyElementVT, PTyLegalElementVT); 4427 uint64_t SrcVL = cast<ConstantSDNode>(*(Op.Val->op_end()-2))->getValue(); 4428 4429 // Loop over all of the elements of the resultant vector, 4430 // VEXTRACT_VECTOR_ELT'ing or VEXTRACT_SUBVECTOR'ing them, converting them 4431 // to PTyLegalElementVT, then copying them into output registers. 4432 SmallVector<SDOperand, 8> OutChains; 4433 SDOperand Root = getRoot(); 4434 for (unsigned i = 0; i != NE; ++i) { 4435 SDOperand Elt = MVT::isVector(PTyElementVT) ? 4436 DAG.getNode(ISD::VEXTRACT_SUBVECTOR, PTyElementVT, 4437 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) : 4438 DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT, 4439 Op, DAG.getConstant(i, TLI.getPointerTy())); 4440 if (PTyElementVT == PTyLegalElementVT) { 4441 // Elements are legal. 4442 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt)); 4443 } else if (PTyLegalElementVT > PTyElementVT) { 4444 // Elements are promoted. 4445 if (MVT::isFloatingPoint(PTyLegalElementVT)) 4446 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt); 4447 else 4448 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt); 4449 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt)); 4450 } else { 4451 // Elements are expanded. 4452 // The src value is expanded into multiple registers. 4453 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT, 4454 Elt, DAG.getConstant(0, TLI.getPointerTy())); 4455 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT, 4456 Elt, DAG.getConstant(1, TLI.getPointerTy())); 4457 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo)); 4458 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi)); 4459 } 4460 } 4461 return DAG.getNode(ISD::TokenFactor, MVT::Other, 4462 &OutChains[0], OutChains.size()); 4463 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) { 4464 // The src value is promoted to the register. 4465 if (MVT::isFloatingPoint(SrcVT)) 4466 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op); 4467 else 4468 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op); 4469 return DAG.getCopyToReg(getRoot(), Reg, Op); 4470 } else { 4471 DestVT = TLI.getTypeToExpandTo(SrcVT); 4472 unsigned NumVals = TLI.getNumElements(SrcVT); 4473 if (NumVals == 1) 4474 return DAG.getCopyToReg(getRoot(), Reg, 4475 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op)); 4476 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!"); 4477 // The src value is expanded into multiple registers. 4478 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT, 4479 Op, DAG.getConstant(0, TLI.getPointerTy())); 4480 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT, 4481 Op, DAG.getConstant(1, TLI.getPointerTy())); 4482 Op = DAG.getCopyToReg(getRoot(), Reg, Lo); 4483 return DAG.getCopyToReg(Op, Reg+1, Hi); 4484 } 4485} 4486 4487void SelectionDAGISel:: 4488LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL, 4489 std::vector<SDOperand> &UnorderedChains) { 4490 // If this is the entry block, emit arguments. 4491 Function &F = *LLVMBB->getParent(); 4492 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo; 4493 SDOperand OldRoot = SDL.DAG.getRoot(); 4494 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG); 4495 4496 unsigned a = 0; 4497 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 4498 AI != E; ++AI, ++a) 4499 if (!AI->use_empty()) { 4500 SDL.setValue(AI, Args[a]); 4501 4502 // If this argument is live outside of the entry block, insert a copy from 4503 // whereever we got it to the vreg that other BB's will reference it as. 4504 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI); 4505 if (VMI != FuncInfo.ValueMap.end()) { 4506 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second); 4507 UnorderedChains.push_back(Copy); 4508 } 4509 } 4510 4511 // Finally, if the target has anything special to do, allow it to do so. 4512 // FIXME: this should insert code into the DAG! 4513 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction()); 4514} 4515 4516void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB, 4517 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate, 4518 FunctionLoweringInfo &FuncInfo) { 4519 SelectionDAGLowering SDL(DAG, TLI, FuncInfo); 4520 4521 std::vector<SDOperand> UnorderedChains; 4522 4523 // Lower any arguments needed in this block if this is the entry block. 4524 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock()) 4525 LowerArguments(LLVMBB, SDL, UnorderedChains); 4526 4527 BB = FuncInfo.MBBMap[LLVMBB]; 4528 SDL.setCurrentBasicBlock(BB); 4529 4530 if (ExceptionHandling && BB->isLandingPad()) { 4531 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4532 4533 if (MMI) { 4534 // Add a label to mark the beginning of the landing pad. Deletion of the 4535 // landing pad can thus be detected via the MachineModuleInfo. 4536 unsigned LabelID = MMI->addLandingPad(BB); 4537 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(), 4538 DAG.getConstant(LabelID, MVT::i32))); 4539 } 4540 } 4541 4542 // Lower all of the non-terminator instructions. 4543 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end(); 4544 I != E; ++I) 4545 SDL.visit(*I); 4546 4547 // Ensure that all instructions which are used outside of their defining 4548 // blocks are available as virtual registers. Invoke is handled elsewhere. 4549 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I) 4550 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) { 4551 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I); 4552 if (VMI != FuncInfo.ValueMap.end()) 4553 UnorderedChains.push_back( 4554 SDL.CopyValueToVirtualRegister(I, VMI->second)); 4555 } 4556 4557 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 4558 // ensure constants are generated when needed. Remember the virtual registers 4559 // that need to be added to the Machine PHI nodes as input. We cannot just 4560 // directly add them, because expansion might result in multiple MBB's for one 4561 // BB. As such, the start of the BB might correspond to a different MBB than 4562 // the end. 4563 // 4564 TerminatorInst *TI = LLVMBB->getTerminator(); 4565 4566 // Emit constants only once even if used by multiple PHI nodes. 4567 std::map<Constant*, unsigned> ConstantsOut; 4568 4569 // Vector bool would be better, but vector<bool> is really slow. 4570 std::vector<unsigned char> SuccsHandled; 4571 if (TI->getNumSuccessors()) 4572 SuccsHandled.resize(BB->getParent()->getNumBlockIDs()); 4573 4574 // Check successor nodes PHI nodes that expect a constant to be available from 4575 // this block. 4576 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 4577 BasicBlock *SuccBB = TI->getSuccessor(succ); 4578 if (!isa<PHINode>(SuccBB->begin())) continue; 4579 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 4580 4581 // If this terminator has multiple identical successors (common for 4582 // switches), only handle each succ once. 4583 unsigned SuccMBBNo = SuccMBB->getNumber(); 4584 if (SuccsHandled[SuccMBBNo]) continue; 4585 SuccsHandled[SuccMBBNo] = true; 4586 4587 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 4588 PHINode *PN; 4589 4590 // At this point we know that there is a 1-1 correspondence between LLVM PHI 4591 // nodes and Machine PHI nodes, but the incoming operands have not been 4592 // emitted yet. 4593 for (BasicBlock::iterator I = SuccBB->begin(); 4594 (PN = dyn_cast<PHINode>(I)); ++I) { 4595 // Ignore dead phi's. 4596 if (PN->use_empty()) continue; 4597 4598 unsigned Reg; 4599 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 4600 4601 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 4602 unsigned &RegOut = ConstantsOut[C]; 4603 if (RegOut == 0) { 4604 RegOut = FuncInfo.CreateRegForValue(C); 4605 UnorderedChains.push_back( 4606 SDL.CopyValueToVirtualRegister(C, RegOut)); 4607 } 4608 Reg = RegOut; 4609 } else { 4610 Reg = FuncInfo.ValueMap[PHIOp]; 4611 if (Reg == 0) { 4612 assert(isa<AllocaInst>(PHIOp) && 4613 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 4614 "Didn't codegen value into a register!??"); 4615 Reg = FuncInfo.CreateRegForValue(PHIOp); 4616 UnorderedChains.push_back( 4617 SDL.CopyValueToVirtualRegister(PHIOp, Reg)); 4618 } 4619 } 4620 4621 // Remember that this register needs to added to the machine PHI node as 4622 // the input for this MBB. 4623 MVT::ValueType VT = TLI.getValueType(PN->getType()); 4624 unsigned NumElements; 4625 if (VT != MVT::Vector) 4626 NumElements = TLI.getNumElements(VT); 4627 else { 4628 MVT::ValueType VT1,VT2; 4629 NumElements = 4630 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()), 4631 VT1, VT2); 4632 } 4633 for (unsigned i = 0, e = NumElements; i != e; ++i) 4634 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 4635 } 4636 } 4637 ConstantsOut.clear(); 4638 4639 // Turn all of the unordered chains into one factored node. 4640 if (!UnorderedChains.empty()) { 4641 SDOperand Root = SDL.getRoot(); 4642 if (Root.getOpcode() != ISD::EntryToken) { 4643 unsigned i = 0, e = UnorderedChains.size(); 4644 for (; i != e; ++i) { 4645 assert(UnorderedChains[i].Val->getNumOperands() > 1); 4646 if (UnorderedChains[i].Val->getOperand(0) == Root) 4647 break; // Don't add the root if we already indirectly depend on it. 4648 } 4649 4650 if (i == e) 4651 UnorderedChains.push_back(Root); 4652 } 4653 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, 4654 &UnorderedChains[0], UnorderedChains.size())); 4655 } 4656 4657 // Lower the terminator after the copies are emitted. 4658 SDL.visit(*LLVMBB->getTerminator()); 4659 4660 // Copy over any CaseBlock records that may now exist due to SwitchInst 4661 // lowering, as well as any jump table information. 4662 SwitchCases.clear(); 4663 SwitchCases = SDL.SwitchCases; 4664 JTCases.clear(); 4665 JTCases = SDL.JTCases; 4666 BitTestCases.clear(); 4667 BitTestCases = SDL.BitTestCases; 4668 4669 // Make sure the root of the DAG is up-to-date. 4670 DAG.setRoot(SDL.getRoot()); 4671} 4672 4673void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) { 4674 // Get alias analysis for load/store combining. 4675 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 4676 4677 // Run the DAG combiner in pre-legalize mode. 4678 DAG.Combine(false, AA); 4679 4680 DOUT << "Lowered selection DAG:\n"; 4681 DEBUG(DAG.dump()); 4682 4683 // Second step, hack on the DAG until it only uses operations and types that 4684 // the target supports. 4685 DAG.Legalize(); 4686 4687 DOUT << "Legalized selection DAG:\n"; 4688 DEBUG(DAG.dump()); 4689 4690 // Run the DAG combiner in post-legalize mode. 4691 DAG.Combine(true, AA); 4692 4693 if (ViewISelDAGs) DAG.viewGraph(); 4694 4695 // Third, instruction select all of the operations to machine code, adding the 4696 // code to the MachineBasicBlock. 4697 InstructionSelectBasicBlock(DAG); 4698 4699 DOUT << "Selected machine code:\n"; 4700 DEBUG(BB->dump()); 4701} 4702 4703void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF, 4704 FunctionLoweringInfo &FuncInfo) { 4705 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate; 4706 { 4707 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4708 CurDAG = &DAG; 4709 4710 // First step, lower LLVM code to some DAG. This DAG may use operations and 4711 // types that are not supported by the target. 4712 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo); 4713 4714 // Second step, emit the lowered DAG as machine code. 4715 CodeGenAndEmitDAG(DAG); 4716 } 4717 4718 DOUT << "Total amount of phi nodes to update: " 4719 << PHINodesToUpdate.size() << "\n"; 4720 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) 4721 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first 4722 << ", " << PHINodesToUpdate[i].second << ")\n";); 4723 4724 // Next, now that we know what the last MBB the LLVM BB expanded is, update 4725 // PHI nodes in successors. 4726 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) { 4727 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 4728 MachineInstr *PHI = PHINodesToUpdate[i].first; 4729 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4730 "This is not a machine PHI node that we are updating!"); 4731 PHI->addRegOperand(PHINodesToUpdate[i].second, false); 4732 PHI->addMachineBasicBlockOperand(BB); 4733 } 4734 return; 4735 } 4736 4737 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) { 4738 // Lower header first, if it wasn't already lowered 4739 if (!BitTestCases[i].Emitted) { 4740 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4741 CurDAG = &HSDAG; 4742 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo); 4743 // Set the current basic block to the mbb we wish to insert the code into 4744 BB = BitTestCases[i].Parent; 4745 HSDL.setCurrentBasicBlock(BB); 4746 // Emit the code 4747 HSDL.visitBitTestHeader(BitTestCases[i]); 4748 HSDAG.setRoot(HSDL.getRoot()); 4749 CodeGenAndEmitDAG(HSDAG); 4750 } 4751 4752 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) { 4753 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4754 CurDAG = &BSDAG; 4755 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo); 4756 // Set the current basic block to the mbb we wish to insert the code into 4757 BB = BitTestCases[i].Cases[j].ThisBB; 4758 BSDL.setCurrentBasicBlock(BB); 4759 // Emit the code 4760 if (j+1 != ej) 4761 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB, 4762 BitTestCases[i].Reg, 4763 BitTestCases[i].Cases[j]); 4764 else 4765 BSDL.visitBitTestCase(BitTestCases[i].Default, 4766 BitTestCases[i].Reg, 4767 BitTestCases[i].Cases[j]); 4768 4769 4770 BSDAG.setRoot(BSDL.getRoot()); 4771 CodeGenAndEmitDAG(BSDAG); 4772 } 4773 4774 // Update PHI Nodes 4775 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) { 4776 MachineInstr *PHI = PHINodesToUpdate[pi].first; 4777 MachineBasicBlock *PHIBB = PHI->getParent(); 4778 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4779 "This is not a machine PHI node that we are updating!"); 4780 // This is "default" BB. We have two jumps to it. From "header" BB and 4781 // from last "case" BB. 4782 if (PHIBB == BitTestCases[i].Default) { 4783 PHI->addRegOperand(PHINodesToUpdate[pi].second, false); 4784 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent); 4785 PHI->addRegOperand(PHINodesToUpdate[pi].second, false); 4786 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB); 4787 } 4788 // One of "cases" BB. 4789 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) { 4790 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB; 4791 if (cBB->succ_end() != 4792 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) { 4793 PHI->addRegOperand(PHINodesToUpdate[pi].second, false); 4794 PHI->addMachineBasicBlockOperand(cBB); 4795 } 4796 } 4797 } 4798 } 4799 4800 // If the JumpTable record is filled in, then we need to emit a jump table. 4801 // Updating the PHI nodes is tricky in this case, since we need to determine 4802 // whether the PHI is a successor of the range check MBB or the jump table MBB 4803 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) { 4804 // Lower header first, if it wasn't already lowered 4805 if (!JTCases[i].first.Emitted) { 4806 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4807 CurDAG = &HSDAG; 4808 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo); 4809 // Set the current basic block to the mbb we wish to insert the code into 4810 BB = JTCases[i].first.HeaderBB; 4811 HSDL.setCurrentBasicBlock(BB); 4812 // Emit the code 4813 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first); 4814 HSDAG.setRoot(HSDL.getRoot()); 4815 CodeGenAndEmitDAG(HSDAG); 4816 } 4817 4818 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4819 CurDAG = &JSDAG; 4820 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo); 4821 // Set the current basic block to the mbb we wish to insert the code into 4822 BB = JTCases[i].second.MBB; 4823 JSDL.setCurrentBasicBlock(BB); 4824 // Emit the code 4825 JSDL.visitJumpTable(JTCases[i].second); 4826 JSDAG.setRoot(JSDL.getRoot()); 4827 CodeGenAndEmitDAG(JSDAG); 4828 4829 // Update PHI Nodes 4830 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) { 4831 MachineInstr *PHI = PHINodesToUpdate[pi].first; 4832 MachineBasicBlock *PHIBB = PHI->getParent(); 4833 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4834 "This is not a machine PHI node that we are updating!"); 4835 // "default" BB. We can go there only from header BB. 4836 if (PHIBB == JTCases[i].second.Default) { 4837 PHI->addRegOperand(PHINodesToUpdate[pi].second, false); 4838 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB); 4839 } 4840 // JT BB. Just iterate over successors here 4841 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) { 4842 PHI->addRegOperand(PHINodesToUpdate[pi].second, false); 4843 PHI->addMachineBasicBlockOperand(BB); 4844 } 4845 } 4846 } 4847 4848 // If the switch block involved a branch to one of the actual successors, we 4849 // need to update PHI nodes in that block. 4850 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 4851 MachineInstr *PHI = PHINodesToUpdate[i].first; 4852 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4853 "This is not a machine PHI node that we are updating!"); 4854 if (BB->isSuccessor(PHI->getParent())) { 4855 PHI->addRegOperand(PHINodesToUpdate[i].second, false); 4856 PHI->addMachineBasicBlockOperand(BB); 4857 } 4858 } 4859 4860 // If we generated any switch lowering information, build and codegen any 4861 // additional DAGs necessary. 4862 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) { 4863 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4864 CurDAG = &SDAG; 4865 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo); 4866 4867 // Set the current basic block to the mbb we wish to insert the code into 4868 BB = SwitchCases[i].ThisBB; 4869 SDL.setCurrentBasicBlock(BB); 4870 4871 // Emit the code 4872 SDL.visitSwitchCase(SwitchCases[i]); 4873 SDAG.setRoot(SDL.getRoot()); 4874 CodeGenAndEmitDAG(SDAG); 4875 4876 // Handle any PHI nodes in successors of this chunk, as if we were coming 4877 // from the original BB before switch expansion. Note that PHI nodes can 4878 // occur multiple times in PHINodesToUpdate. We have to be very careful to 4879 // handle them the right number of times. 4880 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS. 4881 for (MachineBasicBlock::iterator Phi = BB->begin(); 4882 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){ 4883 // This value for this PHI node is recorded in PHINodesToUpdate, get it. 4884 for (unsigned pn = 0; ; ++pn) { 4885 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!"); 4886 if (PHINodesToUpdate[pn].first == Phi) { 4887 Phi->addRegOperand(PHINodesToUpdate[pn].second, false); 4888 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB); 4889 break; 4890 } 4891 } 4892 } 4893 4894 // Don't process RHS if same block as LHS. 4895 if (BB == SwitchCases[i].FalseBB) 4896 SwitchCases[i].FalseBB = 0; 4897 4898 // If we haven't handled the RHS, do so now. Otherwise, we're done. 4899 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB; 4900 SwitchCases[i].FalseBB = 0; 4901 } 4902 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0); 4903 } 4904} 4905 4906 4907//===----------------------------------------------------------------------===// 4908/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each 4909/// target node in the graph. 4910void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) { 4911 if (ViewSchedDAGs) DAG.viewGraph(); 4912 4913 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault(); 4914 4915 if (!Ctor) { 4916 Ctor = ISHeuristic; 4917 RegisterScheduler::setDefault(Ctor); 4918 } 4919 4920 ScheduleDAG *SL = Ctor(this, &DAG, BB); 4921 BB = SL->Run(); 4922 delete SL; 4923} 4924 4925 4926HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { 4927 return new HazardRecognizer(); 4928} 4929 4930//===----------------------------------------------------------------------===// 4931// Helper functions used by the generated instruction selector. 4932//===----------------------------------------------------------------------===// 4933// Calls to these methods are generated by tblgen. 4934 4935/// CheckAndMask - The isel is trying to match something like (and X, 255). If 4936/// the dag combiner simplified the 255, we still want to match. RHS is the 4937/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 4938/// specified in the .td file (e.g. 255). 4939bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS, 4940 int64_t DesiredMaskS) { 4941 uint64_t ActualMask = RHS->getValue(); 4942 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType()); 4943 4944 // If the actual mask exactly matches, success! 4945 if (ActualMask == DesiredMask) 4946 return true; 4947 4948 // If the actual AND mask is allowing unallowed bits, this doesn't match. 4949 if (ActualMask & ~DesiredMask) 4950 return false; 4951 4952 // Otherwise, the DAG Combiner may have proven that the value coming in is 4953 // either already zero or is not demanded. Check for known zero input bits. 4954 uint64_t NeededMask = DesiredMask & ~ActualMask; 4955 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask)) 4956 return true; 4957 4958 // TODO: check to see if missing bits are just not demanded. 4959 4960 // Otherwise, this pattern doesn't match. 4961 return false; 4962} 4963 4964/// CheckOrMask - The isel is trying to match something like (or X, 255). If 4965/// the dag combiner simplified the 255, we still want to match. RHS is the 4966/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 4967/// specified in the .td file (e.g. 255). 4968bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS, 4969 int64_t DesiredMaskS) { 4970 uint64_t ActualMask = RHS->getValue(); 4971 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType()); 4972 4973 // If the actual mask exactly matches, success! 4974 if (ActualMask == DesiredMask) 4975 return true; 4976 4977 // If the actual AND mask is allowing unallowed bits, this doesn't match. 4978 if (ActualMask & ~DesiredMask) 4979 return false; 4980 4981 // Otherwise, the DAG Combiner may have proven that the value coming in is 4982 // either already zero or is not demanded. Check for known zero input bits. 4983 uint64_t NeededMask = DesiredMask & ~ActualMask; 4984 4985 uint64_t KnownZero, KnownOne; 4986 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne); 4987 4988 // If all the missing bits in the or are already known to be set, match! 4989 if ((NeededMask & KnownOne) == NeededMask) 4990 return true; 4991 4992 // TODO: check to see if missing bits are just not demanded. 4993 4994 // Otherwise, this pattern doesn't match. 4995 return false; 4996} 4997 4998 4999/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 5000/// by tblgen. Others should not call it. 5001void SelectionDAGISel:: 5002SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) { 5003 std::vector<SDOperand> InOps; 5004 std::swap(InOps, Ops); 5005 5006 Ops.push_back(InOps[0]); // input chain. 5007 Ops.push_back(InOps[1]); // input asm string. 5008 5009 unsigned i = 2, e = InOps.size(); 5010 if (InOps[e-1].getValueType() == MVT::Flag) 5011 --e; // Don't process a flag operand if it is here. 5012 5013 while (i != e) { 5014 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue(); 5015 if ((Flags & 7) != 4 /*MEM*/) { 5016 // Just skip over this operand, copying the operands verbatim. 5017 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1); 5018 i += (Flags >> 3) + 1; 5019 } else { 5020 assert((Flags >> 3) == 1 && "Memory operand with multiple values?"); 5021 // Otherwise, this is a memory operand. Ask the target to select it. 5022 std::vector<SDOperand> SelOps; 5023 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) { 5024 cerr << "Could not match memory address. Inline asm failure!\n"; 5025 exit(1); 5026 } 5027 5028 // Add this to the output node. 5029 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy(); 5030 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3), 5031 IntPtrTy)); 5032 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 5033 i += 2; 5034 } 5035 } 5036 5037 // Add the flag input back if present. 5038 if (e != InOps.size()) 5039 Ops.push_back(InOps.back()); 5040} 5041 5042char SelectionDAGISel::ID = 0; 5043