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/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CodeGen/IntrinsicLowering.h"
25 #include "llvm/CodeGen/MachineDebugInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Debug.h"
47 ViewISelDAGs("view-isel-dags", cl::Hidden,
48 cl::desc("Pop up a window to show isel dags as they are selected"));
50 ViewSchedDAGs("view-sched-dags", cl::Hidden,
51 cl::desc("Pop up a window to show sched dags as they are processed"));
53 static const bool ViewISelDAGs = 0;
54 static const bool ViewSchedDAGs = 0;
58 //===--------------------------------------------------------------------===//
59 /// FunctionLoweringInfo - This contains information that is global to a
60 /// function that is used when lowering a region of the function.
61 class FunctionLoweringInfo {
68 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
70 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
71 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
73 /// ValueMap - Since we emit code for the function a basic block at a time,
74 /// we must remember which virtual registers hold the values for
75 /// cross-basic-block values.
76 std::map<const Value*, unsigned> ValueMap;
78 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
79 /// the entry block. This allows the allocas to be efficiently referenced
80 /// anywhere in the function.
81 std::map<const AllocaInst*, int> StaticAllocaMap;
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 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
129 /// entry block, return true.
130 static bool isOnlyUsedInEntryBlock(Argument *A) {
131 BasicBlock *Entry = A->getParent()->begin();
132 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
133 if (cast<Instruction>(*UI)->getParent() != Entry)
134 return false; // Use not in entry block.
138 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
139 Function &fn, MachineFunction &mf)
140 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
142 // Create a vreg for each argument register that is not dead and is used
143 // outside of the entry block for the function.
144 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
146 if (!isOnlyUsedInEntryBlock(AI))
147 InitializeRegForValue(AI);
149 // Initialize the mapping of values to registers. This is only set up for
150 // instruction values that are used outside of the block that defines
152 Function::iterator BB = Fn.begin(), EB = Fn.end();
153 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
154 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
155 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
156 const Type *Ty = AI->getAllocatedType();
157 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
159 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
162 // If the alignment of the value is smaller than the size of the value,
163 // and if the size of the value is particularly small (<= 8 bytes),
164 // round up to the size of the value for potentially better performance.
166 // FIXME: This could be made better with a preferred alignment hook in
167 // TargetData. It serves primarily to 8-byte align doubles for X86.
168 if (Align < TySize && TySize <= 8) Align = TySize;
169 TySize *= CUI->getValue(); // Get total allocated size.
170 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
171 StaticAllocaMap[AI] =
172 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
175 for (; BB != EB; ++BB)
176 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
177 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
178 if (!isa<AllocaInst>(I) ||
179 !StaticAllocaMap.count(cast<AllocaInst>(I)))
180 InitializeRegForValue(I);
182 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
183 // also creates the initial PHI MachineInstrs, though none of the input
184 // operands are populated.
185 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
186 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
188 MF.getBasicBlockList().push_back(MBB);
190 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
193 for (BasicBlock::iterator I = BB->begin();
194 (PN = dyn_cast<PHINode>(I)); ++I)
195 if (!PN->use_empty()) {
196 unsigned NumElements =
197 TLI.getNumElements(TLI.getValueType(PN->getType()));
198 unsigned PHIReg = ValueMap[PN];
199 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
200 for (unsigned i = 0; i != NumElements; ++i)
201 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
208 //===----------------------------------------------------------------------===//
209 /// SelectionDAGLowering - This is the common target-independent lowering
210 /// implementation that is parameterized by a TargetLowering object.
211 /// Also, targets can overload any lowering method.
214 class SelectionDAGLowering {
215 MachineBasicBlock *CurMBB;
217 std::map<const Value*, SDOperand> NodeMap;
219 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
220 /// them up and then emit token factor nodes when possible. This allows us to
221 /// get simple disambiguation between loads without worrying about alias
223 std::vector<SDOperand> PendingLoads;
226 // TLI - This is information that describes the available target features we
227 // need for lowering. This indicates when operations are unavailable,
228 // implemented with a libcall, etc.
231 const TargetData &TD;
233 /// FuncInfo - Information about the function as a whole.
235 FunctionLoweringInfo &FuncInfo;
237 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
238 FunctionLoweringInfo &funcinfo)
239 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
243 /// getRoot - Return the current virtual root of the Selection DAG.
245 SDOperand getRoot() {
246 if (PendingLoads.empty())
247 return DAG.getRoot();
249 if (PendingLoads.size() == 1) {
250 SDOperand Root = PendingLoads[0];
252 PendingLoads.clear();
256 // Otherwise, we have to make a token factor node.
257 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
258 PendingLoads.clear();
263 void visit(Instruction &I) { visit(I.getOpcode(), I); }
265 void visit(unsigned Opcode, User &I) {
267 default: assert(0 && "Unknown instruction type encountered!");
269 // Build the switch statement using the Instruction.def file.
270 #define HANDLE_INST(NUM, OPCODE, CLASS) \
271 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
272 #include "llvm/Instruction.def"
276 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
279 SDOperand getIntPtrConstant(uint64_t Val) {
280 return DAG.getConstant(Val, TLI.getPointerTy());
283 SDOperand getValue(const Value *V) {
284 SDOperand &N = NodeMap[V];
287 const Type *VTy = V->getType();
288 MVT::ValueType VT = TLI.getValueType(VTy);
289 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
290 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
291 visit(CE->getOpcode(), *CE);
292 assert(N.Val && "visit didn't populate the ValueMap!");
294 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
295 return N = DAG.getGlobalAddress(GV, VT);
296 } else if (isa<ConstantPointerNull>(C)) {
297 return N = DAG.getConstant(0, TLI.getPointerTy());
298 } else if (isa<UndefValue>(C)) {
299 return N = DAG.getNode(ISD::UNDEF, VT);
300 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
301 return N = DAG.getConstantFP(CFP->getValue(), VT);
302 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
303 unsigned NumElements = PTy->getNumElements();
304 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
305 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
307 // Now that we know the number and type of the elements, push a
308 // Constant or ConstantFP node onto the ops list for each element of
309 // the packed constant.
310 std::vector<SDOperand> Ops;
311 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
312 if (MVT::isFloatingPoint(PVT)) {
313 for (unsigned i = 0; i != NumElements; ++i) {
314 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
315 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
318 for (unsigned i = 0; i != NumElements; ++i) {
319 const ConstantIntegral *El =
320 cast<ConstantIntegral>(CP->getOperand(i));
321 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
325 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
327 if (MVT::isFloatingPoint(PVT))
328 Op = DAG.getConstantFP(0, PVT);
330 Op = DAG.getConstant(0, PVT);
331 Ops.assign(NumElements, Op);
334 // Handle the case where we have a 1-element vector, in which
335 // case we want to immediately turn it into a scalar constant.
336 if (Ops.size() == 1) {
338 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
339 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
341 // If the packed type isn't legal, then create a ConstantVec node with
342 // generic Vector type instead.
343 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
346 // Canonicalize all constant ints to be unsigned.
347 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
350 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
351 std::map<const AllocaInst*, int>::iterator SI =
352 FuncInfo.StaticAllocaMap.find(AI);
353 if (SI != FuncInfo.StaticAllocaMap.end())
354 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
357 std::map<const Value*, unsigned>::const_iterator VMI =
358 FuncInfo.ValueMap.find(V);
359 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
361 unsigned InReg = VMI->second;
363 // If this type is not legal, make it so now.
364 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
366 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
368 // Source must be expanded. This input value is actually coming from the
369 // register pair VMI->second and VMI->second+1.
370 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
371 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
373 if (DestVT > VT) { // Promotion case
374 if (MVT::isFloatingPoint(VT))
375 N = DAG.getNode(ISD::FP_ROUND, VT, N);
377 N = DAG.getNode(ISD::TRUNCATE, VT, N);
384 const SDOperand &setValue(const Value *V, SDOperand NewN) {
385 SDOperand &N = NodeMap[V];
386 assert(N.Val == 0 && "Already set a value for this node!");
390 // Terminator instructions.
391 void visitRet(ReturnInst &I);
392 void visitBr(BranchInst &I);
393 void visitUnreachable(UnreachableInst &I) { /* noop */ }
395 // These all get lowered before this pass.
396 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
397 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
398 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
399 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
400 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
403 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
404 void visitShift(User &I, unsigned Opcode);
405 void visitAdd(User &I) {
406 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
408 void visitSub(User &I);
409 void visitMul(User &I) {
410 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
412 void visitDiv(User &I) {
413 const Type *Ty = I.getType();
414 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
416 void visitRem(User &I) {
417 const Type *Ty = I.getType();
418 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
420 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
421 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
422 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
423 void visitShl(User &I) { visitShift(I, ISD::SHL); }
424 void visitShr(User &I) {
425 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
428 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
429 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
430 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
431 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
432 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
433 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
434 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
436 void visitGetElementPtr(User &I);
437 void visitCast(User &I);
438 void visitSelect(User &I);
441 void visitMalloc(MallocInst &I);
442 void visitFree(FreeInst &I);
443 void visitAlloca(AllocaInst &I);
444 void visitLoad(LoadInst &I);
445 void visitStore(StoreInst &I);
446 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
447 void visitCall(CallInst &I);
448 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
450 void visitVAStart(CallInst &I);
451 void visitVAArg(VAArgInst &I);
452 void visitVAEnd(CallInst &I);
453 void visitVACopy(CallInst &I);
454 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
456 void visitMemIntrinsic(CallInst &I, unsigned Op);
458 void visitUserOp1(Instruction &I) {
459 assert(0 && "UserOp1 should not exist at instruction selection time!");
462 void visitUserOp2(Instruction &I) {
463 assert(0 && "UserOp2 should not exist at instruction selection time!");
467 } // end namespace llvm
469 void SelectionDAGLowering::visitRet(ReturnInst &I) {
470 if (I.getNumOperands() == 0) {
471 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
475 SDOperand Op1 = getValue(I.getOperand(0));
476 MVT::ValueType TmpVT;
478 switch (Op1.getValueType()) {
479 default: assert(0 && "Unknown value type!");
484 // If this is a machine where 32-bits is legal or expanded, promote to
485 // 32-bits, otherwise, promote to 64-bits.
486 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
487 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
491 // Extend integer types to result type.
492 if (I.getOperand(0)->getType()->isSigned())
493 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
495 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
498 // If this is a machine where f32 is promoted to f64, do so now.
499 if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
500 Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
504 break; // No extension needed!
506 // Allow targets to lower this further to meet ABI requirements
507 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
510 void SelectionDAGLowering::visitBr(BranchInst &I) {
511 // Update machine-CFG edges.
512 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
514 // Figure out which block is immediately after the current one.
515 MachineBasicBlock *NextBlock = 0;
516 MachineFunction::iterator BBI = CurMBB;
517 if (++BBI != CurMBB->getParent()->end())
520 if (I.isUnconditional()) {
521 // If this is not a fall-through branch, emit the branch.
522 if (Succ0MBB != NextBlock)
523 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
524 DAG.getBasicBlock(Succ0MBB)));
526 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
528 SDOperand Cond = getValue(I.getCondition());
529 if (Succ1MBB == NextBlock) {
530 // If the condition is false, fall through. This means we should branch
531 // if the condition is true to Succ #0.
532 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
533 Cond, DAG.getBasicBlock(Succ0MBB)));
534 } else if (Succ0MBB == NextBlock) {
535 // If the condition is true, fall through. This means we should branch if
536 // the condition is false to Succ #1. Invert the condition first.
537 SDOperand True = DAG.getConstant(1, Cond.getValueType());
538 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
539 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
540 Cond, DAG.getBasicBlock(Succ1MBB)));
542 std::vector<SDOperand> Ops;
543 Ops.push_back(getRoot());
545 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
546 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
547 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
552 void SelectionDAGLowering::visitSub(User &I) {
554 if (I.getType()->isFloatingPoint()) {
555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
556 if (CFP->isExactlyValue(-0.0)) {
557 SDOperand Op2 = getValue(I.getOperand(1));
558 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
562 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
565 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
567 const Type *Ty = I.getType();
568 SDOperand Op1 = getValue(I.getOperand(0));
569 SDOperand Op2 = getValue(I.getOperand(1));
571 if (Ty->isIntegral()) {
572 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
573 } else if (Ty->isFloatingPoint()) {
574 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
576 const PackedType *PTy = cast<PackedType>(Ty);
577 unsigned NumElements = PTy->getNumElements();
578 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
579 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
581 // Immediately scalarize packed types containing only one element, so that
582 // the Legalize pass does not have to deal with them. Similarly, if the
583 // abstract vector is going to turn into one that the target natively
584 // supports, generate that type now so that Legalize doesn't have to deal
585 // with that either. These steps ensure that Legalize only has to handle
586 // vector types in its Expand case.
587 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
588 if (NumElements == 1) {
589 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
590 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
591 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
593 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
594 SDOperand Typ = DAG.getValueType(PVT);
595 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
600 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
601 SDOperand Op1 = getValue(I.getOperand(0));
602 SDOperand Op2 = getValue(I.getOperand(1));
604 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
606 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
609 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
610 ISD::CondCode UnsignedOpcode) {
611 SDOperand Op1 = getValue(I.getOperand(0));
612 SDOperand Op2 = getValue(I.getOperand(1));
613 ISD::CondCode Opcode = SignedOpcode;
614 if (I.getOperand(0)->getType()->isUnsigned())
615 Opcode = UnsignedOpcode;
616 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
619 void SelectionDAGLowering::visitSelect(User &I) {
620 SDOperand Cond = getValue(I.getOperand(0));
621 SDOperand TrueVal = getValue(I.getOperand(1));
622 SDOperand FalseVal = getValue(I.getOperand(2));
623 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
627 void SelectionDAGLowering::visitCast(User &I) {
628 SDOperand N = getValue(I.getOperand(0));
629 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
630 MVT::ValueType DestTy = TLI.getValueType(I.getType());
632 if (N.getValueType() == DestTy) {
633 setValue(&I, N); // noop cast.
634 } else if (DestTy == MVT::i1) {
635 // Cast to bool is a comparison against zero, not truncation to zero.
636 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
637 DAG.getConstantFP(0.0, N.getValueType());
638 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
639 } else if (isInteger(SrcTy)) {
640 if (isInteger(DestTy)) { // Int -> Int cast
641 if (DestTy < SrcTy) // Truncating cast?
642 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
643 else if (I.getOperand(0)->getType()->isSigned())
644 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
646 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
647 } else { // Int -> FP cast
648 if (I.getOperand(0)->getType()->isSigned())
649 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
651 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
654 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
655 if (isFloatingPoint(DestTy)) { // FP -> FP cast
656 if (DestTy < SrcTy) // Rounding cast?
657 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
659 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
660 } else { // FP -> Int cast.
661 if (I.getType()->isSigned())
662 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
664 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
669 void SelectionDAGLowering::visitGetElementPtr(User &I) {
670 SDOperand N = getValue(I.getOperand(0));
671 const Type *Ty = I.getOperand(0)->getType();
672 const Type *UIntPtrTy = TD.getIntPtrType();
674 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
677 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
678 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
681 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
682 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
683 getIntPtrConstant(Offset));
685 Ty = StTy->getElementType(Field);
687 Ty = cast<SequentialType>(Ty)->getElementType();
689 // If this is a constant subscript, handle it quickly.
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
691 if (CI->getRawValue() == 0) continue;
694 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
695 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
697 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
698 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
702 // N = N + Idx * ElementSize;
703 uint64_t ElementSize = TD.getTypeSize(Ty);
704 SDOperand IdxN = getValue(Idx);
706 // If the index is smaller or larger than intptr_t, truncate or extend
708 if (IdxN.getValueType() < N.getValueType()) {
709 if (Idx->getType()->isSigned())
710 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
712 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
713 } else if (IdxN.getValueType() > N.getValueType())
714 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
716 // If this is a multiply by a power of two, turn it into a shl
717 // immediately. This is a very common case.
718 if (isPowerOf2_64(ElementSize)) {
719 unsigned Amt = Log2_64(ElementSize);
720 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
721 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
722 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
726 SDOperand Scale = getIntPtrConstant(ElementSize);
727 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
728 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
734 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
735 // If this is a fixed sized alloca in the entry block of the function,
736 // allocate it statically on the stack.
737 if (FuncInfo.StaticAllocaMap.count(&I))
738 return; // getValue will auto-populate this.
740 const Type *Ty = I.getAllocatedType();
741 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
742 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
745 SDOperand AllocSize = getValue(I.getArraySize());
746 MVT::ValueType IntPtr = TLI.getPointerTy();
747 if (IntPtr < AllocSize.getValueType())
748 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
749 else if (IntPtr > AllocSize.getValueType())
750 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
752 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
753 getIntPtrConstant(TySize));
755 // Handle alignment. If the requested alignment is less than or equal to the
756 // stack alignment, ignore it and round the size of the allocation up to the
757 // stack alignment size. If the size is greater than the stack alignment, we
758 // note this in the DYNAMIC_STACKALLOC node.
759 unsigned StackAlign =
760 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
761 if (Align <= StackAlign) {
763 // Add SA-1 to the size.
764 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
765 getIntPtrConstant(StackAlign-1));
766 // Mask out the low bits for alignment purposes.
767 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
768 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
771 std::vector<MVT::ValueType> VTs;
772 VTs.push_back(AllocSize.getValueType());
773 VTs.push_back(MVT::Other);
774 std::vector<SDOperand> Ops;
775 Ops.push_back(getRoot());
776 Ops.push_back(AllocSize);
777 Ops.push_back(getIntPtrConstant(Align));
778 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
779 DAG.setRoot(setValue(&I, DSA).getValue(1));
781 // Inform the Frame Information that we have just allocated a variable-sized
783 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
786 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
787 /// global into a string value. Return an empty string if we can't do it.
789 static std::string getStringValue(Value *V, unsigned Offset = 0) {
790 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
791 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
792 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
793 if (Init->isString()) {
794 std::string Result = Init->getAsString();
795 if (Offset < Result.size()) {
796 // If we are pointing INTO The string, erase the beginning...
797 Result.erase(Result.begin(), Result.begin()+Offset);
799 // Take off the null terminator, and any string fragments after it.
800 std::string::size_type NullPos = Result.find_first_of((char)0);
801 if (NullPos != std::string::npos)
802 Result.erase(Result.begin()+NullPos, Result.end());
807 } else if (Constant *C = dyn_cast<Constant>(V)) {
808 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
809 return getStringValue(GV, Offset);
810 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811 if (CE->getOpcode() == Instruction::GetElementPtr) {
812 // Turn a gep into the specified offset.
813 if (CE->getNumOperands() == 3 &&
814 cast<Constant>(CE->getOperand(1))->isNullValue() &&
815 isa<ConstantInt>(CE->getOperand(2))) {
816 return getStringValue(CE->getOperand(0),
817 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
825 void SelectionDAGLowering::visitLoad(LoadInst &I) {
826 SDOperand Ptr = getValue(I.getOperand(0));
832 // Do not serialize non-volatile loads against each other.
833 Root = DAG.getRoot();
836 const Type *Ty = I.getType();
839 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
840 unsigned NumElements = PTy->getNumElements();
841 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
842 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
844 // Immediately scalarize packed types containing only one element, so that
845 // the Legalize pass does not have to deal with them.
846 if (NumElements == 1) {
847 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
848 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
849 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
851 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
852 DAG.getSrcValue(I.getOperand(0)));
855 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
856 DAG.getSrcValue(I.getOperand(0)));
861 DAG.setRoot(L.getValue(1));
863 PendingLoads.push_back(L.getValue(1));
867 void SelectionDAGLowering::visitStore(StoreInst &I) {
868 Value *SrcV = I.getOperand(0);
869 SDOperand Src = getValue(SrcV);
870 SDOperand Ptr = getValue(I.getOperand(1));
871 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
872 DAG.getSrcValue(I.getOperand(1))));
875 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
876 /// we want to emit this as a call to a named external function, return the name
877 /// otherwise lower it and return null.
879 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
881 case Intrinsic::vastart: visitVAStart(I); return 0;
882 case Intrinsic::vaend: visitVAEnd(I); return 0;
883 case Intrinsic::vacopy: visitVACopy(I); return 0;
884 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
885 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
886 case Intrinsic::setjmp:
887 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
889 case Intrinsic::longjmp:
890 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
892 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
893 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
894 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
896 case Intrinsic::readport:
897 case Intrinsic::readio: {
898 std::vector<MVT::ValueType> VTs;
899 VTs.push_back(TLI.getValueType(I.getType()));
900 VTs.push_back(MVT::Other);
901 std::vector<SDOperand> Ops;
902 Ops.push_back(getRoot());
903 Ops.push_back(getValue(I.getOperand(1)));
904 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
905 ISD::READPORT : ISD::READIO, VTs, Ops);
908 DAG.setRoot(Tmp.getValue(1));
911 case Intrinsic::writeport:
912 case Intrinsic::writeio:
913 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
914 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
915 getRoot(), getValue(I.getOperand(1)),
916 getValue(I.getOperand(2))));
919 case Intrinsic::dbg_stoppoint: {
920 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
921 return "llvm_debugger_stop";
923 std::string fname = "<unknown>";
924 std::vector<SDOperand> Ops;
927 Ops.push_back(getRoot());
930 Ops.push_back(getValue(I.getOperand(2)));
933 Ops.push_back(getValue(I.getOperand(3)));
935 // filename/working dir
936 // Pull the filename out of the the compilation unit.
937 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
938 if (cunit && cunit->hasInitializer()) {
939 if (ConstantStruct *CS =
940 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
941 if (CS->getNumOperands() > 0) {
942 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
943 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
948 if (Ops.size() == 5) // Found filename/workingdir.
949 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
950 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
953 case Intrinsic::dbg_region_start:
954 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
955 return "llvm_dbg_region_start";
956 if (I.getType() != Type::VoidTy)
957 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
959 case Intrinsic::dbg_region_end:
960 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
961 return "llvm_dbg_region_end";
962 if (I.getType() != Type::VoidTy)
963 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
965 case Intrinsic::dbg_func_start:
966 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
967 return "llvm_dbg_subprogram";
968 if (I.getType() != Type::VoidTy)
969 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
971 case Intrinsic::dbg_declare:
972 if (I.getType() != Type::VoidTy)
973 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
976 case Intrinsic::isunordered_f32:
977 case Intrinsic::isunordered_f64:
978 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
979 getValue(I.getOperand(2)), ISD::SETUO));
982 case Intrinsic::sqrt_f32:
983 case Intrinsic::sqrt_f64:
984 setValue(&I, DAG.getNode(ISD::FSQRT,
985 getValue(I.getOperand(1)).getValueType(),
986 getValue(I.getOperand(1))));
988 case Intrinsic::pcmarker: {
989 SDOperand Tmp = getValue(I.getOperand(1));
990 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
993 case Intrinsic::readcyclecounter: {
994 std::vector<MVT::ValueType> VTs;
995 VTs.push_back(MVT::i64);
996 VTs.push_back(MVT::Other);
997 std::vector<SDOperand> Ops;
998 Ops.push_back(getRoot());
999 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1001 DAG.setRoot(Tmp.getValue(1));
1004 case Intrinsic::bswap_i16:
1005 case Intrinsic::bswap_i32:
1006 case Intrinsic::bswap_i64:
1007 setValue(&I, DAG.getNode(ISD::BSWAP,
1008 getValue(I.getOperand(1)).getValueType(),
1009 getValue(I.getOperand(1))));
1011 case Intrinsic::cttz_i8:
1012 case Intrinsic::cttz_i16:
1013 case Intrinsic::cttz_i32:
1014 case Intrinsic::cttz_i64:
1015 setValue(&I, DAG.getNode(ISD::CTTZ,
1016 getValue(I.getOperand(1)).getValueType(),
1017 getValue(I.getOperand(1))));
1019 case Intrinsic::ctlz_i8:
1020 case Intrinsic::ctlz_i16:
1021 case Intrinsic::ctlz_i32:
1022 case Intrinsic::ctlz_i64:
1023 setValue(&I, DAG.getNode(ISD::CTLZ,
1024 getValue(I.getOperand(1)).getValueType(),
1025 getValue(I.getOperand(1))));
1027 case Intrinsic::ctpop_i8:
1028 case Intrinsic::ctpop_i16:
1029 case Intrinsic::ctpop_i32:
1030 case Intrinsic::ctpop_i64:
1031 setValue(&I, DAG.getNode(ISD::CTPOP,
1032 getValue(I.getOperand(1)).getValueType(),
1033 getValue(I.getOperand(1))));
1035 case Intrinsic::stacksave: {
1036 std::vector<MVT::ValueType> VTs;
1037 VTs.push_back(TLI.getPointerTy());
1038 VTs.push_back(MVT::Other);
1039 std::vector<SDOperand> Ops;
1040 Ops.push_back(getRoot());
1041 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1043 DAG.setRoot(Tmp.getValue(1));
1046 case Intrinsic::stackrestore:
1047 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1048 getValue(I.getOperand(1))));
1050 case Intrinsic::prefetch:
1051 // FIXME: Currently discarding prefetches.
1055 assert(0 && "This intrinsic is not implemented yet!");
1061 void SelectionDAGLowering::visitCall(CallInst &I) {
1062 const char *RenameFn = 0;
1063 if (Function *F = I.getCalledFunction()) {
1064 if (F->isExternal())
1065 if (unsigned IID = F->getIntrinsicID()) {
1066 RenameFn = visitIntrinsicCall(I, IID);
1069 } else { // Not an LLVM intrinsic.
1070 const std::string &Name = F->getName();
1071 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1072 if (I.getNumOperands() == 2 && // Basic sanity checks.
1073 I.getOperand(1)->getType()->isFloatingPoint() &&
1074 I.getType() == I.getOperand(1)->getType()) {
1075 SDOperand Tmp = getValue(I.getOperand(1));
1076 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1079 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1080 if (I.getNumOperands() == 2 && // Basic sanity checks.
1081 I.getOperand(1)->getType()->isFloatingPoint() &&
1082 I.getType() == I.getOperand(1)->getType() &&
1083 TLI.isOperationLegal(ISD::FSIN,
1084 TLI.getValueType(I.getOperand(1)->getType()))) {
1085 SDOperand Tmp = getValue(I.getOperand(1));
1086 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1089 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1090 if (I.getNumOperands() == 2 && // Basic sanity checks.
1091 I.getOperand(1)->getType()->isFloatingPoint() &&
1092 I.getType() == I.getOperand(1)->getType() &&
1093 TLI.isOperationLegal(ISD::FCOS,
1094 TLI.getValueType(I.getOperand(1)->getType()))) {
1095 SDOperand Tmp = getValue(I.getOperand(1));
1096 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1105 Callee = getValue(I.getOperand(0));
1107 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1108 std::vector<std::pair<SDOperand, const Type*> > Args;
1109 Args.reserve(I.getNumOperands());
1110 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1111 Value *Arg = I.getOperand(i);
1112 SDOperand ArgNode = getValue(Arg);
1113 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1116 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1117 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1119 std::pair<SDOperand,SDOperand> Result =
1120 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1121 I.isTailCall(), Callee, Args, DAG);
1122 if (I.getType() != Type::VoidTy)
1123 setValue(&I, Result.first);
1124 DAG.setRoot(Result.second);
1127 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1128 SDOperand Src = getValue(I.getOperand(0));
1130 MVT::ValueType IntPtr = TLI.getPointerTy();
1132 if (IntPtr < Src.getValueType())
1133 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1134 else if (IntPtr > Src.getValueType())
1135 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1137 // Scale the source by the type size.
1138 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1139 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1140 Src, getIntPtrConstant(ElementSize));
1142 std::vector<std::pair<SDOperand, const Type*> > Args;
1143 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1145 std::pair<SDOperand,SDOperand> Result =
1146 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1147 DAG.getExternalSymbol("malloc", IntPtr),
1149 setValue(&I, Result.first); // Pointers always fit in registers
1150 DAG.setRoot(Result.second);
1153 void SelectionDAGLowering::visitFree(FreeInst &I) {
1154 std::vector<std::pair<SDOperand, const Type*> > Args;
1155 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1156 TLI.getTargetData().getIntPtrType()));
1157 MVT::ValueType IntPtr = TLI.getPointerTy();
1158 std::pair<SDOperand,SDOperand> Result =
1159 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1160 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1161 DAG.setRoot(Result.second);
1164 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1165 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1166 // instructions are special in various ways, which require special support to
1167 // insert. The specified MachineInstr is created but not inserted into any
1168 // basic blocks, and the scheduler passes ownership of it to this method.
1169 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1170 MachineBasicBlock *MBB) {
1171 std::cerr << "If a target marks an instruction with "
1172 "'usesCustomDAGSchedInserter', it must implement "
1173 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1178 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1179 SelectionDAG &DAG) {
1180 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1183 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1184 SDOperand VAListP, Value *VAListV,
1185 SelectionDAG &DAG) {
1186 // We have no sane default behavior, just emit a useful error message and bail
1188 std::cerr << "Variable arguments handling not implemented on this target!\n";
1193 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
1194 SelectionDAG &DAG) {
1195 // Default to a noop.
1199 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1200 SDOperand SrcP, Value *SrcV,
1201 SDOperand DestP, Value *DestV,
1202 SelectionDAG &DAG) {
1203 // Default to copying the input list.
1204 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1205 SrcP, DAG.getSrcValue(SrcV));
1206 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1207 Val, DestP, DAG.getSrcValue(DestV));
1211 std::pair<SDOperand,SDOperand>
1212 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1213 const Type *ArgTy, SelectionDAG &DAG) {
1214 // We have no sane default behavior, just emit a useful error message and bail
1216 std::cerr << "Variable arguments handling not implemented on this target!\n";
1218 return std::make_pair(SDOperand(), SDOperand());
1222 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1223 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1224 I.getOperand(1), DAG));
1227 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1228 std::pair<SDOperand,SDOperand> Result =
1229 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
1231 setValue(&I, Result.first);
1232 DAG.setRoot(Result.second);
1235 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1236 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
1237 I.getOperand(1), DAG));
1240 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1242 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1243 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1244 DAG.setRoot(Result);
1248 // It is always conservatively correct for llvm.returnaddress and
1249 // llvm.frameaddress to return 0.
1250 std::pair<SDOperand, SDOperand>
1251 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1252 unsigned Depth, SelectionDAG &DAG) {
1253 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1256 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1257 assert(0 && "LowerOperation not implemented for this target!");
1262 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1263 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1264 std::pair<SDOperand,SDOperand> Result =
1265 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1266 setValue(&I, Result.first);
1267 DAG.setRoot(Result.second);
1270 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1272 // If the size of the cpy/move/set is constant (known)
1273 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1274 uint64_t size = op3->getValue();
1277 if (size <= TLI.getMaxStoresPerMemSet()) {
1278 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1279 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1280 uint64_t align = op4.getValue();
1281 while (size > align) {
1284 Value *SrcV = I.getOperand(0);
1285 SDOperand Src = getValue(SrcV);
1286 SDOperand Ptr = getValue(I.getOperand(1));
1287 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1288 DAG.getSrcValue(I.getOperand(1))));
1292 break; // don't do this optimization, use a normal memset
1295 break; // FIXME: not implemented yet
1300 // Non-optimized version
1301 std::vector<SDOperand> Ops;
1302 Ops.push_back(getRoot());
1303 Ops.push_back(getValue(I.getOperand(1)));
1304 Ops.push_back(getValue(I.getOperand(2)));
1305 Ops.push_back(getValue(I.getOperand(3)));
1306 Ops.push_back(getValue(I.getOperand(4)));
1307 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1310 //===----------------------------------------------------------------------===//
1311 // SelectionDAGISel code
1312 //===----------------------------------------------------------------------===//
1314 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1315 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1318 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1319 // FIXME: we only modify the CFG to split critical edges. This
1320 // updates dom and loop info.
1324 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1325 /// casting to the type of GEPI.
1326 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1327 Value *Ptr, Value *PtrOffset) {
1328 if (V) return V; // Already computed.
1330 BasicBlock::iterator InsertPt;
1331 if (BB == GEPI->getParent()) {
1332 // If insert into the GEP's block, insert right after the GEP.
1336 // Otherwise, insert at the top of BB, after any PHI nodes
1337 InsertPt = BB->begin();
1338 while (isa<PHINode>(InsertPt)) ++InsertPt;
1341 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1342 // BB so that there is only one value live across basic blocks (the cast
1344 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1345 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1346 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1348 // Add the offset, cast it to the right type.
1349 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1350 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1355 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1356 /// selection, we want to be a bit careful about some things. In particular, if
1357 /// we have a GEP instruction that is used in a different block than it is
1358 /// defined, the addressing expression of the GEP cannot be folded into loads or
1359 /// stores that use it. In this case, decompose the GEP and move constant
1360 /// indices into blocks that use it.
1361 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1362 const TargetData &TD) {
1363 // If this GEP is only used inside the block it is defined in, there is no
1364 // need to rewrite it.
1365 bool isUsedOutsideDefBB = false;
1366 BasicBlock *DefBB = GEPI->getParent();
1367 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1369 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1370 isUsedOutsideDefBB = true;
1374 if (!isUsedOutsideDefBB) return;
1376 // If this GEP has no non-zero constant indices, there is nothing we can do,
1378 bool hasConstantIndex = false;
1379 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1380 E = GEPI->op_end(); OI != E; ++OI) {
1381 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1382 if (CI->getRawValue()) {
1383 hasConstantIndex = true;
1387 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1388 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1390 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1391 // constant offset (which we now know is non-zero) and deal with it later.
1392 uint64_t ConstantOffset = 0;
1393 const Type *UIntPtrTy = TD.getIntPtrType();
1394 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1395 const Type *Ty = GEPI->getOperand(0)->getType();
1397 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1398 E = GEPI->op_end(); OI != E; ++OI) {
1400 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1401 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1403 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1404 Ty = StTy->getElementType(Field);
1406 Ty = cast<SequentialType>(Ty)->getElementType();
1408 // Handle constant subscripts.
1409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1410 if (CI->getRawValue() == 0) continue;
1412 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1413 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1415 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1419 // Ptr = Ptr + Idx * ElementSize;
1421 // Cast Idx to UIntPtrTy if needed.
1422 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1424 uint64_t ElementSize = TD.getTypeSize(Ty);
1425 // Mask off bits that should not be set.
1426 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1427 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1429 // Multiply by the element size and add to the base.
1430 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1431 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1435 // Make sure that the offset fits in uintptr_t.
1436 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1437 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1439 // Okay, we have now emitted all of the variable index parts to the BB that
1440 // the GEP is defined in. Loop over all of the using instructions, inserting
1441 // an "add Ptr, ConstantOffset" into each block that uses it and update the
1442 // instruction to use the newly computed value, making GEPI dead. When the
1443 // user is a load or store instruction address, we emit the add into the user
1444 // block, otherwise we use a canonical version right next to the gep (these
1445 // won't be foldable as addresses, so we might as well share the computation).
1447 std::map<BasicBlock*,Value*> InsertedExprs;
1448 while (!GEPI->use_empty()) {
1449 Instruction *User = cast<Instruction>(GEPI->use_back());
1451 // If this use is not foldable into the addressing mode, use a version
1452 // emitted in the GEP block.
1454 if (!isa<LoadInst>(User) &&
1455 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1456 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1459 // Otherwise, insert the code in the User's block so it can be folded into
1460 // any users in that block.
1461 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
1462 User->getParent(), GEPI,
1465 User->replaceUsesOfWith(GEPI, NewVal);
1468 // Finally, the GEP is dead, remove it.
1469 GEPI->eraseFromParent();
1472 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1473 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1474 RegMap = MF.getSSARegMap();
1475 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1477 // First, split all critical edges for PHI nodes with incoming values that are
1478 // constants, this way the load of the constant into a vreg will not be placed
1479 // into MBBs that are used some other way.
1481 // In this pass we also look for GEP instructions that are used across basic
1482 // blocks and rewrites them to improve basic-block-at-a-time selection.
1484 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1486 BasicBlock::iterator BBI;
1487 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1488 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1489 if (isa<Constant>(PN->getIncomingValue(i)))
1490 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1492 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1493 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1494 OptimizeGEPExpression(GEPI, TLI.getTargetData());
1497 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1499 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1500 SelectBasicBlock(I, MF, FuncInfo);
1506 SDOperand SelectionDAGISel::
1507 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1508 SDOperand Op = SDL.getValue(V);
1509 assert((Op.getOpcode() != ISD::CopyFromReg ||
1510 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1511 "Copy from a reg to the same reg!");
1513 // If this type is not legal, we must make sure to not create an invalid
1515 MVT::ValueType SrcVT = Op.getValueType();
1516 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1517 SelectionDAG &DAG = SDL.DAG;
1518 if (SrcVT == DestVT) {
1519 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1520 } else if (SrcVT < DestVT) {
1521 // The src value is promoted to the register.
1522 if (MVT::isFloatingPoint(SrcVT))
1523 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1525 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1526 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1528 // The src value is expanded into multiple registers.
1529 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1530 Op, DAG.getConstant(0, MVT::i32));
1531 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1532 Op, DAG.getConstant(1, MVT::i32));
1533 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1534 return DAG.getCopyToReg(Op, Reg+1, Hi);
1538 void SelectionDAGISel::
1539 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1540 std::vector<SDOperand> &UnorderedChains) {
1541 // If this is the entry block, emit arguments.
1542 Function &F = *BB->getParent();
1543 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1544 SDOperand OldRoot = SDL.DAG.getRoot();
1545 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1548 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1550 if (!AI->use_empty()) {
1551 SDL.setValue(AI, Args[a]);
1553 // If this argument is live outside of the entry block, insert a copy from
1554 // whereever we got it to the vreg that other BB's will reference it as.
1555 if (FuncInfo.ValueMap.count(AI)) {
1557 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1558 UnorderedChains.push_back(Copy);
1562 // Next, if the function has live ins that need to be copied into vregs,
1563 // emit the copies now, into the top of the block.
1564 MachineFunction &MF = SDL.DAG.getMachineFunction();
1565 if (MF.livein_begin() != MF.livein_end()) {
1566 SSARegMap *RegMap = MF.getSSARegMap();
1567 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1568 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1569 E = MF.livein_end(); LI != E; ++LI)
1571 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1572 LI->first, RegMap->getRegClass(LI->second));
1575 // Finally, if the target has anything special to do, allow it to do so.
1576 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1580 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1581 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1582 FunctionLoweringInfo &FuncInfo) {
1583 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1585 std::vector<SDOperand> UnorderedChains;
1587 // Lower any arguments needed in this block if this is the entry block.
1588 if (LLVMBB == &LLVMBB->getParent()->front())
1589 LowerArguments(LLVMBB, SDL, UnorderedChains);
1591 BB = FuncInfo.MBBMap[LLVMBB];
1592 SDL.setCurrentBasicBlock(BB);
1594 // Lower all of the non-terminator instructions.
1595 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1599 // Ensure that all instructions which are used outside of their defining
1600 // blocks are available as virtual registers.
1601 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1602 if (!I->use_empty() && !isa<PHINode>(I)) {
1603 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1604 if (VMI != FuncInfo.ValueMap.end())
1605 UnorderedChains.push_back(
1606 CopyValueToVirtualRegister(SDL, I, VMI->second));
1609 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1610 // ensure constants are generated when needed. Remember the virtual registers
1611 // that need to be added to the Machine PHI nodes as input. We cannot just
1612 // directly add them, because expansion might result in multiple MBB's for one
1613 // BB. As such, the start of the BB might correspond to a different MBB than
1617 // Emit constants only once even if used by multiple PHI nodes.
1618 std::map<Constant*, unsigned> ConstantsOut;
1620 // Check successor nodes PHI nodes that expect a constant to be available from
1622 TerminatorInst *TI = LLVMBB->getTerminator();
1623 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1624 BasicBlock *SuccBB = TI->getSuccessor(succ);
1625 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1628 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1629 // nodes and Machine PHI nodes, but the incoming operands have not been
1631 for (BasicBlock::iterator I = SuccBB->begin();
1632 (PN = dyn_cast<PHINode>(I)); ++I)
1633 if (!PN->use_empty()) {
1635 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1636 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1637 unsigned &RegOut = ConstantsOut[C];
1639 RegOut = FuncInfo.CreateRegForValue(C);
1640 UnorderedChains.push_back(
1641 CopyValueToVirtualRegister(SDL, C, RegOut));
1645 Reg = FuncInfo.ValueMap[PHIOp];
1647 assert(isa<AllocaInst>(PHIOp) &&
1648 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1649 "Didn't codegen value into a register!??");
1650 Reg = FuncInfo.CreateRegForValue(PHIOp);
1651 UnorderedChains.push_back(
1652 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1656 // Remember that this register needs to added to the machine PHI node as
1657 // the input for this MBB.
1658 unsigned NumElements =
1659 TLI.getNumElements(TLI.getValueType(PN->getType()));
1660 for (unsigned i = 0, e = NumElements; i != e; ++i)
1661 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1664 ConstantsOut.clear();
1666 // Turn all of the unordered chains into one factored node.
1667 if (!UnorderedChains.empty()) {
1668 SDOperand Root = SDL.getRoot();
1669 if (Root.getOpcode() != ISD::EntryToken) {
1670 unsigned i = 0, e = UnorderedChains.size();
1671 for (; i != e; ++i) {
1672 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1673 if (UnorderedChains[i].Val->getOperand(0) == Root)
1674 break; // Don't add the root if we already indirectly depend on it.
1678 UnorderedChains.push_back(Root);
1680 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1683 // Lower the terminator after the copies are emitted.
1684 SDL.visit(*LLVMBB->getTerminator());
1686 // Make sure the root of the DAG is up-to-date.
1687 DAG.setRoot(SDL.getRoot());
1690 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1691 FunctionLoweringInfo &FuncInfo) {
1692 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1694 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1696 // First step, lower LLVM code to some DAG. This DAG may use operations and
1697 // types that are not supported by the target.
1698 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1700 // Run the DAG combiner in pre-legalize mode.
1703 DEBUG(std::cerr << "Lowered selection DAG:\n");
1706 // Second step, hack on the DAG until it only uses operations and types that
1707 // the target supports.
1710 DEBUG(std::cerr << "Legalized selection DAG:\n");
1713 // Run the DAG combiner in post-legalize mode.
1716 if (ViewISelDAGs) DAG.viewGraph();
1718 // Third, instruction select all of the operations to machine code, adding the
1719 // code to the MachineBasicBlock.
1720 InstructionSelectBasicBlock(DAG);
1722 DEBUG(std::cerr << "Selected machine code:\n");
1725 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1726 // PHI nodes in successors.
1727 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1728 MachineInstr *PHI = PHINodesToUpdate[i].first;
1729 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1730 "This is not a machine PHI node that we are updating!");
1731 PHI->addRegOperand(PHINodesToUpdate[i].second);
1732 PHI->addMachineBasicBlockOperand(BB);
1735 // Finally, add the CFG edges from the last selected MBB to the successor
1737 TerminatorInst *TI = LLVMBB->getTerminator();
1738 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1739 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1740 BB->addSuccessor(Succ0MBB);
1744 //===----------------------------------------------------------------------===//
1745 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1746 /// target node in the graph.
1747 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1748 if (ViewSchedDAGs) DAG.viewGraph();
1749 ScheduleDAG *SL = createSimpleDAGScheduler(DAG, BB);