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/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
39 // Temporary command line code to enable use of the dag combiner as a beta
46 CombineDAG("enable-dag-combiner", cl::Hidden,
47 cl::desc("Run the DAG combiner before and after Legalize"),
48 cl::location(CombinerEnabled),
53 ViewDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 static const bool ViewDAGs = 0;
61 //===--------------------------------------------------------------------===//
62 /// FunctionLoweringInfo - This contains information that is global to a
63 /// function that is used when lowering a region of the function.
64 class FunctionLoweringInfo {
71 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
73 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
74 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
76 /// ValueMap - Since we emit code for the function a basic block at a time,
77 /// we must remember which virtual registers hold the values for
78 /// cross-basic-block values.
79 std::map<const Value*, unsigned> ValueMap;
81 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
82 /// the entry block. This allows the allocas to be efficiently referenced
83 /// anywhere in the function.
84 std::map<const AllocaInst*, int> StaticAllocaMap;
86 /// BlockLocalArguments - If any arguments are only used in a single basic
87 /// block, and if the target can access the arguments without side-effects,
88 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
89 /// track of which arguments are local to each BB.
90 std::multimap<BasicBlock*, std::pair<Argument*,
91 unsigned> > BlockLocalArguments;
94 unsigned MakeReg(MVT::ValueType VT) {
95 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
98 unsigned CreateRegForValue(const Value *V) {
99 MVT::ValueType VT = TLI.getValueType(V->getType());
100 // The common case is that we will only create one register for this
101 // value. If we have that case, create and return the virtual register.
102 unsigned NV = TLI.getNumElements(VT);
104 // If we are promoting this value, pick the next largest supported type.
105 return MakeReg(TLI.getTypeToTransformTo(VT));
108 // If this value is represented with multiple target registers, make sure
109 // to create enough consequtive registers of the right (smaller) type.
110 unsigned NT = VT-1; // Find the type to use.
111 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
114 unsigned R = MakeReg((MVT::ValueType)NT);
115 for (unsigned i = 1; i != NV; ++i)
116 MakeReg((MVT::ValueType)NT);
120 unsigned InitializeRegForValue(const Value *V) {
121 unsigned &R = ValueMap[V];
122 assert(R == 0 && "Already initialized this value register!");
123 return R = CreateRegForValue(V);
128 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
129 /// PHI nodes or outside of the basic block that defines it.
130 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
131 if (isa<PHINode>(I)) return true;
132 BasicBlock *BB = I->getParent();
133 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
134 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
139 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
140 Function &fn, MachineFunction &mf)
141 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
143 // Initialize the mapping of values to registers. This is only set up for
144 // instruction values that are used outside of the block that defines
146 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
148 InitializeRegForValue(AI);
150 Function::iterator BB = Fn.begin(), E = Fn.end();
151 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
152 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
153 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
154 const Type *Ty = AI->getAllocatedType();
155 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
156 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
158 // If the alignment of the value is smaller than the size of the value,
159 // and if the size of the value is particularly small (<= 8 bytes),
160 // round up to the size of the value for potentially better performance.
162 // FIXME: This could be made better with a preferred alignment hook in
163 // TargetData. It serves primarily to 8-byte align doubles for X86.
164 if (Align < TySize && TySize <= 8) Align = TySize;
166 if (CUI->getValue()) // Don't produce zero sized stack objects
167 TySize *= CUI->getValue(); // Get total allocated size.
168 StaticAllocaMap[AI] =
169 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
172 for (; BB != E; ++BB)
173 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
174 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
175 if (!isa<AllocaInst>(I) ||
176 !StaticAllocaMap.count(cast<AllocaInst>(I)))
177 InitializeRegForValue(I);
179 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
180 // also creates the initial PHI MachineInstrs, though none of the input
181 // operands are populated.
182 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
183 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
185 MF.getBasicBlockList().push_back(MBB);
187 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
190 for (BasicBlock::iterator I = BB->begin();
191 (PN = dyn_cast<PHINode>(I)); ++I)
192 if (!PN->use_empty()) {
193 unsigned NumElements =
194 TLI.getNumElements(TLI.getValueType(PN->getType()));
195 unsigned PHIReg = ValueMap[PN];
196 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
197 for (unsigned i = 0; i != NumElements; ++i)
198 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
205 //===----------------------------------------------------------------------===//
206 /// SelectionDAGLowering - This is the common target-independent lowering
207 /// implementation that is parameterized by a TargetLowering object.
208 /// Also, targets can overload any lowering method.
211 class SelectionDAGLowering {
212 MachineBasicBlock *CurMBB;
214 std::map<const Value*, SDOperand> NodeMap;
216 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
217 /// them up and then emit token factor nodes when possible. This allows us to
218 /// get simple disambiguation between loads without worrying about alias
220 std::vector<SDOperand> PendingLoads;
223 // TLI - This is information that describes the available target features we
224 // need for lowering. This indicates when operations are unavailable,
225 // implemented with a libcall, etc.
228 const TargetData &TD;
230 /// FuncInfo - Information about the function as a whole.
232 FunctionLoweringInfo &FuncInfo;
234 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
235 FunctionLoweringInfo &funcinfo)
236 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
240 /// getRoot - Return the current virtual root of the Selection DAG.
242 SDOperand getRoot() {
243 if (PendingLoads.empty())
244 return DAG.getRoot();
246 if (PendingLoads.size() == 1) {
247 SDOperand Root = PendingLoads[0];
249 PendingLoads.clear();
253 // Otherwise, we have to make a token factor node.
254 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
255 PendingLoads.clear();
260 void visit(Instruction &I) { visit(I.getOpcode(), I); }
262 void visit(unsigned Opcode, User &I) {
264 default: assert(0 && "Unknown instruction type encountered!");
266 // Build the switch statement using the Instruction.def file.
267 #define HANDLE_INST(NUM, OPCODE, CLASS) \
268 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
269 #include "llvm/Instruction.def"
273 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
276 SDOperand getIntPtrConstant(uint64_t Val) {
277 return DAG.getConstant(Val, TLI.getPointerTy());
280 SDOperand getValue(const Value *V) {
281 SDOperand &N = NodeMap[V];
284 MVT::ValueType VT = TLI.getValueType(V->getType());
285 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
287 visit(CE->getOpcode(), *CE);
288 assert(N.Val && "visit didn't populate the ValueMap!");
290 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
291 return N = DAG.getGlobalAddress(GV, VT);
292 } else if (isa<ConstantPointerNull>(C)) {
293 return N = DAG.getConstant(0, TLI.getPointerTy());
294 } else if (isa<UndefValue>(C)) {
295 return N = DAG.getNode(ISD::UNDEF, VT);
296 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
297 return N = DAG.getConstantFP(CFP->getValue(), VT);
299 // Canonicalize all constant ints to be unsigned.
300 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
303 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
304 std::map<const AllocaInst*, int>::iterator SI =
305 FuncInfo.StaticAllocaMap.find(AI);
306 if (SI != FuncInfo.StaticAllocaMap.end())
307 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
310 std::map<const Value*, unsigned>::const_iterator VMI =
311 FuncInfo.ValueMap.find(V);
312 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
314 unsigned InReg = VMI->second;
316 // If this type is not legal, make it so now.
317 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
319 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
321 // Source must be expanded. This input value is actually coming from the
322 // register pair VMI->second and VMI->second+1.
323 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
324 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
326 if (DestVT > VT) { // Promotion case
327 if (MVT::isFloatingPoint(VT))
328 N = DAG.getNode(ISD::FP_ROUND, VT, N);
330 N = DAG.getNode(ISD::TRUNCATE, VT, N);
337 const SDOperand &setValue(const Value *V, SDOperand NewN) {
338 SDOperand &N = NodeMap[V];
339 assert(N.Val == 0 && "Already set a value for this node!");
343 // Terminator instructions.
344 void visitRet(ReturnInst &I);
345 void visitBr(BranchInst &I);
346 void visitUnreachable(UnreachableInst &I) { /* noop */ }
348 // These all get lowered before this pass.
349 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
350 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
351 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
354 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
355 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
356 void visitSub(User &I);
357 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
358 void visitDiv(User &I) {
359 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
361 void visitRem(User &I) {
362 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
364 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
365 void visitOr (User &I) { visitBinary(I, ISD::OR); }
366 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
367 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
368 void visitShr(User &I) {
369 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
372 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
373 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
374 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
375 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
376 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
377 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
378 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
380 void visitGetElementPtr(User &I);
381 void visitCast(User &I);
382 void visitSelect(User &I);
385 void visitMalloc(MallocInst &I);
386 void visitFree(FreeInst &I);
387 void visitAlloca(AllocaInst &I);
388 void visitLoad(LoadInst &I);
389 void visitStore(StoreInst &I);
390 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
391 void visitCall(CallInst &I);
393 void visitVAStart(CallInst &I);
394 void visitVAArg(VAArgInst &I);
395 void visitVAEnd(CallInst &I);
396 void visitVACopy(CallInst &I);
397 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
399 void visitMemIntrinsic(CallInst &I, unsigned Op);
401 void visitUserOp1(Instruction &I) {
402 assert(0 && "UserOp1 should not exist at instruction selection time!");
405 void visitUserOp2(Instruction &I) {
406 assert(0 && "UserOp2 should not exist at instruction selection time!");
410 } // end namespace llvm
412 void SelectionDAGLowering::visitRet(ReturnInst &I) {
413 if (I.getNumOperands() == 0) {
414 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
418 SDOperand Op1 = getValue(I.getOperand(0));
419 MVT::ValueType TmpVT;
421 switch (Op1.getValueType()) {
422 default: assert(0 && "Unknown value type!");
427 // If this is a machine where 32-bits is legal or expanded, promote to
428 // 32-bits, otherwise, promote to 64-bits.
429 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
430 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
434 // Extend integer types to result type.
435 if (I.getOperand(0)->getType()->isSigned())
436 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
438 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
443 break; // No extension needed!
446 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
449 void SelectionDAGLowering::visitBr(BranchInst &I) {
450 // Update machine-CFG edges.
451 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
453 // Figure out which block is immediately after the current one.
454 MachineBasicBlock *NextBlock = 0;
455 MachineFunction::iterator BBI = CurMBB;
456 if (++BBI != CurMBB->getParent()->end())
459 if (I.isUnconditional()) {
460 // If this is not a fall-through branch, emit the branch.
461 if (Succ0MBB != NextBlock)
462 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
463 DAG.getBasicBlock(Succ0MBB)));
465 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
467 SDOperand Cond = getValue(I.getCondition());
468 if (Succ1MBB == NextBlock) {
469 // If the condition is false, fall through. This means we should branch
470 // if the condition is true to Succ #0.
471 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
472 Cond, DAG.getBasicBlock(Succ0MBB)));
473 } else if (Succ0MBB == NextBlock) {
474 // If the condition is true, fall through. This means we should branch if
475 // the condition is false to Succ #1. Invert the condition first.
476 SDOperand True = DAG.getConstant(1, Cond.getValueType());
477 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
478 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
479 Cond, DAG.getBasicBlock(Succ1MBB)));
481 std::vector<SDOperand> Ops;
482 Ops.push_back(getRoot());
484 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
485 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
486 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
491 void SelectionDAGLowering::visitSub(User &I) {
493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
494 if (CFP->isExactlyValue(-0.0)) {
495 SDOperand Op2 = getValue(I.getOperand(1));
496 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
500 visitBinary(I, ISD::SUB);
503 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
504 SDOperand Op1 = getValue(I.getOperand(0));
505 SDOperand Op2 = getValue(I.getOperand(1));
508 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
510 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
513 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
514 ISD::CondCode UnsignedOpcode) {
515 SDOperand Op1 = getValue(I.getOperand(0));
516 SDOperand Op2 = getValue(I.getOperand(1));
517 ISD::CondCode Opcode = SignedOpcode;
518 if (I.getOperand(0)->getType()->isUnsigned())
519 Opcode = UnsignedOpcode;
520 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
523 void SelectionDAGLowering::visitSelect(User &I) {
524 SDOperand Cond = getValue(I.getOperand(0));
525 SDOperand TrueVal = getValue(I.getOperand(1));
526 SDOperand FalseVal = getValue(I.getOperand(2));
527 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
531 void SelectionDAGLowering::visitCast(User &I) {
532 SDOperand N = getValue(I.getOperand(0));
533 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
534 MVT::ValueType DestTy = TLI.getValueType(I.getType());
536 if (N.getValueType() == DestTy) {
537 setValue(&I, N); // noop cast.
538 } else if (DestTy == MVT::i1) {
539 // Cast to bool is a comparison against zero, not truncation to zero.
540 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
541 DAG.getConstantFP(0.0, N.getValueType());
542 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
543 } else if (isInteger(SrcTy)) {
544 if (isInteger(DestTy)) { // Int -> Int cast
545 if (DestTy < SrcTy) // Truncating cast?
546 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
547 else if (I.getOperand(0)->getType()->isSigned())
548 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
550 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
551 } else { // Int -> FP cast
552 if (I.getOperand(0)->getType()->isSigned())
553 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
555 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
558 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
559 if (isFloatingPoint(DestTy)) { // FP -> FP cast
560 if (DestTy < SrcTy) // Rounding cast?
561 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
563 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
564 } else { // FP -> Int cast.
565 if (I.getType()->isSigned())
566 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
568 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
573 void SelectionDAGLowering::visitGetElementPtr(User &I) {
574 SDOperand N = getValue(I.getOperand(0));
575 const Type *Ty = I.getOperand(0)->getType();
576 const Type *UIntPtrTy = TD.getIntPtrType();
578 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
581 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
582 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
585 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
586 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
587 getIntPtrConstant(Offset));
589 Ty = StTy->getElementType(Field);
591 Ty = cast<SequentialType>(Ty)->getElementType();
592 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
593 // N = N + Idx * ElementSize;
594 uint64_t ElementSize = TD.getTypeSize(Ty);
595 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
597 // If the index is smaller or larger than intptr_t, truncate or extend
599 if (IdxN.getValueType() < Scale.getValueType()) {
600 if (Idx->getType()->isSigned())
601 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
603 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
604 } else if (IdxN.getValueType() > Scale.getValueType())
605 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
607 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
608 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
615 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
616 // If this is a fixed sized alloca in the entry block of the function,
617 // allocate it statically on the stack.
618 if (FuncInfo.StaticAllocaMap.count(&I))
619 return; // getValue will auto-populate this.
621 const Type *Ty = I.getAllocatedType();
622 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
623 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
625 SDOperand AllocSize = getValue(I.getArraySize());
626 MVT::ValueType IntPtr = TLI.getPointerTy();
627 if (IntPtr < AllocSize.getValueType())
628 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
629 else if (IntPtr > AllocSize.getValueType())
630 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
632 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
633 getIntPtrConstant(TySize));
635 // Handle alignment. If the requested alignment is less than or equal to the
636 // stack alignment, ignore it and round the size of the allocation up to the
637 // stack alignment size. If the size is greater than the stack alignment, we
638 // note this in the DYNAMIC_STACKALLOC node.
639 unsigned StackAlign =
640 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
641 if (Align <= StackAlign) {
643 // Add SA-1 to the size.
644 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
645 getIntPtrConstant(StackAlign-1));
646 // Mask out the low bits for alignment purposes.
647 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
648 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
651 std::vector<MVT::ValueType> VTs;
652 VTs.push_back(AllocSize.getValueType());
653 VTs.push_back(MVT::Other);
654 std::vector<SDOperand> Ops;
655 Ops.push_back(getRoot());
656 Ops.push_back(AllocSize);
657 Ops.push_back(getIntPtrConstant(Align));
658 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
659 DAG.setRoot(setValue(&I, DSA).getValue(1));
661 // Inform the Frame Information that we have just allocated a variable-sized
663 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
667 void SelectionDAGLowering::visitLoad(LoadInst &I) {
668 SDOperand Ptr = getValue(I.getOperand(0));
674 // Do not serialize non-volatile loads against each other.
675 Root = DAG.getRoot();
678 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
679 DAG.getSrcValue(I.getOperand(0)));
683 DAG.setRoot(L.getValue(1));
685 PendingLoads.push_back(L.getValue(1));
689 void SelectionDAGLowering::visitStore(StoreInst &I) {
690 Value *SrcV = I.getOperand(0);
691 SDOperand Src = getValue(SrcV);
692 SDOperand Ptr = getValue(I.getOperand(1));
693 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
694 DAG.getSrcValue(I.getOperand(1))));
697 void SelectionDAGLowering::visitCall(CallInst &I) {
698 const char *RenameFn = 0;
700 if (Function *F = I.getCalledFunction())
702 switch (F->getIntrinsicID()) {
703 case 0: // Not an LLVM intrinsic.
704 if (F->getName() == "fabs" || F->getName() == "fabsf") {
705 if (I.getNumOperands() == 2 && // Basic sanity checks.
706 I.getOperand(1)->getType()->isFloatingPoint() &&
707 I.getType() == I.getOperand(1)->getType()) {
708 Tmp = getValue(I.getOperand(1));
709 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
713 else if (F->getName() == "sin" || F->getName() == "sinf") {
714 if (I.getNumOperands() == 2 && // Basic sanity checks.
715 I.getOperand(1)->getType()->isFloatingPoint() &&
716 I.getType() == I.getOperand(1)->getType()) {
717 Tmp = getValue(I.getOperand(1));
718 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
722 else if (F->getName() == "cos" || F->getName() == "cosf") {
723 if (I.getNumOperands() == 2 && // Basic sanity checks.
724 I.getOperand(1)->getType()->isFloatingPoint() &&
725 I.getType() == I.getOperand(1)->getType()) {
726 Tmp = getValue(I.getOperand(1));
727 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
732 case Intrinsic::vastart: visitVAStart(I); return;
733 case Intrinsic::vaend: visitVAEnd(I); return;
734 case Intrinsic::vacopy: visitVACopy(I); return;
735 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
736 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
738 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
739 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
740 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
741 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
742 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
744 case Intrinsic::readport:
745 case Intrinsic::readio: {
746 std::vector<MVT::ValueType> VTs;
747 VTs.push_back(TLI.getValueType(I.getType()));
748 VTs.push_back(MVT::Other);
749 std::vector<SDOperand> Ops;
750 Ops.push_back(getRoot());
751 Ops.push_back(getValue(I.getOperand(1)));
752 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
753 ISD::READPORT : ISD::READIO, VTs, Ops);
756 DAG.setRoot(Tmp.getValue(1));
759 case Intrinsic::writeport:
760 case Intrinsic::writeio:
761 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
762 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
763 getRoot(), getValue(I.getOperand(1)),
764 getValue(I.getOperand(2))));
766 case Intrinsic::dbg_stoppoint:
767 case Intrinsic::dbg_region_start:
768 case Intrinsic::dbg_region_end:
769 case Intrinsic::dbg_func_start:
770 case Intrinsic::dbg_declare:
771 if (I.getType() != Type::VoidTy)
772 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
775 case Intrinsic::isunordered:
776 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
777 getValue(I.getOperand(2)), ISD::SETUO));
780 case Intrinsic::sqrt:
781 setValue(&I, DAG.getNode(ISD::FSQRT,
782 getValue(I.getOperand(1)).getValueType(),
783 getValue(I.getOperand(1))));
786 case Intrinsic::pcmarker:
787 Tmp = getValue(I.getOperand(1));
788 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
790 case Intrinsic::cttz:
791 setValue(&I, DAG.getNode(ISD::CTTZ,
792 getValue(I.getOperand(1)).getValueType(),
793 getValue(I.getOperand(1))));
795 case Intrinsic::ctlz:
796 setValue(&I, DAG.getNode(ISD::CTLZ,
797 getValue(I.getOperand(1)).getValueType(),
798 getValue(I.getOperand(1))));
800 case Intrinsic::ctpop:
801 setValue(&I, DAG.getNode(ISD::CTPOP,
802 getValue(I.getOperand(1)).getValueType(),
803 getValue(I.getOperand(1))));
807 assert(0 && "This intrinsic is not implemented yet!");
813 Callee = getValue(I.getOperand(0));
815 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
816 std::vector<std::pair<SDOperand, const Type*> > Args;
818 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
819 Value *Arg = I.getOperand(i);
820 SDOperand ArgNode = getValue(Arg);
821 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
824 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
825 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
827 std::pair<SDOperand,SDOperand> Result =
828 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
829 I.isTailCall(), Callee, Args, DAG);
830 if (I.getType() != Type::VoidTy)
831 setValue(&I, Result.first);
832 DAG.setRoot(Result.second);
835 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
836 SDOperand Src = getValue(I.getOperand(0));
838 MVT::ValueType IntPtr = TLI.getPointerTy();
840 if (IntPtr < Src.getValueType())
841 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
842 else if (IntPtr > Src.getValueType())
843 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
845 // Scale the source by the type size.
846 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
847 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
848 Src, getIntPtrConstant(ElementSize));
850 std::vector<std::pair<SDOperand, const Type*> > Args;
851 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
853 std::pair<SDOperand,SDOperand> Result =
854 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
855 DAG.getExternalSymbol("malloc", IntPtr),
857 setValue(&I, Result.first); // Pointers always fit in registers
858 DAG.setRoot(Result.second);
861 void SelectionDAGLowering::visitFree(FreeInst &I) {
862 std::vector<std::pair<SDOperand, const Type*> > Args;
863 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
864 TLI.getTargetData().getIntPtrType()));
865 MVT::ValueType IntPtr = TLI.getPointerTy();
866 std::pair<SDOperand,SDOperand> Result =
867 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
868 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
869 DAG.setRoot(Result.second);
872 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
873 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
874 // instructions are special in various ways, which require special support to
875 // insert. The specified MachineInstr is created but not inserted into any
876 // basic blocks, and the scheduler passes ownership of it to this method.
877 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
878 MachineBasicBlock *MBB) {
879 std::cerr << "If a target marks an instruction with "
880 "'usesCustomDAGSchedInserter', it must implement "
881 "TargetLowering::InsertAtEndOfBasicBlock!\n";
886 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
887 SDOperand VAListP, Value *VAListV,
889 // We have no sane default behavior, just emit a useful error message and bail
891 std::cerr << "Variable arguments handling not implemented on this target!\n";
896 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
898 // Default to a noop.
902 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
903 SDOperand SrcP, Value *SrcV,
904 SDOperand DestP, Value *DestV,
906 // Default to copying the input list.
907 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
908 SrcP, DAG.getSrcValue(SrcV));
909 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
910 Val, DestP, DAG.getSrcValue(DestV));
914 std::pair<SDOperand,SDOperand>
915 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
916 const Type *ArgTy, SelectionDAG &DAG) {
917 // We have no sane default behavior, just emit a useful error message and bail
919 std::cerr << "Variable arguments handling not implemented on this target!\n";
921 return std::make_pair(SDOperand(), SDOperand());
925 void SelectionDAGLowering::visitVAStart(CallInst &I) {
926 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
927 I.getOperand(1), DAG));
930 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
931 std::pair<SDOperand,SDOperand> Result =
932 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
934 setValue(&I, Result.first);
935 DAG.setRoot(Result.second);
938 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
939 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
940 I.getOperand(1), DAG));
943 void SelectionDAGLowering::visitVACopy(CallInst &I) {
945 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
946 getValue(I.getOperand(1)), I.getOperand(1), DAG);
951 // It is always conservatively correct for llvm.returnaddress and
952 // llvm.frameaddress to return 0.
953 std::pair<SDOperand, SDOperand>
954 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
955 unsigned Depth, SelectionDAG &DAG) {
956 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
959 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
960 assert(0 && "LowerOperation not implemented for this target!");
965 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
966 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
967 std::pair<SDOperand,SDOperand> Result =
968 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
969 setValue(&I, Result.first);
970 DAG.setRoot(Result.second);
973 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
974 std::vector<SDOperand> Ops;
975 Ops.push_back(getRoot());
976 Ops.push_back(getValue(I.getOperand(1)));
977 Ops.push_back(getValue(I.getOperand(2)));
978 Ops.push_back(getValue(I.getOperand(3)));
979 Ops.push_back(getValue(I.getOperand(4)));
980 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
983 //===----------------------------------------------------------------------===//
984 // SelectionDAGISel code
985 //===----------------------------------------------------------------------===//
987 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
988 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
991 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
992 // FIXME: we only modify the CFG to split critical edges. This
993 // updates dom and loop info.
997 bool SelectionDAGISel::runOnFunction(Function &Fn) {
998 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
999 RegMap = MF.getSSARegMap();
1000 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1002 // First pass, split all critical edges for PHI nodes with incoming values
1003 // that are constants, this way the load of the constant into a vreg will not
1004 // be placed into MBBs that are used some other way.
1005 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1007 for (BasicBlock::iterator BBI = BB->begin();
1008 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1009 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1010 if (isa<Constant>(PN->getIncomingValue(i)))
1011 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1014 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1016 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1017 SelectBasicBlock(I, MF, FuncInfo);
1023 SDOperand SelectionDAGISel::
1024 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1025 SDOperand Op = SDL.getValue(V);
1026 assert((Op.getOpcode() != ISD::CopyFromReg ||
1027 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1028 "Copy from a reg to the same reg!");
1030 // If this type is not legal, we must make sure to not create an invalid
1032 MVT::ValueType SrcVT = Op.getValueType();
1033 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1034 SelectionDAG &DAG = SDL.DAG;
1035 if (SrcVT == DestVT) {
1036 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1037 } else if (SrcVT < DestVT) {
1038 // The src value is promoted to the register.
1039 if (MVT::isFloatingPoint(SrcVT))
1040 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1042 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1043 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1045 // The src value is expanded into multiple registers.
1046 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1047 Op, DAG.getConstant(0, MVT::i32));
1048 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1049 Op, DAG.getConstant(1, MVT::i32));
1050 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1051 return DAG.getCopyToReg(Op, Reg+1, Hi);
1055 /// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1056 /// single basic block, return that block. Otherwise, return a null pointer.
1057 static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1058 if (A->use_empty()) return 0;
1059 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1060 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1062 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1063 return 0; // Disagreement among the users?
1065 // Okay, there is a single BB user. Only permit this optimization if this is
1066 // the entry block, otherwise, we might sink argument loads into loops and
1067 // stuff. Later, when we have global instruction selection, this won't be an
1069 if (BB == BB->getParent()->begin())
1074 void SelectionDAGISel::
1075 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1076 std::vector<SDOperand> &UnorderedChains) {
1077 // If this is the entry block, emit arguments.
1078 Function &F = *BB->getParent();
1079 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1081 if (BB == &F.front()) {
1082 SDOperand OldRoot = SDL.DAG.getRoot();
1084 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1086 // If there were side effects accessing the argument list, do not do
1087 // anything special.
1088 if (OldRoot != SDL.DAG.getRoot()) {
1090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1092 if (!AI->use_empty()) {
1093 SDL.setValue(AI, Args[a]);
1096 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1097 UnorderedChains.push_back(Copy);
1100 // Otherwise, if any argument is only accessed in a single basic block,
1101 // emit that argument only to that basic block.
1103 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1105 if (!AI->use_empty()) {
1106 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1107 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1108 std::make_pair(AI, a)));
1110 SDL.setValue(AI, Args[a]);
1112 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1113 UnorderedChains.push_back(Copy);
1118 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1121 // See if there are any block-local arguments that need to be emitted in this
1124 if (!FuncInfo.BlockLocalArguments.empty()) {
1125 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1126 FuncInfo.BlockLocalArguments.lower_bound(BB);
1127 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1128 // Lower the arguments into this block.
1129 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1131 // Set up the value mapping for the local arguments.
1132 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1134 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
1136 // Any dead arguments will just be ignored here.
1142 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1143 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1144 FunctionLoweringInfo &FuncInfo) {
1145 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1147 std::vector<SDOperand> UnorderedChains;
1149 // Lower any arguments needed in this block.
1150 LowerArguments(LLVMBB, SDL, UnorderedChains);
1152 BB = FuncInfo.MBBMap[LLVMBB];
1153 SDL.setCurrentBasicBlock(BB);
1155 // Lower all of the non-terminator instructions.
1156 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1160 // Ensure that all instructions which are used outside of their defining
1161 // blocks are available as virtual registers.
1162 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1163 if (!I->use_empty() && !isa<PHINode>(I)) {
1164 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1165 if (VMI != FuncInfo.ValueMap.end())
1166 UnorderedChains.push_back(
1167 CopyValueToVirtualRegister(SDL, I, VMI->second));
1170 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1171 // ensure constants are generated when needed. Remember the virtual registers
1172 // that need to be added to the Machine PHI nodes as input. We cannot just
1173 // directly add them, because expansion might result in multiple MBB's for one
1174 // BB. As such, the start of the BB might correspond to a different MBB than
1178 // Emit constants only once even if used by multiple PHI nodes.
1179 std::map<Constant*, unsigned> ConstantsOut;
1181 // Check successor nodes PHI nodes that expect a constant to be available from
1183 TerminatorInst *TI = LLVMBB->getTerminator();
1184 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1185 BasicBlock *SuccBB = TI->getSuccessor(succ);
1186 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1189 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1190 // nodes and Machine PHI nodes, but the incoming operands have not been
1192 for (BasicBlock::iterator I = SuccBB->begin();
1193 (PN = dyn_cast<PHINode>(I)); ++I)
1194 if (!PN->use_empty()) {
1196 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1197 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1198 unsigned &RegOut = ConstantsOut[C];
1200 RegOut = FuncInfo.CreateRegForValue(C);
1201 UnorderedChains.push_back(
1202 CopyValueToVirtualRegister(SDL, C, RegOut));
1206 Reg = FuncInfo.ValueMap[PHIOp];
1208 assert(isa<AllocaInst>(PHIOp) &&
1209 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1210 "Didn't codegen value into a register!??");
1211 Reg = FuncInfo.CreateRegForValue(PHIOp);
1212 UnorderedChains.push_back(
1213 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1217 // Remember that this register needs to added to the machine PHI node as
1218 // the input for this MBB.
1219 unsigned NumElements =
1220 TLI.getNumElements(TLI.getValueType(PN->getType()));
1221 for (unsigned i = 0, e = NumElements; i != e; ++i)
1222 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1225 ConstantsOut.clear();
1227 // Turn all of the unordered chains into one factored node.
1228 if (!UnorderedChains.empty()) {
1229 UnorderedChains.push_back(SDL.getRoot());
1230 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1233 // Lower the terminator after the copies are emitted.
1234 SDL.visit(*LLVMBB->getTerminator());
1236 // Make sure the root of the DAG is up-to-date.
1237 DAG.setRoot(SDL.getRoot());
1240 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1241 FunctionLoweringInfo &FuncInfo) {
1242 SelectionDAG DAG(TLI, MF);
1244 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1246 // First step, lower LLVM code to some DAG. This DAG may use operations and
1247 // types that are not supported by the target.
1248 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1250 // Run the DAG combiner in pre-legalize mode, if we are told to do so
1251 if (CombinerEnabled) DAG.Combine(false);
1253 DEBUG(std::cerr << "Lowered selection DAG:\n");
1256 // Second step, hack on the DAG until it only uses operations and types that
1257 // the target supports.
1260 DEBUG(std::cerr << "Legalized selection DAG:\n");
1263 if (ViewDAGs) DAG.viewGraph();
1265 // Run the DAG combiner in post-legalize mode, if we are told to do so
1266 if (CombinerEnabled) DAG.Combine(true);
1268 // Third, instruction select all of the operations to machine code, adding the
1269 // code to the MachineBasicBlock.
1270 InstructionSelectBasicBlock(DAG);
1272 DEBUG(std::cerr << "Selected machine code:\n");
1275 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1276 // PHI nodes in successors.
1277 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1278 MachineInstr *PHI = PHINodesToUpdate[i].first;
1279 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1280 "This is not a machine PHI node that we are updating!");
1281 PHI->addRegOperand(PHINodesToUpdate[i].second);
1282 PHI->addMachineBasicBlockOperand(BB);
1285 // Finally, add the CFG edges from the last selected MBB to the successor
1287 TerminatorInst *TI = LLVMBB->getTerminator();
1288 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1289 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1290 BB->addSuccessor(Succ0MBB);