1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
40 // Temporary command line code to enable use of the dag combiner as a beta
47 CombineDAG("enable-dag-combiner", cl::Hidden,
48 cl::desc("Run the DAG combiner before and after Legalize"),
49 cl::location(CombinerEnabled),
54 ViewDAGs("view-isel-dags", cl::Hidden,
55 cl::desc("Pop up a window to show isel dags as they are selected"));
57 static const bool ViewDAGs = 0;
62 //===--------------------------------------------------------------------===//
63 /// FunctionLoweringInfo - This contains information that is global to a
64 /// function that is used when lowering a region of the function.
65 class FunctionLoweringInfo {
72 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
74 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
75 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
77 /// ValueMap - Since we emit code for the function a basic block at a time,
78 /// we must remember which virtual registers hold the values for
79 /// cross-basic-block values.
80 std::map<const Value*, unsigned> ValueMap;
82 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
83 /// the entry block. This allows the allocas to be efficiently referenced
84 /// anywhere in the function.
85 std::map<const AllocaInst*, int> StaticAllocaMap;
87 /// BlockLocalArguments - If any arguments are only used in a single basic
88 /// block, and if the target can access the arguments without side-effects,
89 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
90 /// track of which arguments are local to each BB.
91 std::multimap<BasicBlock*, std::pair<Argument*,
92 unsigned> > BlockLocalArguments;
95 unsigned MakeReg(MVT::ValueType VT) {
96 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
99 unsigned CreateRegForValue(const Value *V) {
100 MVT::ValueType VT = TLI.getValueType(V->getType());
101 // The common case is that we will only create one register for this
102 // value. If we have that case, create and return the virtual register.
103 unsigned NV = TLI.getNumElements(VT);
105 // If we are promoting this value, pick the next largest supported type.
106 return MakeReg(TLI.getTypeToTransformTo(VT));
109 // If this value is represented with multiple target registers, make sure
110 // to create enough consequtive registers of the right (smaller) type.
111 unsigned NT = VT-1; // Find the type to use.
112 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
115 unsigned R = MakeReg((MVT::ValueType)NT);
116 for (unsigned i = 1; i != NV; ++i)
117 MakeReg((MVT::ValueType)NT);
121 unsigned InitializeRegForValue(const Value *V) {
122 unsigned &R = ValueMap[V];
123 assert(R == 0 && "Already initialized this value register!");
124 return R = CreateRegForValue(V);
129 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
130 /// PHI nodes or outside of the basic block that defines it.
131 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
132 if (isa<PHINode>(I)) return true;
133 BasicBlock *BB = I->getParent();
134 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
135 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
140 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
141 Function &fn, MachineFunction &mf)
142 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
144 // Initialize the mapping of values to registers. This is only set up for
145 // instruction values that are used outside of the block that defines
147 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
149 InitializeRegForValue(AI);
151 Function::iterator BB = Fn.begin(), E = Fn.end();
152 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
153 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
154 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
155 const Type *Ty = AI->getAllocatedType();
156 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
157 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
159 // If the alignment of the value is smaller than the size of the value,
160 // and if the size of the value is particularly small (<= 8 bytes),
161 // round up to the size of the value for potentially better performance.
163 // FIXME: This could be made better with a preferred alignment hook in
164 // TargetData. It serves primarily to 8-byte align doubles for X86.
165 if (Align < TySize && TySize <= 8) Align = TySize;
167 if (CUI->getValue()) // Don't produce zero sized stack objects
168 TySize *= CUI->getValue(); // Get total allocated size.
169 StaticAllocaMap[AI] =
170 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
173 for (; BB != E; ++BB)
174 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
175 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
176 if (!isa<AllocaInst>(I) ||
177 !StaticAllocaMap.count(cast<AllocaInst>(I)))
178 InitializeRegForValue(I);
180 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
181 // also creates the initial PHI MachineInstrs, though none of the input
182 // operands are populated.
183 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
184 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
186 MF.getBasicBlockList().push_back(MBB);
188 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
191 for (BasicBlock::iterator I = BB->begin();
192 (PN = dyn_cast<PHINode>(I)); ++I)
193 if (!PN->use_empty()) {
194 unsigned NumElements =
195 TLI.getNumElements(TLI.getValueType(PN->getType()));
196 unsigned PHIReg = ValueMap[PN];
197 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
198 for (unsigned i = 0; i != NumElements; ++i)
199 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
206 //===----------------------------------------------------------------------===//
207 /// SelectionDAGLowering - This is the common target-independent lowering
208 /// implementation that is parameterized by a TargetLowering object.
209 /// Also, targets can overload any lowering method.
212 class SelectionDAGLowering {
213 MachineBasicBlock *CurMBB;
215 std::map<const Value*, SDOperand> NodeMap;
217 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
218 /// them up and then emit token factor nodes when possible. This allows us to
219 /// get simple disambiguation between loads without worrying about alias
221 std::vector<SDOperand> PendingLoads;
224 // TLI - This is information that describes the available target features we
225 // need for lowering. This indicates when operations are unavailable,
226 // implemented with a libcall, etc.
229 const TargetData &TD;
231 /// FuncInfo - Information about the function as a whole.
233 FunctionLoweringInfo &FuncInfo;
235 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
236 FunctionLoweringInfo &funcinfo)
237 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
241 /// getRoot - Return the current virtual root of the Selection DAG.
243 SDOperand getRoot() {
244 if (PendingLoads.empty())
245 return DAG.getRoot();
247 if (PendingLoads.size() == 1) {
248 SDOperand Root = PendingLoads[0];
250 PendingLoads.clear();
254 // Otherwise, we have to make a token factor node.
255 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
256 PendingLoads.clear();
261 void visit(Instruction &I) { visit(I.getOpcode(), I); }
263 void visit(unsigned Opcode, User &I) {
265 default: assert(0 && "Unknown instruction type encountered!");
267 // Build the switch statement using the Instruction.def file.
268 #define HANDLE_INST(NUM, OPCODE, CLASS) \
269 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
270 #include "llvm/Instruction.def"
274 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
277 SDOperand getIntPtrConstant(uint64_t Val) {
278 return DAG.getConstant(Val, TLI.getPointerTy());
281 SDOperand getValue(const Value *V) {
282 SDOperand &N = NodeMap[V];
285 MVT::ValueType VT = TLI.getValueType(V->getType());
286 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
287 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
288 visit(CE->getOpcode(), *CE);
289 assert(N.Val && "visit didn't populate the ValueMap!");
291 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
292 return N = DAG.getGlobalAddress(GV, VT);
293 } else if (isa<ConstantPointerNull>(C)) {
294 return N = DAG.getConstant(0, TLI.getPointerTy());
295 } else if (isa<UndefValue>(C)) {
296 return N = DAG.getNode(ISD::UNDEF, VT);
297 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
298 return N = DAG.getConstantFP(CFP->getValue(), VT);
300 // Canonicalize all constant ints to be unsigned.
301 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
304 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
305 std::map<const AllocaInst*, int>::iterator SI =
306 FuncInfo.StaticAllocaMap.find(AI);
307 if (SI != FuncInfo.StaticAllocaMap.end())
308 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
311 std::map<const Value*, unsigned>::const_iterator VMI =
312 FuncInfo.ValueMap.find(V);
313 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
315 unsigned InReg = VMI->second;
317 // If this type is not legal, make it so now.
318 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
320 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
322 // Source must be expanded. This input value is actually coming from the
323 // register pair VMI->second and VMI->second+1.
324 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
325 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
327 if (DestVT > VT) { // Promotion case
328 if (MVT::isFloatingPoint(VT))
329 N = DAG.getNode(ISD::FP_ROUND, VT, N);
331 N = DAG.getNode(ISD::TRUNCATE, VT, N);
338 const SDOperand &setValue(const Value *V, SDOperand NewN) {
339 SDOperand &N = NodeMap[V];
340 assert(N.Val == 0 && "Already set a value for this node!");
344 // Terminator instructions.
345 void visitRet(ReturnInst &I);
346 void visitBr(BranchInst &I);
347 void visitUnreachable(UnreachableInst &I) { /* noop */ }
349 // These all get lowered before this pass.
350 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
351 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
352 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
355 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
356 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
357 void visitSub(User &I);
358 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
359 void visitDiv(User &I) {
360 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
362 void visitRem(User &I) {
363 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
365 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
366 void visitOr (User &I) { visitBinary(I, ISD::OR); }
367 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
368 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
369 void visitShr(User &I) {
370 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
373 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
374 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
375 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
376 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
377 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
378 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
379 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
381 void visitGetElementPtr(User &I);
382 void visitCast(User &I);
383 void visitSelect(User &I);
386 void visitMalloc(MallocInst &I);
387 void visitFree(FreeInst &I);
388 void visitAlloca(AllocaInst &I);
389 void visitLoad(LoadInst &I);
390 void visitStore(StoreInst &I);
391 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
392 void visitCall(CallInst &I);
394 void visitVAStart(CallInst &I);
395 void visitVAArg(VAArgInst &I);
396 void visitVAEnd(CallInst &I);
397 void visitVACopy(CallInst &I);
398 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
400 void visitMemIntrinsic(CallInst &I, unsigned Op);
402 void visitUserOp1(Instruction &I) {
403 assert(0 && "UserOp1 should not exist at instruction selection time!");
406 void visitUserOp2(Instruction &I) {
407 assert(0 && "UserOp2 should not exist at instruction selection time!");
411 } // end namespace llvm
413 void SelectionDAGLowering::visitRet(ReturnInst &I) {
414 if (I.getNumOperands() == 0) {
415 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
419 SDOperand Op1 = getValue(I.getOperand(0));
420 MVT::ValueType TmpVT;
422 switch (Op1.getValueType()) {
423 default: assert(0 && "Unknown value type!");
428 // If this is a machine where 32-bits is legal or expanded, promote to
429 // 32-bits, otherwise, promote to 64-bits.
430 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
431 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
435 // Extend integer types to result type.
436 if (I.getOperand(0)->getType()->isSigned())
437 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
439 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
444 break; // No extension needed!
447 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
450 void SelectionDAGLowering::visitBr(BranchInst &I) {
451 // Update machine-CFG edges.
452 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
454 // Figure out which block is immediately after the current one.
455 MachineBasicBlock *NextBlock = 0;
456 MachineFunction::iterator BBI = CurMBB;
457 if (++BBI != CurMBB->getParent()->end())
460 if (I.isUnconditional()) {
461 // If this is not a fall-through branch, emit the branch.
462 if (Succ0MBB != NextBlock)
463 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
464 DAG.getBasicBlock(Succ0MBB)));
466 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
468 SDOperand Cond = getValue(I.getCondition());
469 if (Succ1MBB == NextBlock) {
470 // If the condition is false, fall through. This means we should branch
471 // if the condition is true to Succ #0.
472 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
473 Cond, DAG.getBasicBlock(Succ0MBB)));
474 } else if (Succ0MBB == NextBlock) {
475 // If the condition is true, fall through. This means we should branch if
476 // the condition is false to Succ #1. Invert the condition first.
477 SDOperand True = DAG.getConstant(1, Cond.getValueType());
478 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
479 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
480 Cond, DAG.getBasicBlock(Succ1MBB)));
482 std::vector<SDOperand> Ops;
483 Ops.push_back(getRoot());
485 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
486 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
487 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
492 void SelectionDAGLowering::visitSub(User &I) {
494 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
495 if (CFP->isExactlyValue(-0.0)) {
496 SDOperand Op2 = getValue(I.getOperand(1));
497 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
501 visitBinary(I, ISD::SUB);
504 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
505 SDOperand Op1 = getValue(I.getOperand(0));
506 SDOperand Op2 = getValue(I.getOperand(1));
509 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
511 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
514 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
515 ISD::CondCode UnsignedOpcode) {
516 SDOperand Op1 = getValue(I.getOperand(0));
517 SDOperand Op2 = getValue(I.getOperand(1));
518 ISD::CondCode Opcode = SignedOpcode;
519 if (I.getOperand(0)->getType()->isUnsigned())
520 Opcode = UnsignedOpcode;
521 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
524 void SelectionDAGLowering::visitSelect(User &I) {
525 SDOperand Cond = getValue(I.getOperand(0));
526 SDOperand TrueVal = getValue(I.getOperand(1));
527 SDOperand FalseVal = getValue(I.getOperand(2));
528 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
532 void SelectionDAGLowering::visitCast(User &I) {
533 SDOperand N = getValue(I.getOperand(0));
534 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
535 MVT::ValueType DestTy = TLI.getValueType(I.getType());
537 if (N.getValueType() == DestTy) {
538 setValue(&I, N); // noop cast.
539 } else if (DestTy == MVT::i1) {
540 // Cast to bool is a comparison against zero, not truncation to zero.
541 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
542 DAG.getConstantFP(0.0, N.getValueType());
543 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
544 } else if (isInteger(SrcTy)) {
545 if (isInteger(DestTy)) { // Int -> Int cast
546 if (DestTy < SrcTy) // Truncating cast?
547 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
548 else if (I.getOperand(0)->getType()->isSigned())
549 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
551 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
552 } else { // Int -> FP cast
553 if (I.getOperand(0)->getType()->isSigned())
554 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
556 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
559 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
560 if (isFloatingPoint(DestTy)) { // FP -> FP cast
561 if (DestTy < SrcTy) // Rounding cast?
562 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
564 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
565 } else { // FP -> Int cast.
566 if (I.getType()->isSigned())
567 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
569 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
574 void SelectionDAGLowering::visitGetElementPtr(User &I) {
575 SDOperand N = getValue(I.getOperand(0));
576 const Type *Ty = I.getOperand(0)->getType();
577 const Type *UIntPtrTy = TD.getIntPtrType();
579 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
582 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
583 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
586 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
587 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
588 getIntPtrConstant(Offset));
590 Ty = StTy->getElementType(Field);
592 Ty = cast<SequentialType>(Ty)->getElementType();
593 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
594 // N = N + Idx * ElementSize;
595 uint64_t ElementSize = TD.getTypeSize(Ty);
596 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
598 // If the index is smaller or larger than intptr_t, truncate or extend
600 if (IdxN.getValueType() < Scale.getValueType()) {
601 if (Idx->getType()->isSigned())
602 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
604 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
605 } else if (IdxN.getValueType() > Scale.getValueType())
606 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
608 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
609 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
616 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
617 // If this is a fixed sized alloca in the entry block of the function,
618 // allocate it statically on the stack.
619 if (FuncInfo.StaticAllocaMap.count(&I))
620 return; // getValue will auto-populate this.
622 const Type *Ty = I.getAllocatedType();
623 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
624 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
626 SDOperand AllocSize = getValue(I.getArraySize());
627 MVT::ValueType IntPtr = TLI.getPointerTy();
628 if (IntPtr < AllocSize.getValueType())
629 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
630 else if (IntPtr > AllocSize.getValueType())
631 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
633 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
634 getIntPtrConstant(TySize));
636 // Handle alignment. If the requested alignment is less than or equal to the
637 // stack alignment, ignore it and round the size of the allocation up to the
638 // stack alignment size. If the size is greater than the stack alignment, we
639 // note this in the DYNAMIC_STACKALLOC node.
640 unsigned StackAlign =
641 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
642 if (Align <= StackAlign) {
644 // Add SA-1 to the size.
645 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
646 getIntPtrConstant(StackAlign-1));
647 // Mask out the low bits for alignment purposes.
648 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
649 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
652 std::vector<MVT::ValueType> VTs;
653 VTs.push_back(AllocSize.getValueType());
654 VTs.push_back(MVT::Other);
655 std::vector<SDOperand> Ops;
656 Ops.push_back(getRoot());
657 Ops.push_back(AllocSize);
658 Ops.push_back(getIntPtrConstant(Align));
659 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
660 DAG.setRoot(setValue(&I, DSA).getValue(1));
662 // Inform the Frame Information that we have just allocated a variable-sized
664 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
668 void SelectionDAGLowering::visitLoad(LoadInst &I) {
669 SDOperand Ptr = getValue(I.getOperand(0));
675 // Do not serialize non-volatile loads against each other.
676 Root = DAG.getRoot();
679 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
680 DAG.getSrcValue(I.getOperand(0)));
684 DAG.setRoot(L.getValue(1));
686 PendingLoads.push_back(L.getValue(1));
690 void SelectionDAGLowering::visitStore(StoreInst &I) {
691 Value *SrcV = I.getOperand(0);
692 SDOperand Src = getValue(SrcV);
693 SDOperand Ptr = getValue(I.getOperand(1));
694 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
695 DAG.getSrcValue(I.getOperand(1))));
698 void SelectionDAGLowering::visitCall(CallInst &I) {
699 const char *RenameFn = 0;
701 if (Function *F = I.getCalledFunction())
703 switch (F->getIntrinsicID()) {
704 case 0: // Not an LLVM intrinsic.
705 if (F->getName() == "fabs" || F->getName() == "fabsf") {
706 if (I.getNumOperands() == 2 && // Basic sanity checks.
707 I.getOperand(1)->getType()->isFloatingPoint() &&
708 I.getType() == I.getOperand(1)->getType()) {
709 Tmp = getValue(I.getOperand(1));
710 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
714 else if (F->getName() == "sin" || F->getName() == "sinf") {
715 if (I.getNumOperands() == 2 && // Basic sanity checks.
716 I.getOperand(1)->getType()->isFloatingPoint() &&
717 I.getType() == I.getOperand(1)->getType()) {
718 Tmp = getValue(I.getOperand(1));
719 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
723 else if (F->getName() == "cos" || F->getName() == "cosf") {
724 if (I.getNumOperands() == 2 && // Basic sanity checks.
725 I.getOperand(1)->getType()->isFloatingPoint() &&
726 I.getType() == I.getOperand(1)->getType()) {
727 Tmp = getValue(I.getOperand(1));
728 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
733 case Intrinsic::vastart: visitVAStart(I); return;
734 case Intrinsic::vaend: visitVAEnd(I); return;
735 case Intrinsic::vacopy: visitVACopy(I); return;
736 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
737 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
739 case Intrinsic::setjmp:
740 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
742 case Intrinsic::longjmp:
743 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
745 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
746 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
747 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
749 case Intrinsic::readport:
750 case Intrinsic::readio: {
751 std::vector<MVT::ValueType> VTs;
752 VTs.push_back(TLI.getValueType(I.getType()));
753 VTs.push_back(MVT::Other);
754 std::vector<SDOperand> Ops;
755 Ops.push_back(getRoot());
756 Ops.push_back(getValue(I.getOperand(1)));
757 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
758 ISD::READPORT : ISD::READIO, VTs, Ops);
761 DAG.setRoot(Tmp.getValue(1));
764 case Intrinsic::writeport:
765 case Intrinsic::writeio:
766 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
767 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
768 getRoot(), getValue(I.getOperand(1)),
769 getValue(I.getOperand(2))));
771 case Intrinsic::dbg_stoppoint:
772 case Intrinsic::dbg_region_start:
773 case Intrinsic::dbg_region_end:
774 case Intrinsic::dbg_func_start:
775 case Intrinsic::dbg_declare:
776 if (I.getType() != Type::VoidTy)
777 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
780 case Intrinsic::isunordered:
781 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
782 getValue(I.getOperand(2)), ISD::SETUO));
785 case Intrinsic::sqrt:
786 setValue(&I, DAG.getNode(ISD::FSQRT,
787 getValue(I.getOperand(1)).getValueType(),
788 getValue(I.getOperand(1))));
791 case Intrinsic::pcmarker:
792 Tmp = getValue(I.getOperand(1));
793 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
795 case Intrinsic::cttz:
796 setValue(&I, DAG.getNode(ISD::CTTZ,
797 getValue(I.getOperand(1)).getValueType(),
798 getValue(I.getOperand(1))));
800 case Intrinsic::ctlz:
801 setValue(&I, DAG.getNode(ISD::CTLZ,
802 getValue(I.getOperand(1)).getValueType(),
803 getValue(I.getOperand(1))));
805 case Intrinsic::ctpop:
806 setValue(&I, DAG.getNode(ISD::CTPOP,
807 getValue(I.getOperand(1)).getValueType(),
808 getValue(I.getOperand(1))));
812 assert(0 && "This intrinsic is not implemented yet!");
818 Callee = getValue(I.getOperand(0));
820 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
821 std::vector<std::pair<SDOperand, const Type*> > Args;
823 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
824 Value *Arg = I.getOperand(i);
825 SDOperand ArgNode = getValue(Arg);
826 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
829 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
830 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
832 std::pair<SDOperand,SDOperand> Result =
833 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
834 I.isTailCall(), Callee, Args, DAG);
835 if (I.getType() != Type::VoidTy)
836 setValue(&I, Result.first);
837 DAG.setRoot(Result.second);
840 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
841 SDOperand Src = getValue(I.getOperand(0));
843 MVT::ValueType IntPtr = TLI.getPointerTy();
845 if (IntPtr < Src.getValueType())
846 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
847 else if (IntPtr > Src.getValueType())
848 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
850 // Scale the source by the type size.
851 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
852 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
853 Src, getIntPtrConstant(ElementSize));
855 std::vector<std::pair<SDOperand, const Type*> > Args;
856 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
858 std::pair<SDOperand,SDOperand> Result =
859 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
860 DAG.getExternalSymbol("malloc", IntPtr),
862 setValue(&I, Result.first); // Pointers always fit in registers
863 DAG.setRoot(Result.second);
866 void SelectionDAGLowering::visitFree(FreeInst &I) {
867 std::vector<std::pair<SDOperand, const Type*> > Args;
868 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
869 TLI.getTargetData().getIntPtrType()));
870 MVT::ValueType IntPtr = TLI.getPointerTy();
871 std::pair<SDOperand,SDOperand> Result =
872 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
873 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
874 DAG.setRoot(Result.second);
877 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
878 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
879 // instructions are special in various ways, which require special support to
880 // insert. The specified MachineInstr is created but not inserted into any
881 // basic blocks, and the scheduler passes ownership of it to this method.
882 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
883 MachineBasicBlock *MBB) {
884 std::cerr << "If a target marks an instruction with "
885 "'usesCustomDAGSchedInserter', it must implement "
886 "TargetLowering::InsertAtEndOfBasicBlock!\n";
891 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
892 SDOperand VAListP, Value *VAListV,
894 // We have no sane default behavior, just emit a useful error message and bail
896 std::cerr << "Variable arguments handling not implemented on this target!\n";
901 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
903 // Default to a noop.
907 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
908 SDOperand SrcP, Value *SrcV,
909 SDOperand DestP, Value *DestV,
911 // Default to copying the input list.
912 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
913 SrcP, DAG.getSrcValue(SrcV));
914 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
915 Val, DestP, DAG.getSrcValue(DestV));
919 std::pair<SDOperand,SDOperand>
920 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
921 const Type *ArgTy, SelectionDAG &DAG) {
922 // We have no sane default behavior, just emit a useful error message and bail
924 std::cerr << "Variable arguments handling not implemented on this target!\n";
926 return std::make_pair(SDOperand(), SDOperand());
930 void SelectionDAGLowering::visitVAStart(CallInst &I) {
931 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
932 I.getOperand(1), DAG));
935 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
936 std::pair<SDOperand,SDOperand> Result =
937 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
939 setValue(&I, Result.first);
940 DAG.setRoot(Result.second);
943 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
944 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
945 I.getOperand(1), DAG));
948 void SelectionDAGLowering::visitVACopy(CallInst &I) {
950 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
951 getValue(I.getOperand(1)), I.getOperand(1), DAG);
956 // It is always conservatively correct for llvm.returnaddress and
957 // llvm.frameaddress to return 0.
958 std::pair<SDOperand, SDOperand>
959 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
960 unsigned Depth, SelectionDAG &DAG) {
961 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
964 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
965 assert(0 && "LowerOperation not implemented for this target!");
970 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
971 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
972 std::pair<SDOperand,SDOperand> Result =
973 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
974 setValue(&I, Result.first);
975 DAG.setRoot(Result.second);
978 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
979 std::vector<SDOperand> Ops;
980 Ops.push_back(getRoot());
981 Ops.push_back(getValue(I.getOperand(1)));
982 Ops.push_back(getValue(I.getOperand(2)));
983 Ops.push_back(getValue(I.getOperand(3)));
984 Ops.push_back(getValue(I.getOperand(4)));
985 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
988 //===----------------------------------------------------------------------===//
989 // SelectionDAGISel code
990 //===----------------------------------------------------------------------===//
992 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
993 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
996 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
997 // FIXME: we only modify the CFG to split critical edges. This
998 // updates dom and loop info.
1002 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1003 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1004 RegMap = MF.getSSARegMap();
1005 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1007 // First pass, split all critical edges for PHI nodes with incoming values
1008 // that are constants, this way the load of the constant into a vreg will not
1009 // be placed into MBBs that are used some other way.
1010 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1012 for (BasicBlock::iterator BBI = BB->begin();
1013 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1014 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1015 if (isa<Constant>(PN->getIncomingValue(i)))
1016 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1019 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1021 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1022 SelectBasicBlock(I, MF, FuncInfo);
1028 SDOperand SelectionDAGISel::
1029 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1030 SDOperand Op = SDL.getValue(V);
1031 assert((Op.getOpcode() != ISD::CopyFromReg ||
1032 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1033 "Copy from a reg to the same reg!");
1035 // If this type is not legal, we must make sure to not create an invalid
1037 MVT::ValueType SrcVT = Op.getValueType();
1038 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1039 SelectionDAG &DAG = SDL.DAG;
1040 if (SrcVT == DestVT) {
1041 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1042 } else if (SrcVT < DestVT) {
1043 // The src value is promoted to the register.
1044 if (MVT::isFloatingPoint(SrcVT))
1045 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1047 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1048 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1050 // The src value is expanded into multiple registers.
1051 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1052 Op, DAG.getConstant(0, MVT::i32));
1053 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1054 Op, DAG.getConstant(1, MVT::i32));
1055 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1056 return DAG.getCopyToReg(Op, Reg+1, Hi);
1060 /// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1061 /// single basic block, return that block. Otherwise, return a null pointer.
1062 static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1063 if (A->use_empty()) return 0;
1064 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1065 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1067 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1068 return 0; // Disagreement among the users?
1070 // Okay, there is a single BB user. Only permit this optimization if this is
1071 // the entry block, otherwise, we might sink argument loads into loops and
1072 // stuff. Later, when we have global instruction selection, this won't be an
1074 if (BB == BB->getParent()->begin())
1079 void SelectionDAGISel::
1080 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1081 std::vector<SDOperand> &UnorderedChains) {
1082 // If this is the entry block, emit arguments.
1083 Function &F = *BB->getParent();
1084 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1086 if (BB == &F.front()) {
1087 SDOperand OldRoot = SDL.DAG.getRoot();
1089 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1091 // If there were side effects accessing the argument list, do not do
1092 // anything special.
1093 if (OldRoot != SDL.DAG.getRoot()) {
1095 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1097 if (!AI->use_empty()) {
1098 SDL.setValue(AI, Args[a]);
1101 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1102 UnorderedChains.push_back(Copy);
1105 // Otherwise, if any argument is only accessed in a single basic block,
1106 // emit that argument only to that basic block.
1108 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1110 if (!AI->use_empty()) {
1111 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1112 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1113 std::make_pair(AI, a)));
1115 SDL.setValue(AI, Args[a]);
1117 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1118 UnorderedChains.push_back(Copy);
1123 // Next, if the function has live ins that need to be copied into vregs,
1124 // emit the copies now, into the top of the block.
1125 MachineFunction &MF = SDL.DAG.getMachineFunction();
1126 if (MF.livein_begin() != MF.livein_end()) {
1127 SSARegMap *RegMap = MF.getSSARegMap();
1128 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1129 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1130 E = MF.livein_end(); LI != E; ++LI)
1132 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1133 LI->first, RegMap->getRegClass(LI->second));
1136 // Finally, if the target has anything special to do, allow it to do so.
1137 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1140 // See if there are any block-local arguments that need to be emitted in this
1143 if (!FuncInfo.BlockLocalArguments.empty()) {
1144 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1145 FuncInfo.BlockLocalArguments.lower_bound(BB);
1146 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1147 // Lower the arguments into this block.
1148 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1150 // Set up the value mapping for the local arguments.
1151 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1153 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
1155 // Any dead arguments will just be ignored here.
1161 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1162 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1163 FunctionLoweringInfo &FuncInfo) {
1164 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1166 std::vector<SDOperand> UnorderedChains;
1168 // Lower any arguments needed in this block.
1169 LowerArguments(LLVMBB, SDL, UnorderedChains);
1171 BB = FuncInfo.MBBMap[LLVMBB];
1172 SDL.setCurrentBasicBlock(BB);
1174 // Lower all of the non-terminator instructions.
1175 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1179 // Ensure that all instructions which are used outside of their defining
1180 // blocks are available as virtual registers.
1181 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1182 if (!I->use_empty() && !isa<PHINode>(I)) {
1183 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1184 if (VMI != FuncInfo.ValueMap.end())
1185 UnorderedChains.push_back(
1186 CopyValueToVirtualRegister(SDL, I, VMI->second));
1189 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1190 // ensure constants are generated when needed. Remember the virtual registers
1191 // that need to be added to the Machine PHI nodes as input. We cannot just
1192 // directly add them, because expansion might result in multiple MBB's for one
1193 // BB. As such, the start of the BB might correspond to a different MBB than
1197 // Emit constants only once even if used by multiple PHI nodes.
1198 std::map<Constant*, unsigned> ConstantsOut;
1200 // Check successor nodes PHI nodes that expect a constant to be available from
1202 TerminatorInst *TI = LLVMBB->getTerminator();
1203 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1204 BasicBlock *SuccBB = TI->getSuccessor(succ);
1205 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1208 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1209 // nodes and Machine PHI nodes, but the incoming operands have not been
1211 for (BasicBlock::iterator I = SuccBB->begin();
1212 (PN = dyn_cast<PHINode>(I)); ++I)
1213 if (!PN->use_empty()) {
1215 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1216 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1217 unsigned &RegOut = ConstantsOut[C];
1219 RegOut = FuncInfo.CreateRegForValue(C);
1220 UnorderedChains.push_back(
1221 CopyValueToVirtualRegister(SDL, C, RegOut));
1225 Reg = FuncInfo.ValueMap[PHIOp];
1227 assert(isa<AllocaInst>(PHIOp) &&
1228 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1229 "Didn't codegen value into a register!??");
1230 Reg = FuncInfo.CreateRegForValue(PHIOp);
1231 UnorderedChains.push_back(
1232 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1236 // Remember that this register needs to added to the machine PHI node as
1237 // the input for this MBB.
1238 unsigned NumElements =
1239 TLI.getNumElements(TLI.getValueType(PN->getType()));
1240 for (unsigned i = 0, e = NumElements; i != e; ++i)
1241 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1244 ConstantsOut.clear();
1246 // Turn all of the unordered chains into one factored node.
1247 if (!UnorderedChains.empty()) {
1248 UnorderedChains.push_back(SDL.getRoot());
1249 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1252 // Lower the terminator after the copies are emitted.
1253 SDL.visit(*LLVMBB->getTerminator());
1255 // Make sure the root of the DAG is up-to-date.
1256 DAG.setRoot(SDL.getRoot());
1259 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1260 FunctionLoweringInfo &FuncInfo) {
1261 SelectionDAG DAG(TLI, MF);
1263 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1265 // First step, lower LLVM code to some DAG. This DAG may use operations and
1266 // types that are not supported by the target.
1267 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1269 // Run the DAG combiner in pre-legalize mode, if we are told to do so
1270 if (CombinerEnabled) DAG.Combine(false);
1272 DEBUG(std::cerr << "Lowered selection DAG:\n");
1275 // Second step, hack on the DAG until it only uses operations and types that
1276 // the target supports.
1279 DEBUG(std::cerr << "Legalized selection DAG:\n");
1282 if (ViewDAGs) DAG.viewGraph();
1284 // Run the DAG combiner in post-legalize mode, if we are told to do so
1285 if (CombinerEnabled) DAG.Combine(true);
1287 // Third, instruction select all of the operations to machine code, adding the
1288 // code to the MachineBasicBlock.
1289 InstructionSelectBasicBlock(DAG);
1291 DEBUG(std::cerr << "Selected machine code:\n");
1294 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1295 // PHI nodes in successors.
1296 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1297 MachineInstr *PHI = PHINodesToUpdate[i].first;
1298 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1299 "This is not a machine PHI node that we are updating!");
1300 PHI->addRegOperand(PHINodesToUpdate[i].second);
1301 PHI->addMachineBasicBlockOperand(BB);
1304 // Finally, add the CFG edges from the last selected MBB to the successor
1306 TerminatorInst *TI = LLVMBB->getTerminator();
1307 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1308 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1309 BB->addSuccessor(Succ0MBB);