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"
42 ViewDAGs("view-isel-dags", cl::Hidden,
43 cl::desc("Pop up a window to show isel dags as they are selected"));
45 static const bool ViewDAGs = 0;
50 //===--------------------------------------------------------------------===//
51 /// FunctionLoweringInfo - This contains information that is global to a
52 /// function that is used when lowering a region of the function.
53 class FunctionLoweringInfo {
60 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
62 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
65 /// ValueMap - Since we emit code for the function a basic block at a time,
66 /// we must remember which virtual registers hold the values for
67 /// cross-basic-block values.
68 std::map<const Value*, unsigned> ValueMap;
70 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71 /// the entry block. This allows the allocas to be efficiently referenced
72 /// anywhere in the function.
73 std::map<const AllocaInst*, int> StaticAllocaMap;
75 /// BlockLocalArguments - If any arguments are only used in a single basic
76 /// block, and if the target can access the arguments without side-effects,
77 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
78 /// track of which arguments are local to each BB.
79 std::multimap<BasicBlock*, std::pair<Argument*,
80 unsigned> > BlockLocalArguments;
83 unsigned MakeReg(MVT::ValueType VT) {
84 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
87 unsigned CreateRegForValue(const Value *V) {
88 MVT::ValueType VT = TLI.getValueType(V->getType());
89 // The common case is that we will only create one register for this
90 // value. If we have that case, create and return the virtual register.
91 unsigned NV = TLI.getNumElements(VT);
93 // If we are promoting this value, pick the next largest supported type.
94 return MakeReg(TLI.getTypeToTransformTo(VT));
97 // If this value is represented with multiple target registers, make sure
98 // to create enough consequtive registers of the right (smaller) type.
99 unsigned NT = VT-1; // Find the type to use.
100 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
103 unsigned R = MakeReg((MVT::ValueType)NT);
104 for (unsigned i = 1; i != NV; ++i)
105 MakeReg((MVT::ValueType)NT);
109 unsigned InitializeRegForValue(const Value *V) {
110 unsigned &R = ValueMap[V];
111 assert(R == 0 && "Already initialized this value register!");
112 return R = CreateRegForValue(V);
117 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118 /// PHI nodes or outside of the basic block that defines it.
119 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120 if (isa<PHINode>(I)) return true;
121 BasicBlock *BB = I->getParent();
122 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
128 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
129 Function &fn, MachineFunction &mf)
130 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
132 // Initialize the mapping of values to registers. This is only set up for
133 // instruction values that are used outside of the block that defines
135 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137 InitializeRegForValue(AI);
139 Function::iterator BB = Fn.begin(), EB = Fn.end();
140 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
141 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
143 const Type *Ty = AI->getAllocatedType();
144 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
145 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
147 // If the alignment of the value is smaller than the size of the value,
148 // and if the size of the value is particularly small (<= 8 bytes),
149 // round up to the size of the value for potentially better performance.
151 // FIXME: This could be made better with a preferred alignment hook in
152 // TargetData. It serves primarily to 8-byte align doubles for X86.
153 if (Align < TySize && TySize <= 8) Align = TySize;
154 TySize *= CUI->getValue(); // Get total allocated size.
155 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
156 StaticAllocaMap[AI] =
157 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
160 for (; BB != EB; ++BB)
161 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
162 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
163 if (!isa<AllocaInst>(I) ||
164 !StaticAllocaMap.count(cast<AllocaInst>(I)))
165 InitializeRegForValue(I);
167 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
168 // also creates the initial PHI MachineInstrs, though none of the input
169 // operands are populated.
170 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
171 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
173 MF.getBasicBlockList().push_back(MBB);
175 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
178 for (BasicBlock::iterator I = BB->begin();
179 (PN = dyn_cast<PHINode>(I)); ++I)
180 if (!PN->use_empty()) {
181 unsigned NumElements =
182 TLI.getNumElements(TLI.getValueType(PN->getType()));
183 unsigned PHIReg = ValueMap[PN];
184 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
185 for (unsigned i = 0; i != NumElements; ++i)
186 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
193 //===----------------------------------------------------------------------===//
194 /// SelectionDAGLowering - This is the common target-independent lowering
195 /// implementation that is parameterized by a TargetLowering object.
196 /// Also, targets can overload any lowering method.
199 class SelectionDAGLowering {
200 MachineBasicBlock *CurMBB;
202 std::map<const Value*, SDOperand> NodeMap;
204 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
205 /// them up and then emit token factor nodes when possible. This allows us to
206 /// get simple disambiguation between loads without worrying about alias
208 std::vector<SDOperand> PendingLoads;
211 // TLI - This is information that describes the available target features we
212 // need for lowering. This indicates when operations are unavailable,
213 // implemented with a libcall, etc.
216 const TargetData &TD;
218 /// FuncInfo - Information about the function as a whole.
220 FunctionLoweringInfo &FuncInfo;
222 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
223 FunctionLoweringInfo &funcinfo)
224 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
228 /// getRoot - Return the current virtual root of the Selection DAG.
230 SDOperand getRoot() {
231 if (PendingLoads.empty())
232 return DAG.getRoot();
234 if (PendingLoads.size() == 1) {
235 SDOperand Root = PendingLoads[0];
237 PendingLoads.clear();
241 // Otherwise, we have to make a token factor node.
242 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
243 PendingLoads.clear();
248 void visit(Instruction &I) { visit(I.getOpcode(), I); }
250 void visit(unsigned Opcode, User &I) {
252 default: assert(0 && "Unknown instruction type encountered!");
254 // Build the switch statement using the Instruction.def file.
255 #define HANDLE_INST(NUM, OPCODE, CLASS) \
256 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
257 #include "llvm/Instruction.def"
261 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
264 SDOperand getIntPtrConstant(uint64_t Val) {
265 return DAG.getConstant(Val, TLI.getPointerTy());
268 SDOperand getValue(const Value *V) {
269 SDOperand &N = NodeMap[V];
272 MVT::ValueType VT = TLI.getValueType(V->getType());
273 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
275 visit(CE->getOpcode(), *CE);
276 assert(N.Val && "visit didn't populate the ValueMap!");
278 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
279 return N = DAG.getGlobalAddress(GV, VT);
280 } else if (isa<ConstantPointerNull>(C)) {
281 return N = DAG.getConstant(0, TLI.getPointerTy());
282 } else if (isa<UndefValue>(C)) {
283 return N = DAG.getNode(ISD::UNDEF, VT);
284 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
285 return N = DAG.getConstantFP(CFP->getValue(), VT);
287 // Canonicalize all constant ints to be unsigned.
288 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
291 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
292 std::map<const AllocaInst*, int>::iterator SI =
293 FuncInfo.StaticAllocaMap.find(AI);
294 if (SI != FuncInfo.StaticAllocaMap.end())
295 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
298 std::map<const Value*, unsigned>::const_iterator VMI =
299 FuncInfo.ValueMap.find(V);
300 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
302 unsigned InReg = VMI->second;
304 // If this type is not legal, make it so now.
305 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
307 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
309 // Source must be expanded. This input value is actually coming from the
310 // register pair VMI->second and VMI->second+1.
311 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
312 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
314 if (DestVT > VT) { // Promotion case
315 if (MVT::isFloatingPoint(VT))
316 N = DAG.getNode(ISD::FP_ROUND, VT, N);
318 N = DAG.getNode(ISD::TRUNCATE, VT, N);
325 const SDOperand &setValue(const Value *V, SDOperand NewN) {
326 SDOperand &N = NodeMap[V];
327 assert(N.Val == 0 && "Already set a value for this node!");
331 // Terminator instructions.
332 void visitRet(ReturnInst &I);
333 void visitBr(BranchInst &I);
334 void visitUnreachable(UnreachableInst &I) { /* noop */ }
336 // These all get lowered before this pass.
337 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
338 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
339 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
342 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
343 void visitAdd(User &I) {
344 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
346 void visitSub(User &I);
347 void visitMul(User &I) {
348 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
350 void visitDiv(User &I) {
352 const Type *Ty = I.getType();
353 if (Ty->isFloatingPoint())
355 else if (Ty->isUnsigned())
361 void visitRem(User &I) {
363 const Type *Ty = I.getType();
364 if (Ty->isFloatingPoint())
366 else if (Ty->isUnsigned())
372 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
373 void visitOr (User &I) { visitBinary(I, ISD::OR); }
374 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
375 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
376 void visitShr(User &I) {
377 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
380 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
381 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
382 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
383 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
384 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
385 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
386 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
388 void visitGetElementPtr(User &I);
389 void visitCast(User &I);
390 void visitSelect(User &I);
393 void visitMalloc(MallocInst &I);
394 void visitFree(FreeInst &I);
395 void visitAlloca(AllocaInst &I);
396 void visitLoad(LoadInst &I);
397 void visitStore(StoreInst &I);
398 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
399 void visitCall(CallInst &I);
401 void visitVAStart(CallInst &I);
402 void visitVAArg(VAArgInst &I);
403 void visitVAEnd(CallInst &I);
404 void visitVACopy(CallInst &I);
405 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
407 void visitMemIntrinsic(CallInst &I, unsigned Op);
409 void visitUserOp1(Instruction &I) {
410 assert(0 && "UserOp1 should not exist at instruction selection time!");
413 void visitUserOp2(Instruction &I) {
414 assert(0 && "UserOp2 should not exist at instruction selection time!");
418 } // end namespace llvm
420 void SelectionDAGLowering::visitRet(ReturnInst &I) {
421 if (I.getNumOperands() == 0) {
422 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
426 SDOperand Op1 = getValue(I.getOperand(0));
427 MVT::ValueType TmpVT;
429 switch (Op1.getValueType()) {
430 default: assert(0 && "Unknown value type!");
435 // If this is a machine where 32-bits is legal or expanded, promote to
436 // 32-bits, otherwise, promote to 64-bits.
437 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
438 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
442 // Extend integer types to result type.
443 if (I.getOperand(0)->getType()->isSigned())
444 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
446 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
451 break; // No extension needed!
453 // Allow targets to lower this further to meet ABI requirements
454 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
457 void SelectionDAGLowering::visitBr(BranchInst &I) {
458 // Update machine-CFG edges.
459 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
461 // Figure out which block is immediately after the current one.
462 MachineBasicBlock *NextBlock = 0;
463 MachineFunction::iterator BBI = CurMBB;
464 if (++BBI != CurMBB->getParent()->end())
467 if (I.isUnconditional()) {
468 // If this is not a fall-through branch, emit the branch.
469 if (Succ0MBB != NextBlock)
470 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
471 DAG.getBasicBlock(Succ0MBB)));
473 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
475 SDOperand Cond = getValue(I.getCondition());
476 if (Succ1MBB == NextBlock) {
477 // If the condition is false, fall through. This means we should branch
478 // if the condition is true to Succ #0.
479 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
480 Cond, DAG.getBasicBlock(Succ0MBB)));
481 } else if (Succ0MBB == NextBlock) {
482 // If the condition is true, fall through. This means we should branch if
483 // the condition is false to Succ #1. Invert the condition first.
484 SDOperand True = DAG.getConstant(1, Cond.getValueType());
485 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
486 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
487 Cond, DAG.getBasicBlock(Succ1MBB)));
489 std::vector<SDOperand> Ops;
490 Ops.push_back(getRoot());
492 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
493 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
494 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
499 void SelectionDAGLowering::visitSub(User &I) {
501 if (I.getType()->isFloatingPoint()) {
502 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
503 if (CFP->isExactlyValue(-0.0)) {
504 SDOperand Op2 = getValue(I.getOperand(1));
505 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
508 visitBinary(I, ISD::FSUB);
510 visitBinary(I, ISD::SUB);
514 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
515 SDOperand Op1 = getValue(I.getOperand(0));
516 SDOperand Op2 = getValue(I.getOperand(1));
519 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
521 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
524 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
525 ISD::CondCode UnsignedOpcode) {
526 SDOperand Op1 = getValue(I.getOperand(0));
527 SDOperand Op2 = getValue(I.getOperand(1));
528 ISD::CondCode Opcode = SignedOpcode;
529 if (I.getOperand(0)->getType()->isUnsigned())
530 Opcode = UnsignedOpcode;
531 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
534 void SelectionDAGLowering::visitSelect(User &I) {
535 SDOperand Cond = getValue(I.getOperand(0));
536 SDOperand TrueVal = getValue(I.getOperand(1));
537 SDOperand FalseVal = getValue(I.getOperand(2));
538 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
542 void SelectionDAGLowering::visitCast(User &I) {
543 SDOperand N = getValue(I.getOperand(0));
544 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
545 MVT::ValueType DestTy = TLI.getValueType(I.getType());
547 if (N.getValueType() == DestTy) {
548 setValue(&I, N); // noop cast.
549 } else if (DestTy == MVT::i1) {
550 // Cast to bool is a comparison against zero, not truncation to zero.
551 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
552 DAG.getConstantFP(0.0, N.getValueType());
553 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
554 } else if (isInteger(SrcTy)) {
555 if (isInteger(DestTy)) { // Int -> Int cast
556 if (DestTy < SrcTy) // Truncating cast?
557 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
558 else if (I.getOperand(0)->getType()->isSigned())
559 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
561 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
562 } else { // Int -> FP cast
563 if (I.getOperand(0)->getType()->isSigned())
564 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
566 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
569 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
570 if (isFloatingPoint(DestTy)) { // FP -> FP cast
571 if (DestTy < SrcTy) // Rounding cast?
572 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
574 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
575 } else { // FP -> Int cast.
576 if (I.getType()->isSigned())
577 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
579 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
584 void SelectionDAGLowering::visitGetElementPtr(User &I) {
585 SDOperand N = getValue(I.getOperand(0));
586 const Type *Ty = I.getOperand(0)->getType();
587 const Type *UIntPtrTy = TD.getIntPtrType();
589 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
592 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
593 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
596 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
597 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
598 getIntPtrConstant(Offset));
600 Ty = StTy->getElementType(Field);
602 Ty = cast<SequentialType>(Ty)->getElementType();
603 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
604 // N = N + Idx * ElementSize;
605 uint64_t ElementSize = TD.getTypeSize(Ty);
606 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
608 // If the index is smaller or larger than intptr_t, truncate or extend
610 if (IdxN.getValueType() < Scale.getValueType()) {
611 if (Idx->getType()->isSigned())
612 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
614 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
615 } else if (IdxN.getValueType() > Scale.getValueType())
616 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
618 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
619 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
626 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
627 // If this is a fixed sized alloca in the entry block of the function,
628 // allocate it statically on the stack.
629 if (FuncInfo.StaticAllocaMap.count(&I))
630 return; // getValue will auto-populate this.
632 const Type *Ty = I.getAllocatedType();
633 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
634 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
636 SDOperand AllocSize = getValue(I.getArraySize());
637 MVT::ValueType IntPtr = TLI.getPointerTy();
638 if (IntPtr < AllocSize.getValueType())
639 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
640 else if (IntPtr > AllocSize.getValueType())
641 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
643 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
644 getIntPtrConstant(TySize));
646 // Handle alignment. If the requested alignment is less than or equal to the
647 // stack alignment, ignore it and round the size of the allocation up to the
648 // stack alignment size. If the size is greater than the stack alignment, we
649 // note this in the DYNAMIC_STACKALLOC node.
650 unsigned StackAlign =
651 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
652 if (Align <= StackAlign) {
654 // Add SA-1 to the size.
655 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
656 getIntPtrConstant(StackAlign-1));
657 // Mask out the low bits for alignment purposes.
658 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
659 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
662 std::vector<MVT::ValueType> VTs;
663 VTs.push_back(AllocSize.getValueType());
664 VTs.push_back(MVT::Other);
665 std::vector<SDOperand> Ops;
666 Ops.push_back(getRoot());
667 Ops.push_back(AllocSize);
668 Ops.push_back(getIntPtrConstant(Align));
669 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
670 DAG.setRoot(setValue(&I, DSA).getValue(1));
672 // Inform the Frame Information that we have just allocated a variable-sized
674 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
678 void SelectionDAGLowering::visitLoad(LoadInst &I) {
679 SDOperand Ptr = getValue(I.getOperand(0));
685 // Do not serialize non-volatile loads against each other.
686 Root = DAG.getRoot();
689 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
690 DAG.getSrcValue(I.getOperand(0)));
694 DAG.setRoot(L.getValue(1));
696 PendingLoads.push_back(L.getValue(1));
700 void SelectionDAGLowering::visitStore(StoreInst &I) {
701 Value *SrcV = I.getOperand(0);
702 SDOperand Src = getValue(SrcV);
703 SDOperand Ptr = getValue(I.getOperand(1));
704 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
705 DAG.getSrcValue(I.getOperand(1))));
708 void SelectionDAGLowering::visitCall(CallInst &I) {
709 const char *RenameFn = 0;
711 if (Function *F = I.getCalledFunction())
713 switch (F->getIntrinsicID()) {
714 case 0: // Not an LLVM intrinsic.
715 if (F->getName() == "fabs" || F->getName() == "fabsf") {
716 if (I.getNumOperands() == 2 && // Basic sanity checks.
717 I.getOperand(1)->getType()->isFloatingPoint() &&
718 I.getType() == I.getOperand(1)->getType()) {
719 Tmp = getValue(I.getOperand(1));
720 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
724 else if (F->getName() == "sin" || F->getName() == "sinf") {
725 if (I.getNumOperands() == 2 && // Basic sanity checks.
726 I.getOperand(1)->getType()->isFloatingPoint() &&
727 I.getType() == I.getOperand(1)->getType()) {
728 Tmp = getValue(I.getOperand(1));
729 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
733 else if (F->getName() == "cos" || F->getName() == "cosf") {
734 if (I.getNumOperands() == 2 && // Basic sanity checks.
735 I.getOperand(1)->getType()->isFloatingPoint() &&
736 I.getType() == I.getOperand(1)->getType()) {
737 Tmp = getValue(I.getOperand(1));
738 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
743 case Intrinsic::vastart: visitVAStart(I); return;
744 case Intrinsic::vaend: visitVAEnd(I); return;
745 case Intrinsic::vacopy: visitVACopy(I); return;
746 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
747 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
749 case Intrinsic::setjmp:
750 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
752 case Intrinsic::longjmp:
753 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
755 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
756 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
757 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
759 case Intrinsic::readport:
760 case Intrinsic::readio: {
761 std::vector<MVT::ValueType> VTs;
762 VTs.push_back(TLI.getValueType(I.getType()));
763 VTs.push_back(MVT::Other);
764 std::vector<SDOperand> Ops;
765 Ops.push_back(getRoot());
766 Ops.push_back(getValue(I.getOperand(1)));
767 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
768 ISD::READPORT : ISD::READIO, VTs, Ops);
771 DAG.setRoot(Tmp.getValue(1));
774 case Intrinsic::writeport:
775 case Intrinsic::writeio:
776 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
777 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
778 getRoot(), getValue(I.getOperand(1)),
779 getValue(I.getOperand(2))));
781 case Intrinsic::dbg_stoppoint:
782 case Intrinsic::dbg_region_start:
783 case Intrinsic::dbg_region_end:
784 case Intrinsic::dbg_func_start:
785 case Intrinsic::dbg_declare:
786 if (I.getType() != Type::VoidTy)
787 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
790 case Intrinsic::isunordered:
791 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
792 getValue(I.getOperand(2)), ISD::SETUO));
795 case Intrinsic::sqrt:
796 setValue(&I, DAG.getNode(ISD::FSQRT,
797 getValue(I.getOperand(1)).getValueType(),
798 getValue(I.getOperand(1))));
801 case Intrinsic::pcmarker:
802 Tmp = getValue(I.getOperand(1));
803 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
805 case Intrinsic::cttz:
806 setValue(&I, DAG.getNode(ISD::CTTZ,
807 getValue(I.getOperand(1)).getValueType(),
808 getValue(I.getOperand(1))));
810 case Intrinsic::ctlz:
811 setValue(&I, DAG.getNode(ISD::CTLZ,
812 getValue(I.getOperand(1)).getValueType(),
813 getValue(I.getOperand(1))));
815 case Intrinsic::ctpop:
816 setValue(&I, DAG.getNode(ISD::CTPOP,
817 getValue(I.getOperand(1)).getValueType(),
818 getValue(I.getOperand(1))));
822 assert(0 && "This intrinsic is not implemented yet!");
828 Callee = getValue(I.getOperand(0));
830 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
831 std::vector<std::pair<SDOperand, const Type*> > Args;
833 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
834 Value *Arg = I.getOperand(i);
835 SDOperand ArgNode = getValue(Arg);
836 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
839 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
840 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
842 std::pair<SDOperand,SDOperand> Result =
843 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
844 I.isTailCall(), Callee, Args, DAG);
845 if (I.getType() != Type::VoidTy)
846 setValue(&I, Result.first);
847 DAG.setRoot(Result.second);
850 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
851 SDOperand Src = getValue(I.getOperand(0));
853 MVT::ValueType IntPtr = TLI.getPointerTy();
855 if (IntPtr < Src.getValueType())
856 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
857 else if (IntPtr > Src.getValueType())
858 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
860 // Scale the source by the type size.
861 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
862 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
863 Src, getIntPtrConstant(ElementSize));
865 std::vector<std::pair<SDOperand, const Type*> > Args;
866 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
868 std::pair<SDOperand,SDOperand> Result =
869 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
870 DAG.getExternalSymbol("malloc", IntPtr),
872 setValue(&I, Result.first); // Pointers always fit in registers
873 DAG.setRoot(Result.second);
876 void SelectionDAGLowering::visitFree(FreeInst &I) {
877 std::vector<std::pair<SDOperand, const Type*> > Args;
878 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
879 TLI.getTargetData().getIntPtrType()));
880 MVT::ValueType IntPtr = TLI.getPointerTy();
881 std::pair<SDOperand,SDOperand> Result =
882 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
883 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
884 DAG.setRoot(Result.second);
887 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
888 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
889 // instructions are special in various ways, which require special support to
890 // insert. The specified MachineInstr is created but not inserted into any
891 // basic blocks, and the scheduler passes ownership of it to this method.
892 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
893 MachineBasicBlock *MBB) {
894 std::cerr << "If a target marks an instruction with "
895 "'usesCustomDAGSchedInserter', it must implement "
896 "TargetLowering::InsertAtEndOfBasicBlock!\n";
901 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
903 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
906 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
907 SDOperand VAListP, Value *VAListV,
909 // We have no sane default behavior, just emit a useful error message and bail
911 std::cerr << "Variable arguments handling not implemented on this target!\n";
916 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
918 // Default to a noop.
922 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
923 SDOperand SrcP, Value *SrcV,
924 SDOperand DestP, Value *DestV,
926 // Default to copying the input list.
927 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
928 SrcP, DAG.getSrcValue(SrcV));
929 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
930 Val, DestP, DAG.getSrcValue(DestV));
934 std::pair<SDOperand,SDOperand>
935 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
936 const Type *ArgTy, SelectionDAG &DAG) {
937 // We have no sane default behavior, just emit a useful error message and bail
939 std::cerr << "Variable arguments handling not implemented on this target!\n";
941 return std::make_pair(SDOperand(), SDOperand());
945 void SelectionDAGLowering::visitVAStart(CallInst &I) {
946 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
947 I.getOperand(1), DAG));
950 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
951 std::pair<SDOperand,SDOperand> Result =
952 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
954 setValue(&I, Result.first);
955 DAG.setRoot(Result.second);
958 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
959 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
960 I.getOperand(1), DAG));
963 void SelectionDAGLowering::visitVACopy(CallInst &I) {
965 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
966 getValue(I.getOperand(1)), I.getOperand(1), DAG);
971 // It is always conservatively correct for llvm.returnaddress and
972 // llvm.frameaddress to return 0.
973 std::pair<SDOperand, SDOperand>
974 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
975 unsigned Depth, SelectionDAG &DAG) {
976 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
979 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
980 assert(0 && "LowerOperation not implemented for this target!");
985 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
986 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
987 std::pair<SDOperand,SDOperand> Result =
988 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
989 setValue(&I, Result.first);
990 DAG.setRoot(Result.second);
993 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
994 std::vector<SDOperand> Ops;
995 Ops.push_back(getRoot());
996 Ops.push_back(getValue(I.getOperand(1)));
997 Ops.push_back(getValue(I.getOperand(2)));
998 Ops.push_back(getValue(I.getOperand(3)));
999 Ops.push_back(getValue(I.getOperand(4)));
1000 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1003 //===----------------------------------------------------------------------===//
1004 // SelectionDAGISel code
1005 //===----------------------------------------------------------------------===//
1007 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1008 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1011 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1012 // FIXME: we only modify the CFG to split critical edges. This
1013 // updates dom and loop info.
1017 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1018 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1019 RegMap = MF.getSSARegMap();
1020 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1022 // First pass, split all critical edges for PHI nodes with incoming values
1023 // that are constants, this way the load of the constant into a vreg will not
1024 // be placed into MBBs that are used some other way.
1025 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1027 for (BasicBlock::iterator BBI = BB->begin();
1028 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1030 if (isa<Constant>(PN->getIncomingValue(i)))
1031 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1034 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1036 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1037 SelectBasicBlock(I, MF, FuncInfo);
1043 SDOperand SelectionDAGISel::
1044 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1045 SDOperand Op = SDL.getValue(V);
1046 assert((Op.getOpcode() != ISD::CopyFromReg ||
1047 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1048 "Copy from a reg to the same reg!");
1050 // If this type is not legal, we must make sure to not create an invalid
1052 MVT::ValueType SrcVT = Op.getValueType();
1053 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1054 SelectionDAG &DAG = SDL.DAG;
1055 if (SrcVT == DestVT) {
1056 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1057 } else if (SrcVT < DestVT) {
1058 // The src value is promoted to the register.
1059 if (MVT::isFloatingPoint(SrcVT))
1060 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1062 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1063 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1065 // The src value is expanded into multiple registers.
1066 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1067 Op, DAG.getConstant(0, MVT::i32));
1068 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1069 Op, DAG.getConstant(1, MVT::i32));
1070 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1071 return DAG.getCopyToReg(Op, Reg+1, Hi);
1075 /// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1076 /// single basic block, return that block. Otherwise, return a null pointer.
1077 static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1078 if (A->use_empty()) return 0;
1079 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1080 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1082 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1083 return 0; // Disagreement among the users?
1085 // Okay, there is a single BB user. Only permit this optimization if this is
1086 // the entry block, otherwise, we might sink argument loads into loops and
1087 // stuff. Later, when we have global instruction selection, this won't be an
1089 if (BB == BB->getParent()->begin())
1094 void SelectionDAGISel::
1095 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1096 std::vector<SDOperand> &UnorderedChains) {
1097 // If this is the entry block, emit arguments.
1098 Function &F = *BB->getParent();
1099 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1101 if (BB == &F.front()) {
1102 SDOperand OldRoot = SDL.DAG.getRoot();
1104 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1106 // If there were side effects accessing the argument list, do not do
1107 // anything special.
1108 if (OldRoot != SDL.DAG.getRoot()) {
1110 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1112 if (!AI->use_empty()) {
1113 SDL.setValue(AI, Args[a]);
1116 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1117 UnorderedChains.push_back(Copy);
1120 // Otherwise, if any argument is only accessed in a single basic block,
1121 // emit that argument only to that basic block.
1123 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1125 if (!AI->use_empty()) {
1126 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1127 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1128 std::make_pair(AI, a)));
1130 SDL.setValue(AI, Args[a]);
1132 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1133 UnorderedChains.push_back(Copy);
1138 // Next, if the function has live ins that need to be copied into vregs,
1139 // emit the copies now, into the top of the block.
1140 MachineFunction &MF = SDL.DAG.getMachineFunction();
1141 if (MF.livein_begin() != MF.livein_end()) {
1142 SSARegMap *RegMap = MF.getSSARegMap();
1143 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1144 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1145 E = MF.livein_end(); LI != E; ++LI)
1147 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1148 LI->first, RegMap->getRegClass(LI->second));
1151 // Finally, if the target has anything special to do, allow it to do so.
1152 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1155 // See if there are any block-local arguments that need to be emitted in this
1158 if (!FuncInfo.BlockLocalArguments.empty()) {
1159 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1160 FuncInfo.BlockLocalArguments.lower_bound(BB);
1161 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1162 // Lower the arguments into this block.
1163 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1165 // Set up the value mapping for the local arguments.
1166 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1168 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
1170 // Any dead arguments will just be ignored here.
1176 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1177 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1178 FunctionLoweringInfo &FuncInfo) {
1179 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1181 std::vector<SDOperand> UnorderedChains;
1183 // Lower any arguments needed in this block.
1184 LowerArguments(LLVMBB, SDL, UnorderedChains);
1186 BB = FuncInfo.MBBMap[LLVMBB];
1187 SDL.setCurrentBasicBlock(BB);
1189 // Lower all of the non-terminator instructions.
1190 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1194 // Ensure that all instructions which are used outside of their defining
1195 // blocks are available as virtual registers.
1196 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1197 if (!I->use_empty() && !isa<PHINode>(I)) {
1198 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1199 if (VMI != FuncInfo.ValueMap.end())
1200 UnorderedChains.push_back(
1201 CopyValueToVirtualRegister(SDL, I, VMI->second));
1204 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1205 // ensure constants are generated when needed. Remember the virtual registers
1206 // that need to be added to the Machine PHI nodes as input. We cannot just
1207 // directly add them, because expansion might result in multiple MBB's for one
1208 // BB. As such, the start of the BB might correspond to a different MBB than
1212 // Emit constants only once even if used by multiple PHI nodes.
1213 std::map<Constant*, unsigned> ConstantsOut;
1215 // Check successor nodes PHI nodes that expect a constant to be available from
1217 TerminatorInst *TI = LLVMBB->getTerminator();
1218 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1219 BasicBlock *SuccBB = TI->getSuccessor(succ);
1220 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1223 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1224 // nodes and Machine PHI nodes, but the incoming operands have not been
1226 for (BasicBlock::iterator I = SuccBB->begin();
1227 (PN = dyn_cast<PHINode>(I)); ++I)
1228 if (!PN->use_empty()) {
1230 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1231 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1232 unsigned &RegOut = ConstantsOut[C];
1234 RegOut = FuncInfo.CreateRegForValue(C);
1235 UnorderedChains.push_back(
1236 CopyValueToVirtualRegister(SDL, C, RegOut));
1240 Reg = FuncInfo.ValueMap[PHIOp];
1242 assert(isa<AllocaInst>(PHIOp) &&
1243 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1244 "Didn't codegen value into a register!??");
1245 Reg = FuncInfo.CreateRegForValue(PHIOp);
1246 UnorderedChains.push_back(
1247 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1251 // Remember that this register needs to added to the machine PHI node as
1252 // the input for this MBB.
1253 unsigned NumElements =
1254 TLI.getNumElements(TLI.getValueType(PN->getType()));
1255 for (unsigned i = 0, e = NumElements; i != e; ++i)
1256 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1259 ConstantsOut.clear();
1261 // Turn all of the unordered chains into one factored node.
1262 if (!UnorderedChains.empty()) {
1263 UnorderedChains.push_back(SDL.getRoot());
1264 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1267 // Lower the terminator after the copies are emitted.
1268 SDL.visit(*LLVMBB->getTerminator());
1270 // Make sure the root of the DAG is up-to-date.
1271 DAG.setRoot(SDL.getRoot());
1274 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1275 FunctionLoweringInfo &FuncInfo) {
1276 SelectionDAG DAG(TLI, MF);
1278 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1280 // First step, lower LLVM code to some DAG. This DAG may use operations and
1281 // types that are not supported by the target.
1282 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1284 // Run the DAG combiner in pre-legalize mode.
1287 DEBUG(std::cerr << "Lowered selection DAG:\n");
1290 // Second step, hack on the DAG until it only uses operations and types that
1291 // the target supports.
1294 DEBUG(std::cerr << "Legalized selection DAG:\n");
1297 // Run the DAG combiner in post-legalize mode.
1300 if (ViewDAGs) DAG.viewGraph();
1302 // Third, instruction select all of the operations to machine code, adding the
1303 // code to the MachineBasicBlock.
1304 InstructionSelectBasicBlock(DAG);
1306 DEBUG(std::cerr << "Selected machine code:\n");
1309 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1310 // PHI nodes in successors.
1311 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1312 MachineInstr *PHI = PHINodesToUpdate[i].first;
1313 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1314 "This is not a machine PHI node that we are updating!");
1315 PHI->addRegOperand(PHINodesToUpdate[i].second);
1316 PHI->addMachineBasicBlockOperand(BB);
1319 // Finally, add the CFG edges from the last selected MBB to the successor
1321 TerminatorInst *TI = LLVMBB->getTerminator();
1322 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1323 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1324 BB->addSuccessor(Succ0MBB);