blob: 1ccbdd7d0b044a713c96395bda3abeae82090bed [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/SelectionDAG.h"
25#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetFrameInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetMachine.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/Support/Debug.h"
33#include <map>
34#include <iostream>
35using namespace llvm;
36
Chris Lattnere05a4612005-01-12 03:41:21 +000037#ifndef _NDEBUG
38static cl::opt<bool>
39ViewDAGs("view-isel-dags", cl::Hidden,
40 cl::desc("Pop up a window to show isel dags as they are selected"));
41#else
42static const bool ViewDAGS = 0;
43#endif
44
Chris Lattner7a60d912005-01-07 07:47:53 +000045namespace llvm {
46 //===--------------------------------------------------------------------===//
47 /// FunctionLoweringInfo - This contains information that is global to a
48 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000049 class FunctionLoweringInfo {
50 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000051 TargetLowering &TLI;
52 Function &Fn;
53 MachineFunction &MF;
54 SSARegMap *RegMap;
55
56 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
57
58 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
59 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
60
61 /// ValueMap - Since we emit code for the function a basic block at a time,
62 /// we must remember which virtual registers hold the values for
63 /// cross-basic-block values.
64 std::map<const Value*, unsigned> ValueMap;
65
66 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
67 /// the entry block. This allows the allocas to be efficiently referenced
68 /// anywhere in the function.
69 std::map<const AllocaInst*, int> StaticAllocaMap;
70
Chris Lattnere3c2cf42005-01-17 17:55:19 +000071 /// BlockLocalArguments - If any arguments are only used in a single basic
72 /// block, and if the target can access the arguments without side-effects,
73 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
74 /// track of which arguments are local to each BB.
75 std::multimap<BasicBlock*, std::pair<Argument*,
76 unsigned> > BlockLocalArguments;
77
78
Chris Lattner7a60d912005-01-07 07:47:53 +000079 unsigned MakeReg(MVT::ValueType VT) {
80 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
81 }
82
83 unsigned CreateRegForValue(const Value *V) {
84 MVT::ValueType VT = TLI.getValueType(V->getType());
85 // The common case is that we will only create one register for this
86 // value. If we have that case, create and return the virtual register.
87 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000088 if (NV == 1) {
89 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000090 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000091 }
Chris Lattner7a60d912005-01-07 07:47:53 +000092
93 // If this value is represented with multiple target registers, make sure
94 // to create enough consequtive registers of the right (smaller) type.
95 unsigned NT = VT-1; // Find the type to use.
96 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
97 --NT;
98
99 unsigned R = MakeReg((MVT::ValueType)NT);
100 for (unsigned i = 1; i != NV; ++i)
101 MakeReg((MVT::ValueType)NT);
102 return R;
103 }
104
105 unsigned InitializeRegForValue(const Value *V) {
106 unsigned &R = ValueMap[V];
107 assert(R == 0 && "Already initialized this value register!");
108 return R = CreateRegForValue(V);
109 }
110 };
111}
112
113/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
114/// PHI nodes or outside of the basic block that defines it.
115static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
116 if (isa<PHINode>(I)) return true;
117 BasicBlock *BB = I->getParent();
118 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
119 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
120 return true;
121 return false;
122}
123
124FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
125 Function &fn, MachineFunction &mf)
126 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
127
128 // Initialize the mapping of values to registers. This is only set up for
129 // instruction values that are used outside of the block that defines
130 // them.
131 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
132 InitializeRegForValue(AI);
133
134 Function::iterator BB = Fn.begin(), E = Fn.end();
135 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
136 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
137 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
138 const Type *Ty = AI->getAllocatedType();
139 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
140 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
141 TySize *= CUI->getValue(); // Get total allocated size.
142 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000143 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000144 }
145
146 for (; BB != E; ++BB)
Chris Lattnerd0061952005-01-08 19:52:31 +0000147 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000148 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
149 if (!isa<AllocaInst>(I) ||
150 !StaticAllocaMap.count(cast<AllocaInst>(I)))
151 InitializeRegForValue(I);
152
153 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
154 // also creates the initial PHI MachineInstrs, though none of the input
155 // operands are populated.
156 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
157 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
158 MBBMap[BB] = MBB;
159 MF.getBasicBlockList().push_back(MBB);
160
161 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
162 // appropriate.
163 PHINode *PN;
164 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000165 (PN = dyn_cast<PHINode>(I)); ++I)
166 if (!PN->use_empty()) {
167 unsigned NumElements =
168 TLI.getNumElements(TLI.getValueType(PN->getType()));
169 unsigned PHIReg = ValueMap[PN];
170 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
171 for (unsigned i = 0; i != NumElements; ++i)
172 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
173 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 }
175}
176
177
178
179//===----------------------------------------------------------------------===//
180/// SelectionDAGLowering - This is the common target-independent lowering
181/// implementation that is parameterized by a TargetLowering object.
182/// Also, targets can overload any lowering method.
183///
184namespace llvm {
185class SelectionDAGLowering {
186 MachineBasicBlock *CurMBB;
187
188 std::map<const Value*, SDOperand> NodeMap;
189
190public:
191 // TLI - This is information that describes the available target features we
192 // need for lowering. This indicates when operations are unavailable,
193 // implemented with a libcall, etc.
194 TargetLowering &TLI;
195 SelectionDAG &DAG;
196 const TargetData &TD;
197
198 /// FuncInfo - Information about the function as a whole.
199 ///
200 FunctionLoweringInfo &FuncInfo;
201
202 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
203 FunctionLoweringInfo &funcinfo)
204 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
205 FuncInfo(funcinfo) {
206 }
207
Chris Lattner4108bb02005-01-17 19:43:36 +0000208 /// getRoot - Return the current virtual root of the Selection DAG.
209 ///
210 SDOperand getRoot() {
211 return DAG.getRoot();
212 }
213
Chris Lattner7a60d912005-01-07 07:47:53 +0000214 void visit(Instruction &I) { visit(I.getOpcode(), I); }
215
216 void visit(unsigned Opcode, User &I) {
217 switch (Opcode) {
218 default: assert(0 && "Unknown instruction type encountered!");
219 abort();
220 // Build the switch statement using the Instruction.def file.
221#define HANDLE_INST(NUM, OPCODE, CLASS) \
222 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
223#include "llvm/Instruction.def"
224 }
225 }
226
227 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
228
229
230 SDOperand getIntPtrConstant(uint64_t Val) {
231 return DAG.getConstant(Val, TLI.getPointerTy());
232 }
233
234 SDOperand getValue(const Value *V) {
235 SDOperand &N = NodeMap[V];
236 if (N.Val) return N;
237
238 MVT::ValueType VT = TLI.getValueType(V->getType());
239 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
240 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
241 visit(CE->getOpcode(), *CE);
242 assert(N.Val && "visit didn't populate the ValueMap!");
243 return N;
244 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
245 return N = DAG.getGlobalAddress(GV, VT);
246 } else if (isa<ConstantPointerNull>(C)) {
247 return N = DAG.getConstant(0, TLI.getPointerTy());
248 } else if (isa<UndefValue>(C)) {
249 /// FIXME: Implement UNDEFVALUE better.
250 if (MVT::isInteger(VT))
251 return N = DAG.getConstant(0, VT);
252 else if (MVT::isFloatingPoint(VT))
253 return N = DAG.getConstantFP(0, VT);
254 else
255 assert(0 && "Unknown value type!");
256
257 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
258 return N = DAG.getConstantFP(CFP->getValue(), VT);
259 } else {
260 // Canonicalize all constant ints to be unsigned.
261 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
262 }
263
264 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
265 std::map<const AllocaInst*, int>::iterator SI =
266 FuncInfo.StaticAllocaMap.find(AI);
267 if (SI != FuncInfo.StaticAllocaMap.end())
268 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
269 }
270
271 std::map<const Value*, unsigned>::const_iterator VMI =
272 FuncInfo.ValueMap.find(V);
273 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000274
275 MVT::ValueType RegVT = VT;
276 if (TLI.getTypeAction(VT) == 1) // Must promote this value?
277 RegVT = TLI.getTypeToTransformTo(VT);
278
279 N = DAG.getCopyFromReg(VMI->second, RegVT, DAG.getEntryNode());
280
281 if (RegVT != VT)
282 if (MVT::isFloatingPoint(VT))
283 N = DAG.getNode(ISD::FP_ROUND, VT, N);
284 else
285 N = DAG.getNode(ISD::TRUNCATE, VT, N);
286
287 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000288 }
289
290 const SDOperand &setValue(const Value *V, SDOperand NewN) {
291 SDOperand &N = NodeMap[V];
292 assert(N.Val == 0 && "Already set a value for this node!");
293 return N = NewN;
294 }
295
296 // Terminator instructions.
297 void visitRet(ReturnInst &I);
298 void visitBr(BranchInst &I);
299 void visitUnreachable(UnreachableInst &I) { /* noop */ }
300
301 // These all get lowered before this pass.
302 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
303 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
304 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
305
306 //
307 void visitBinary(User &I, unsigned Opcode);
308 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
309 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
310 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
311 void visitDiv(User &I) {
312 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
313 }
314 void visitRem(User &I) {
315 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
316 }
317 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
318 void visitOr (User &I) { visitBinary(I, ISD::OR); }
319 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
320 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
321 void visitShr(User &I) {
322 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
323 }
324
325 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
326 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
327 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
328 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
329 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
330 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
331 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
332
333 void visitGetElementPtr(User &I);
334 void visitCast(User &I);
335 void visitSelect(User &I);
336 //
337
338 void visitMalloc(MallocInst &I);
339 void visitFree(FreeInst &I);
340 void visitAlloca(AllocaInst &I);
341 void visitLoad(LoadInst &I);
342 void visitStore(StoreInst &I);
343 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
344 void visitCall(CallInst &I);
345
Chris Lattner7a60d912005-01-07 07:47:53 +0000346 void visitVAStart(CallInst &I);
347 void visitVANext(VANextInst &I);
348 void visitVAArg(VAArgInst &I);
349 void visitVAEnd(CallInst &I);
350 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000351 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000352
Chris Lattner875def92005-01-11 05:56:49 +0000353 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000354
355 void visitUserOp1(Instruction &I) {
356 assert(0 && "UserOp1 should not exist at instruction selection time!");
357 abort();
358 }
359 void visitUserOp2(Instruction &I) {
360 assert(0 && "UserOp2 should not exist at instruction selection time!");
361 abort();
362 }
363};
364} // end namespace llvm
365
366void SelectionDAGLowering::visitRet(ReturnInst &I) {
367 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000368 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000369 return;
370 }
371
372 SDOperand Op1 = getValue(I.getOperand(0));
373 switch (Op1.getValueType()) {
374 default: assert(0 && "Unknown value type!");
375 case MVT::i1:
376 case MVT::i8:
377 case MVT::i16:
378 // Extend integer types to 32-bits.
379 if (I.getOperand(0)->getType()->isSigned())
380 Op1 = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Op1);
381 else
382 Op1 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op1);
383 break;
384 case MVT::f32:
385 // Extend float to double.
386 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
387 break;
388 case MVT::i32:
389 case MVT::i64:
390 case MVT::f64:
391 break; // No extension needed!
392 }
393
Chris Lattner4108bb02005-01-17 19:43:36 +0000394 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000395}
396
397void SelectionDAGLowering::visitBr(BranchInst &I) {
398 // Update machine-CFG edges.
399 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
400 CurMBB->addSuccessor(Succ0MBB);
401
402 // Figure out which block is immediately after the current one.
403 MachineBasicBlock *NextBlock = 0;
404 MachineFunction::iterator BBI = CurMBB;
405 if (++BBI != CurMBB->getParent()->end())
406 NextBlock = BBI;
407
408 if (I.isUnconditional()) {
409 // If this is not a fall-through branch, emit the branch.
410 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000411 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000412 DAG.getBasicBlock(Succ0MBB)));
413 } else {
414 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
415 CurMBB->addSuccessor(Succ1MBB);
416
417 SDOperand Cond = getValue(I.getCondition());
418
419 if (Succ1MBB == NextBlock) {
420 // If the condition is false, fall through. This means we should branch
421 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000422 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000423 Cond, DAG.getBasicBlock(Succ0MBB)));
424 } else if (Succ0MBB == NextBlock) {
425 // If the condition is true, fall through. This means we should branch if
426 // the condition is false to Succ #1. Invert the condition first.
427 SDOperand True = DAG.getConstant(1, Cond.getValueType());
428 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000429 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 Cond, DAG.getBasicBlock(Succ1MBB)));
431 } else {
432 // Neither edge is a fall through. If the comparison is true, jump to
433 // Succ#0, otherwise branch unconditionally to succ #1.
Chris Lattner4108bb02005-01-17 19:43:36 +0000434 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000435 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner4108bb02005-01-17 19:43:36 +0000436 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000437 DAG.getBasicBlock(Succ1MBB)));
438 }
439 }
440}
441
442void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
443 SDOperand Op1 = getValue(I.getOperand(0));
444 SDOperand Op2 = getValue(I.getOperand(1));
445 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
446}
447
448void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
449 ISD::CondCode UnsignedOpcode) {
450 SDOperand Op1 = getValue(I.getOperand(0));
451 SDOperand Op2 = getValue(I.getOperand(1));
452 ISD::CondCode Opcode = SignedOpcode;
453 if (I.getOperand(0)->getType()->isUnsigned())
454 Opcode = UnsignedOpcode;
455 setValue(&I, DAG.getSetCC(Opcode, Op1, Op2));
456}
457
458void SelectionDAGLowering::visitSelect(User &I) {
459 SDOperand Cond = getValue(I.getOperand(0));
460 SDOperand TrueVal = getValue(I.getOperand(1));
461 SDOperand FalseVal = getValue(I.getOperand(2));
462 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
463 TrueVal, FalseVal));
464}
465
466void SelectionDAGLowering::visitCast(User &I) {
467 SDOperand N = getValue(I.getOperand(0));
468 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
469 MVT::ValueType DestTy = TLI.getValueType(I.getType());
470
471 if (N.getValueType() == DestTy) {
472 setValue(&I, N); // noop cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000473 } else if (isInteger(SrcTy)) {
474 if (isInteger(DestTy)) { // Int -> Int cast
475 if (DestTy < SrcTy) // Truncating cast?
476 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
477 else if (I.getOperand(0)->getType()->isSigned())
478 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
479 else
480 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
481 } else { // Int -> FP cast
482 if (I.getOperand(0)->getType()->isSigned())
483 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
484 else
485 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
486 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000487 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000488 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
489 if (isFloatingPoint(DestTy)) { // FP -> FP cast
490 if (DestTy < SrcTy) // Rounding cast?
491 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
492 else
493 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
494 } else { // FP -> Int cast.
495 if (I.getType()->isSigned())
496 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
497 else
498 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
499 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
501}
502
503void SelectionDAGLowering::visitGetElementPtr(User &I) {
504 SDOperand N = getValue(I.getOperand(0));
505 const Type *Ty = I.getOperand(0)->getType();
506 const Type *UIntPtrTy = TD.getIntPtrType();
507
508 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
509 OI != E; ++OI) {
510 Value *Idx = *OI;
511 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
512 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
513 if (Field) {
514 // N = N + Offset
515 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
516 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
517 getIntPtrConstant(Offset));
518 }
519 Ty = StTy->getElementType(Field);
520 } else {
521 Ty = cast<SequentialType>(Ty)->getElementType();
522 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
523 // N = N + Idx * ElementSize;
524 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000525 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
526
527 // If the index is smaller or larger than intptr_t, truncate or extend
528 // it.
529 if (IdxN.getValueType() < Scale.getValueType()) {
530 if (Idx->getType()->isSigned())
531 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
532 else
533 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
534 } else if (IdxN.getValueType() > Scale.getValueType())
535 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
536
537 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
538
Chris Lattner7a60d912005-01-07 07:47:53 +0000539 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
540 }
541 }
542 }
543 setValue(&I, N);
544}
545
546void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
547 // If this is a fixed sized alloca in the entry block of the function,
548 // allocate it statically on the stack.
549 if (FuncInfo.StaticAllocaMap.count(&I))
550 return; // getValue will auto-populate this.
551
552 const Type *Ty = I.getAllocatedType();
553 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
554 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
555
556 SDOperand AllocSize = getValue(I.getArraySize());
557
558 assert(AllocSize.getValueType() == TLI.getPointerTy() &&
559 "FIXME: should extend or truncate to pointer size!");
560
561 AllocSize = DAG.getNode(ISD::MUL, TLI.getPointerTy(), AllocSize,
562 getIntPtrConstant(TySize));
563
564 // Handle alignment. If the requested alignment is less than or equal to the
565 // stack alignment, ignore it and round the size of the allocation up to the
566 // stack alignment size. If the size is greater than the stack alignment, we
567 // note this in the DYNAMIC_STACKALLOC node.
568 unsigned StackAlign =
569 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
570 if (Align <= StackAlign) {
571 Align = 0;
572 // Add SA-1 to the size.
573 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
574 getIntPtrConstant(StackAlign-1));
575 // Mask out the low bits for alignment purposes.
576 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
577 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
578 }
579
580 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattner4108bb02005-01-17 19:43:36 +0000581 getRoot(), AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000582 getIntPtrConstant(Align));
583 DAG.setRoot(setValue(&I, DSA).getValue(1));
584
585 // Inform the Frame Information that we have just allocated a variable-sized
586 // object.
587 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
588}
589
590
591void SelectionDAGLowering::visitLoad(LoadInst &I) {
592 SDOperand Ptr = getValue(I.getOperand(0));
Chris Lattner4108bb02005-01-17 19:43:36 +0000593 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), getRoot(), Ptr);
Chris Lattner7a60d912005-01-07 07:47:53 +0000594 DAG.setRoot(setValue(&I, L).getValue(1));
595}
596
597
598void SelectionDAGLowering::visitStore(StoreInst &I) {
599 Value *SrcV = I.getOperand(0);
600 SDOperand Src = getValue(SrcV);
601 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner4108bb02005-01-17 19:43:36 +0000602 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr));
Chris Lattner7a60d912005-01-07 07:47:53 +0000603}
604
605void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000606 const char *RenameFn = 0;
Chris Lattner7a60d912005-01-07 07:47:53 +0000607 if (Function *F = I.getCalledFunction())
608 switch (F->getIntrinsicID()) {
609 case 0: break; // Not an intrinsic.
610 case Intrinsic::vastart: visitVAStart(I); return;
611 case Intrinsic::vaend: visitVAEnd(I); return;
612 case Intrinsic::vacopy: visitVACopy(I); return;
Chris Lattner58cfd792005-01-09 00:00:49 +0000613 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
614 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000615 default:
616 // FIXME: IMPLEMENT THESE.
617 // readport, writeport, readio, writeio
618 assert(0 && "This intrinsic is not implemented yet!");
619 return;
Chris Lattner18d2b342005-01-08 22:48:57 +0000620 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
621 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
Chris Lattner875def92005-01-11 05:56:49 +0000622 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
623 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
624 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000625
626 case Intrinsic::isunordered:
627 setValue(&I, DAG.getSetCC(ISD::SETUO, getValue(I.getOperand(1)),
628 getValue(I.getOperand(2))));
629 return;
630 }
631
Chris Lattner18d2b342005-01-08 22:48:57 +0000632 SDOperand Callee;
633 if (!RenameFn)
634 Callee = getValue(I.getOperand(0));
635 else
636 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000637 std::vector<std::pair<SDOperand, const Type*> > Args;
638
639 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
640 Value *Arg = I.getOperand(i);
641 SDOperand ArgNode = getValue(Arg);
642 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
643 }
644
Chris Lattner1f45cd72005-01-08 19:26:18 +0000645 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000646 TLI.LowerCallTo(getRoot(), I.getType(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000647 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000648 setValue(&I, Result.first);
649 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000650}
651
652void SelectionDAGLowering::visitMalloc(MallocInst &I) {
653 SDOperand Src = getValue(I.getOperand(0));
654
655 MVT::ValueType IntPtr = TLI.getPointerTy();
656 // FIXME: Extend or truncate to the intptr size.
657 assert(Src.getValueType() == IntPtr && "Need to adjust the amount!");
658
659 // Scale the source by the type size.
660 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
661 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
662 Src, getIntPtrConstant(ElementSize));
663
664 std::vector<std::pair<SDOperand, const Type*> > Args;
665 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000666
667 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000668 TLI.LowerCallTo(getRoot(), I.getType(),
Chris Lattner1f45cd72005-01-08 19:26:18 +0000669 DAG.getExternalSymbol("malloc", IntPtr),
670 Args, DAG);
671 setValue(&I, Result.first); // Pointers always fit in registers
672 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000673}
674
675void SelectionDAGLowering::visitFree(FreeInst &I) {
676 std::vector<std::pair<SDOperand, const Type*> > Args;
677 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
678 TLI.getTargetData().getIntPtrType()));
679 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000680 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000681 TLI.LowerCallTo(getRoot(), Type::VoidTy,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000682 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
683 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000684}
685
Chris Lattner58cfd792005-01-09 00:00:49 +0000686std::pair<SDOperand, SDOperand>
687TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000688 // We have no sane default behavior, just emit a useful error message and bail
689 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000690 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000691 abort();
692}
693
Chris Lattner58cfd792005-01-09 00:00:49 +0000694SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
695 SelectionDAG &DAG) {
696 // Default to a noop.
697 return Chain;
698}
699
700std::pair<SDOperand,SDOperand>
701TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
702 // Default to returning the input list.
703 return std::make_pair(L, Chain);
704}
705
706std::pair<SDOperand,SDOperand>
707TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
708 const Type *ArgTy, SelectionDAG &DAG) {
709 // We have no sane default behavior, just emit a useful error message and bail
710 // out.
711 std::cerr << "Variable arguments handling not implemented on this target!\n";
712 abort();
713}
714
715
716void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000717 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000718 setValue(&I, Result.first);
719 DAG.setRoot(Result.second);
720}
721
722void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
723 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000724 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000725 I.getType(), DAG);
726 setValue(&I, Result.first);
727 DAG.setRoot(Result.second);
728}
729
Chris Lattner7a60d912005-01-07 07:47:53 +0000730void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000731 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000732 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000733 I.getArgType(), DAG);
734 setValue(&I, Result.first);
735 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000736}
737
738void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000739 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000740}
741
742void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000743 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000744 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000745 setValue(&I, Result.first);
746 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000747}
748
Chris Lattner58cfd792005-01-09 00:00:49 +0000749
750// It is always conservatively correct for llvm.returnaddress and
751// llvm.frameaddress to return 0.
752std::pair<SDOperand, SDOperand>
753TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
754 unsigned Depth, SelectionDAG &DAG) {
755 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000756}
757
Chris Lattner897cd7d2005-01-16 07:28:41 +0000758SDOperand TargetLowering::LowerOperation(SDOperand Op) {
759 assert(0 && "LowerOperation not implemented for this target!");
760 abort();
761}
762
Chris Lattner58cfd792005-01-09 00:00:49 +0000763void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
764 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
765 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000766 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000767 setValue(&I, Result.first);
768 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000769}
770
Chris Lattner875def92005-01-11 05:56:49 +0000771void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
772 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000773 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000774 Ops.push_back(getValue(I.getOperand(1)));
775 Ops.push_back(getValue(I.getOperand(2)));
776 Ops.push_back(getValue(I.getOperand(3)));
777 Ops.push_back(getValue(I.getOperand(4)));
778 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000779}
780
Chris Lattner875def92005-01-11 05:56:49 +0000781//===----------------------------------------------------------------------===//
782// SelectionDAGISel code
783//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000784
785unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
786 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
787}
788
789
790
791bool SelectionDAGISel::runOnFunction(Function &Fn) {
792 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
793 RegMap = MF.getSSARegMap();
794 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
795
796 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
797
798 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
799 SelectBasicBlock(I, MF, FuncInfo);
800
801 return true;
802}
803
804
Chris Lattner718b5c22005-01-13 17:59:43 +0000805SDOperand SelectionDAGISel::
806CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000807 SelectionDAG &DAG = SDL.DAG;
Chris Lattner613f79f2005-01-11 22:03:46 +0000808 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +0000809 assert((Op.getOpcode() != ISD::CopyFromReg ||
810 cast<RegSDNode>(Op)->getReg() != Reg) &&
811 "Copy from a reg to the same reg!");
Chris Lattner209f5852005-01-16 02:23:07 +0000812 MVT::ValueType VT = Op.getValueType();
813 if (TLI.getTypeAction(VT) == 1) { // Must promote this value?
814 if (MVT::isFloatingPoint(VT))
815 Op = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(VT), Op);
816 else
817 Op = DAG.getNode(ISD::ZERO_EXTEND, TLI.getTypeToTransformTo(VT), Op);
818 }
819
Chris Lattner4108bb02005-01-17 19:43:36 +0000820 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner7a60d912005-01-07 07:47:53 +0000821}
822
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000823/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
824/// single basic block, return that block. Otherwise, return a null pointer.
825static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
826 if (A->use_empty()) return 0;
827 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
828 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
829 ++UI)
830 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
831 return 0; // Disagreement among the users?
832 return BB;
833}
834
Chris Lattner16f64df2005-01-17 17:15:02 +0000835void SelectionDAGISel::
836LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
837 std::vector<SDOperand> &UnorderedChains) {
838 // If this is the entry block, emit arguments.
839 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000840 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +0000841
842 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000843 SDOperand OldRoot = SDL.DAG.getRoot();
844
Chris Lattner16f64df2005-01-17 17:15:02 +0000845 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
846
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000847 // If there were side effects accessing the argument list, do not do
848 // anything special.
849 if (OldRoot != SDL.DAG.getRoot()) {
850 unsigned a = 0;
851 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI,++a)
852 if (!AI->use_empty()) {
853 SDL.setValue(AI, Args[a]);
854 SDOperand Copy =
855 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
856 UnorderedChains.push_back(Copy);
857 }
858 } else {
859 // Otherwise, if any argument is only accessed in a single basic block,
860 // emit that argument only to that basic block.
861 unsigned a = 0;
862 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI,++a)
863 if (!AI->use_empty()) {
864 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
865 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
866 std::make_pair(AI, a)));
867 } else {
868 SDL.setValue(AI, Args[a]);
869 SDOperand Copy =
870 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
871 UnorderedChains.push_back(Copy);
872 }
873 }
874 }
875 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000876
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000877 // See if there are any block-local arguments that need to be emitted in this
878 // block.
879
880 if (!FuncInfo.BlockLocalArguments.empty()) {
881 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
882 FuncInfo.BlockLocalArguments.lower_bound(BB);
883 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
884 // Lower the arguments into this block.
885 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
886
887 // Set up the value mapping for the local arguments.
888 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
889 ++BLAI)
890 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
891
892 // Any dead arguments will just be ignored here.
893 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000894 }
895}
896
897
Chris Lattner7a60d912005-01-07 07:47:53 +0000898void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
899 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
900 FunctionLoweringInfo &FuncInfo) {
901 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +0000902
903 std::vector<SDOperand> UnorderedChains;
Chris Lattner7a60d912005-01-07 07:47:53 +0000904
Chris Lattner16f64df2005-01-17 17:15:02 +0000905 // Lower any arguments needed in this block.
906 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +0000907
908 BB = FuncInfo.MBBMap[LLVMBB];
909 SDL.setCurrentBasicBlock(BB);
910
911 // Lower all of the non-terminator instructions.
912 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
913 I != E; ++I)
914 SDL.visit(*I);
915
916 // Ensure that all instructions which are used outside of their defining
917 // blocks are available as virtual registers.
918 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +0000919 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +0000920 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000921 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +0000922 UnorderedChains.push_back(
923 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +0000924 }
925
926 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
927 // ensure constants are generated when needed. Remember the virtual registers
928 // that need to be added to the Machine PHI nodes as input. We cannot just
929 // directly add them, because expansion might result in multiple MBB's for one
930 // BB. As such, the start of the BB might correspond to a different MBB than
931 // the end.
932 //
933
934 // Emit constants only once even if used by multiple PHI nodes.
935 std::map<Constant*, unsigned> ConstantsOut;
936
937 // Check successor nodes PHI nodes that expect a constant to be available from
938 // this block.
939 TerminatorInst *TI = LLVMBB->getTerminator();
940 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
941 BasicBlock *SuccBB = TI->getSuccessor(succ);
942 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
943 PHINode *PN;
944
945 // At this point we know that there is a 1-1 correspondence between LLVM PHI
946 // nodes and Machine PHI nodes, but the incoming operands have not been
947 // emitted yet.
948 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000949 (PN = dyn_cast<PHINode>(I)); ++I)
950 if (!PN->use_empty()) {
951 unsigned Reg;
952 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
953 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
954 unsigned &RegOut = ConstantsOut[C];
955 if (RegOut == 0) {
956 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +0000957 UnorderedChains.push_back(
958 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +0000959 }
960 Reg = RegOut;
961 } else {
962 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +0000963 if (Reg == 0) {
964 assert(isa<AllocaInst>(PHIOp) &&
965 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
966 "Didn't codegen value into a register!??");
967 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +0000968 UnorderedChains.push_back(
969 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +0000970 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000971 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000972
973 // Remember that this register needs to added to the machine PHI node as
974 // the input for this MBB.
975 unsigned NumElements =
976 TLI.getNumElements(TLI.getValueType(PN->getType()));
977 for (unsigned i = 0, e = NumElements; i != e; ++i)
978 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +0000979 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000980 }
981 ConstantsOut.clear();
982
Chris Lattner718b5c22005-01-13 17:59:43 +0000983 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +0000984 if (!UnorderedChains.empty()) {
985 UnorderedChains.push_back(DAG.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +0000986 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
987 }
988
Chris Lattner7a60d912005-01-07 07:47:53 +0000989 // Lower the terminator after the copies are emitted.
990 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +0000991
992 // Make sure the root of the DAG is up-to-date.
993 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +0000994}
995
996void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
997 FunctionLoweringInfo &FuncInfo) {
998 SelectionDAG DAG(TLI.getTargetMachine(), MF);
999 CurDAG = &DAG;
1000 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1001
1002 // First step, lower LLVM code to some DAG. This DAG may use operations and
1003 // types that are not supported by the target.
1004 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1005
1006 DEBUG(std::cerr << "Lowered selection DAG:\n");
1007 DEBUG(DAG.dump());
1008
1009 // Second step, hack on the DAG until it only uses operations and types that
1010 // the target supports.
1011 DAG.Legalize(TLI);
1012
1013 DEBUG(std::cerr << "Legalized selection DAG:\n");
1014 DEBUG(DAG.dump());
1015
1016 // Finally, instruction select all of the operations to machine code, adding
1017 // the code to the MachineBasicBlock.
1018 InstructionSelectBasicBlock(DAG);
1019
Chris Lattnere05a4612005-01-12 03:41:21 +00001020 if (ViewDAGs) DAG.viewGraph();
1021
Chris Lattner7a60d912005-01-07 07:47:53 +00001022 DEBUG(std::cerr << "Selected machine code:\n");
1023 DEBUG(BB->dump());
1024
1025 // Finally, now that we know what the last MBB the LLVM BB expanded is, update
1026 // PHI nodes in successors.
1027 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1028 MachineInstr *PHI = PHINodesToUpdate[i].first;
1029 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1030 "This is not a machine PHI node that we are updating!");
1031 PHI->addRegOperand(PHINodesToUpdate[i].second);
1032 PHI->addMachineBasicBlockOperand(BB);
1033 }
1034}