blob: bfceecb7aafce690526764cb31c339374ba0647b [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.
Chris Lattner531f9e92005-03-15 04:54:21 +0000131 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); AI != E; ++AI)
Chris Lattner7a60d912005-01-07 07:47:53 +0000132 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
Chris Lattner4d9651c2005-01-17 22:19:26 +0000190 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
191 /// them up and then emit token factor nodes when possible. This allows us to
192 /// get simple disambiguation between loads without worrying about alias
193 /// analysis.
194 std::vector<SDOperand> PendingLoads;
195
Chris Lattner7a60d912005-01-07 07:47:53 +0000196public:
197 // TLI - This is information that describes the available target features we
198 // need for lowering. This indicates when operations are unavailable,
199 // implemented with a libcall, etc.
200 TargetLowering &TLI;
201 SelectionDAG &DAG;
202 const TargetData &TD;
203
204 /// FuncInfo - Information about the function as a whole.
205 ///
206 FunctionLoweringInfo &FuncInfo;
207
208 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
209 FunctionLoweringInfo &funcinfo)
210 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
211 FuncInfo(funcinfo) {
212 }
213
Chris Lattner4108bb02005-01-17 19:43:36 +0000214 /// getRoot - Return the current virtual root of the Selection DAG.
215 ///
216 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000217 if (PendingLoads.empty())
218 return DAG.getRoot();
219
220 if (PendingLoads.size() == 1) {
221 SDOperand Root = PendingLoads[0];
222 DAG.setRoot(Root);
223 PendingLoads.clear();
224 return Root;
225 }
226
227 // Otherwise, we have to make a token factor node.
228 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
229 PendingLoads.clear();
230 DAG.setRoot(Root);
231 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000232 }
233
Chris Lattner7a60d912005-01-07 07:47:53 +0000234 void visit(Instruction &I) { visit(I.getOpcode(), I); }
235
236 void visit(unsigned Opcode, User &I) {
237 switch (Opcode) {
238 default: assert(0 && "Unknown instruction type encountered!");
239 abort();
240 // Build the switch statement using the Instruction.def file.
241#define HANDLE_INST(NUM, OPCODE, CLASS) \
242 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
243#include "llvm/Instruction.def"
244 }
245 }
246
247 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
248
249
250 SDOperand getIntPtrConstant(uint64_t Val) {
251 return DAG.getConstant(Val, TLI.getPointerTy());
252 }
253
254 SDOperand getValue(const Value *V) {
255 SDOperand &N = NodeMap[V];
256 if (N.Val) return N;
257
258 MVT::ValueType VT = TLI.getValueType(V->getType());
259 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
261 visit(CE->getOpcode(), *CE);
262 assert(N.Val && "visit didn't populate the ValueMap!");
263 return N;
264 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
265 return N = DAG.getGlobalAddress(GV, VT);
266 } else if (isa<ConstantPointerNull>(C)) {
267 return N = DAG.getConstant(0, TLI.getPointerTy());
268 } else if (isa<UndefValue>(C)) {
269 /// FIXME: Implement UNDEFVALUE better.
270 if (MVT::isInteger(VT))
271 return N = DAG.getConstant(0, VT);
272 else if (MVT::isFloatingPoint(VT))
273 return N = DAG.getConstantFP(0, VT);
274 else
275 assert(0 && "Unknown value type!");
276
277 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
278 return N = DAG.getConstantFP(CFP->getValue(), VT);
279 } else {
280 // Canonicalize all constant ints to be unsigned.
281 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
282 }
283
284 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
285 std::map<const AllocaInst*, int>::iterator SI =
286 FuncInfo.StaticAllocaMap.find(AI);
287 if (SI != FuncInfo.StaticAllocaMap.end())
288 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
289 }
290
291 std::map<const Value*, unsigned>::const_iterator VMI =
292 FuncInfo.ValueMap.find(V);
293 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000294
Chris Lattner9f2c4a52005-01-18 17:54:55 +0000295 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode());
Chris Lattner7a60d912005-01-07 07:47:53 +0000296 }
297
298 const SDOperand &setValue(const Value *V, SDOperand NewN) {
299 SDOperand &N = NodeMap[V];
300 assert(N.Val == 0 && "Already set a value for this node!");
301 return N = NewN;
302 }
303
304 // Terminator instructions.
305 void visitRet(ReturnInst &I);
306 void visitBr(BranchInst &I);
307 void visitUnreachable(UnreachableInst &I) { /* noop */ }
308
309 // These all get lowered before this pass.
310 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
311 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
312 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
313
314 //
315 void visitBinary(User &I, unsigned Opcode);
316 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000317 void visitSub(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000318 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
319 void visitDiv(User &I) {
320 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
321 }
322 void visitRem(User &I) {
323 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
324 }
325 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
326 void visitOr (User &I) { visitBinary(I, ISD::OR); }
327 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
328 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
329 void visitShr(User &I) {
330 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
331 }
332
333 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
334 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
335 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
336 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
337 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
338 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
339 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
340
341 void visitGetElementPtr(User &I);
342 void visitCast(User &I);
343 void visitSelect(User &I);
344 //
345
346 void visitMalloc(MallocInst &I);
347 void visitFree(FreeInst &I);
348 void visitAlloca(AllocaInst &I);
349 void visitLoad(LoadInst &I);
350 void visitStore(StoreInst &I);
351 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
352 void visitCall(CallInst &I);
353
Chris Lattner7a60d912005-01-07 07:47:53 +0000354 void visitVAStart(CallInst &I);
355 void visitVANext(VANextInst &I);
356 void visitVAArg(VAArgInst &I);
357 void visitVAEnd(CallInst &I);
358 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000359 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000360
Chris Lattner875def92005-01-11 05:56:49 +0000361 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000362
363 void visitUserOp1(Instruction &I) {
364 assert(0 && "UserOp1 should not exist at instruction selection time!");
365 abort();
366 }
367 void visitUserOp2(Instruction &I) {
368 assert(0 && "UserOp2 should not exist at instruction selection time!");
369 abort();
370 }
371};
372} // end namespace llvm
373
374void SelectionDAGLowering::visitRet(ReturnInst &I) {
375 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000376 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000377 return;
378 }
379
380 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000381 MVT::ValueType TmpVT;
382
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 switch (Op1.getValueType()) {
384 default: assert(0 && "Unknown value type!");
385 case MVT::i1:
386 case MVT::i8:
387 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000388 case MVT::i32:
389 // If this is a machine where 32-bits is legal or expanded, promote to
390 // 32-bits, otherwise, promote to 64-bits.
391 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
392 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000393 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000394 TmpVT = MVT::i32;
395
396 // Extend integer types to result type.
397 if (I.getOperand(0)->getType()->isSigned())
398 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
399 else
400 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000401 break;
402 case MVT::f32:
403 // Extend float to double.
404 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
405 break;
Chris Lattner7a60d912005-01-07 07:47:53 +0000406 case MVT::i64:
407 case MVT::f64:
408 break; // No extension needed!
409 }
410
Chris Lattner4108bb02005-01-17 19:43:36 +0000411 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000412}
413
414void SelectionDAGLowering::visitBr(BranchInst &I) {
415 // Update machine-CFG edges.
416 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000417
418 // Figure out which block is immediately after the current one.
419 MachineBasicBlock *NextBlock = 0;
420 MachineFunction::iterator BBI = CurMBB;
421 if (++BBI != CurMBB->getParent()->end())
422 NextBlock = BBI;
423
424 if (I.isUnconditional()) {
425 // If this is not a fall-through branch, emit the branch.
426 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000427 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 DAG.getBasicBlock(Succ0MBB)));
429 } else {
430 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000431
432 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 if (Succ1MBB == NextBlock) {
434 // If the condition is false, fall through. This means we should branch
435 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000436 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000437 Cond, DAG.getBasicBlock(Succ0MBB)));
438 } else if (Succ0MBB == NextBlock) {
439 // If the condition is true, fall through. This means we should branch if
440 // the condition is false to Succ #1. Invert the condition first.
441 SDOperand True = DAG.getConstant(1, Cond.getValueType());
442 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000443 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000444 Cond, DAG.getBasicBlock(Succ1MBB)));
445 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000446 std::vector<SDOperand> Ops;
447 Ops.push_back(getRoot());
448 Ops.push_back(Cond);
449 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
450 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
451 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000452 }
453 }
454}
455
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000456void SelectionDAGLowering::visitSub(User &I) {
457 // -0.0 - X --> fneg
458 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
459 if (CFP->isExactlyValue(-0.0)) {
460 SDOperand Op2 = getValue(I.getOperand(1));
461 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
462 return;
463 }
464
465 visitBinary(I, ISD::SUB);
466}
467
Chris Lattner7a60d912005-01-07 07:47:53 +0000468void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
469 SDOperand Op1 = getValue(I.getOperand(0));
470 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000471
472 if (isa<ShiftInst>(I))
473 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2);
474
Chris Lattner7a60d912005-01-07 07:47:53 +0000475 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
476}
477
478void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
479 ISD::CondCode UnsignedOpcode) {
480 SDOperand Op1 = getValue(I.getOperand(0));
481 SDOperand Op2 = getValue(I.getOperand(1));
482 ISD::CondCode Opcode = SignedOpcode;
483 if (I.getOperand(0)->getType()->isUnsigned())
484 Opcode = UnsignedOpcode;
Chris Lattnerb07e2d22005-01-18 02:52:03 +0000485 setValue(&I, DAG.getSetCC(Opcode, MVT::i1, Op1, Op2));
Chris Lattner7a60d912005-01-07 07:47:53 +0000486}
487
488void SelectionDAGLowering::visitSelect(User &I) {
489 SDOperand Cond = getValue(I.getOperand(0));
490 SDOperand TrueVal = getValue(I.getOperand(1));
491 SDOperand FalseVal = getValue(I.getOperand(2));
492 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
493 TrueVal, FalseVal));
494}
495
496void SelectionDAGLowering::visitCast(User &I) {
497 SDOperand N = getValue(I.getOperand(0));
498 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
499 MVT::ValueType DestTy = TLI.getValueType(I.getType());
500
501 if (N.getValueType() == DestTy) {
502 setValue(&I, N); // noop cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000503 } else if (isInteger(SrcTy)) {
504 if (isInteger(DestTy)) { // Int -> Int cast
505 if (DestTy < SrcTy) // Truncating cast?
506 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
507 else if (I.getOperand(0)->getType()->isSigned())
508 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
509 else
510 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
511 } else { // Int -> FP cast
512 if (I.getOperand(0)->getType()->isSigned())
513 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
514 else
515 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
516 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000517 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000518 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
519 if (isFloatingPoint(DestTy)) { // FP -> FP cast
520 if (DestTy < SrcTy) // Rounding cast?
521 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
522 else
523 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
524 } else { // FP -> Int cast.
525 if (I.getType()->isSigned())
526 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
527 else
528 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
529 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000530 }
531}
532
533void SelectionDAGLowering::visitGetElementPtr(User &I) {
534 SDOperand N = getValue(I.getOperand(0));
535 const Type *Ty = I.getOperand(0)->getType();
536 const Type *UIntPtrTy = TD.getIntPtrType();
537
538 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
539 OI != E; ++OI) {
540 Value *Idx = *OI;
541 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
542 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
543 if (Field) {
544 // N = N + Offset
545 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
546 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
547 getIntPtrConstant(Offset));
548 }
549 Ty = StTy->getElementType(Field);
550 } else {
551 Ty = cast<SequentialType>(Ty)->getElementType();
552 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
553 // N = N + Idx * ElementSize;
554 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000555 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
556
557 // If the index is smaller or larger than intptr_t, truncate or extend
558 // it.
559 if (IdxN.getValueType() < Scale.getValueType()) {
560 if (Idx->getType()->isSigned())
561 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
562 else
563 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
564 } else if (IdxN.getValueType() > Scale.getValueType())
565 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
566
567 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
568
Chris Lattner7a60d912005-01-07 07:47:53 +0000569 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
570 }
571 }
572 }
573 setValue(&I, N);
574}
575
576void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
577 // If this is a fixed sized alloca in the entry block of the function,
578 // allocate it statically on the stack.
579 if (FuncInfo.StaticAllocaMap.count(&I))
580 return; // getValue will auto-populate this.
581
582 const Type *Ty = I.getAllocatedType();
583 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
584 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
585
586 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000587 MVT::ValueType IntPtr = TLI.getPointerTy();
588 if (IntPtr < AllocSize.getValueType())
589 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
590 else if (IntPtr > AllocSize.getValueType())
591 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000592
Chris Lattnereccb73d2005-01-22 23:04:37 +0000593 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000594 getIntPtrConstant(TySize));
595
596 // Handle alignment. If the requested alignment is less than or equal to the
597 // stack alignment, ignore it and round the size of the allocation up to the
598 // stack alignment size. If the size is greater than the stack alignment, we
599 // note this in the DYNAMIC_STACKALLOC node.
600 unsigned StackAlign =
601 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
602 if (Align <= StackAlign) {
603 Align = 0;
604 // Add SA-1 to the size.
605 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
606 getIntPtrConstant(StackAlign-1));
607 // Mask out the low bits for alignment purposes.
608 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
609 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
610 }
611
612 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattner4108bb02005-01-17 19:43:36 +0000613 getRoot(), AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000614 getIntPtrConstant(Align));
615 DAG.setRoot(setValue(&I, DSA).getValue(1));
616
617 // Inform the Frame Information that we have just allocated a variable-sized
618 // object.
619 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
620}
621
622
623void SelectionDAGLowering::visitLoad(LoadInst &I) {
624 SDOperand Ptr = getValue(I.getOperand(0));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000625
626 SDOperand Root;
627 if (I.isVolatile())
628 Root = getRoot();
629 else {
630 // Do not serialize non-volatile loads against each other.
631 Root = DAG.getRoot();
632 }
633
634 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr);
635 setValue(&I, L);
636
637 if (I.isVolatile())
638 DAG.setRoot(L.getValue(1));
639 else
640 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000641}
642
643
644void SelectionDAGLowering::visitStore(StoreInst &I) {
645 Value *SrcV = I.getOperand(0);
646 SDOperand Src = getValue(SrcV);
647 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner4108bb02005-01-17 19:43:36 +0000648 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr));
Chris Lattner7a60d912005-01-07 07:47:53 +0000649}
650
651void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000652 const char *RenameFn = 0;
Chris Lattner7a60d912005-01-07 07:47:53 +0000653 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000654 if (F->isExternal())
655 switch (F->getIntrinsicID()) {
656 case 0: // Not an LLVM intrinsic.
657 if (F->getName() == "fabs" || F->getName() == "fabsf") {
658 if (I.getNumOperands() == 2 && // Basic sanity checks.
659 I.getOperand(1)->getType()->isFloatingPoint() &&
660 I.getType() == I.getOperand(1)->getType()) {
661 SDOperand Tmp = getValue(I.getOperand(1));
662 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
663 return;
664 }
665 }
666 break;
667 case Intrinsic::vastart: visitVAStart(I); return;
668 case Intrinsic::vaend: visitVAEnd(I); return;
669 case Intrinsic::vacopy: visitVACopy(I); return;
670 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
671 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
672 default:
673 // FIXME: IMPLEMENT THESE.
674 // readport, writeport, readio, writeio
675 assert(0 && "This intrinsic is not implemented yet!");
676 return;
677 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
678 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
679 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
680 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
681 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
682
683 case Intrinsic::isunordered:
684 setValue(&I, DAG.getSetCC(ISD::SETUO, MVT::i1,getValue(I.getOperand(1)),
685 getValue(I.getOperand(2))));
686 return;
687 case Intrinsic::pcmarker: {
688 SDOperand Num = getValue(I.getOperand(1));
689 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Num));
690 return;
691 }
692 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000693
Chris Lattner18d2b342005-01-08 22:48:57 +0000694 SDOperand Callee;
695 if (!RenameFn)
696 Callee = getValue(I.getOperand(0));
697 else
698 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000699 std::vector<std::pair<SDOperand, const Type*> > Args;
700
701 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
702 Value *Arg = I.getOperand(i);
703 SDOperand ArgNode = getValue(Arg);
704 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
705 }
706
Nate Begemanf6565252005-03-26 01:29:23 +0000707 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
708 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
709
Chris Lattner1f45cd72005-01-08 19:26:18 +0000710 std::pair<SDOperand,SDOperand> Result =
Nate Begemanf6565252005-03-26 01:29:23 +0000711 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000712 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000713 setValue(&I, Result.first);
714 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000715}
716
717void SelectionDAGLowering::visitMalloc(MallocInst &I) {
718 SDOperand Src = getValue(I.getOperand(0));
719
720 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000721
722 if (IntPtr < Src.getValueType())
723 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
724 else if (IntPtr > Src.getValueType())
725 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000726
727 // Scale the source by the type size.
728 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
729 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
730 Src, getIntPtrConstant(ElementSize));
731
732 std::vector<std::pair<SDOperand, const Type*> > Args;
733 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000734
735 std::pair<SDOperand,SDOperand> Result =
Nate Begemanf6565252005-03-26 01:29:23 +0000736 TLI.LowerCallTo(getRoot(), I.getType(), false,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000737 DAG.getExternalSymbol("malloc", IntPtr),
738 Args, DAG);
739 setValue(&I, Result.first); // Pointers always fit in registers
740 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000741}
742
743void SelectionDAGLowering::visitFree(FreeInst &I) {
744 std::vector<std::pair<SDOperand, const Type*> > Args;
745 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
746 TLI.getTargetData().getIntPtrType()));
747 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000748 std::pair<SDOperand,SDOperand> Result =
Nate Begemanf6565252005-03-26 01:29:23 +0000749 TLI.LowerCallTo(getRoot(), Type::VoidTy, false,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000750 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
751 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000752}
753
Chris Lattner58cfd792005-01-09 00:00:49 +0000754std::pair<SDOperand, SDOperand>
755TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000756 // We have no sane default behavior, just emit a useful error message and bail
757 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000758 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000759 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000760 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner7a60d912005-01-07 07:47:53 +0000761}
762
Chris Lattner58cfd792005-01-09 00:00:49 +0000763SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
764 SelectionDAG &DAG) {
765 // Default to a noop.
766 return Chain;
767}
768
769std::pair<SDOperand,SDOperand>
770TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
771 // Default to returning the input list.
772 return std::make_pair(L, Chain);
773}
774
775std::pair<SDOperand,SDOperand>
776TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
777 const Type *ArgTy, SelectionDAG &DAG) {
778 // We have no sane default behavior, just emit a useful error message and bail
779 // out.
780 std::cerr << "Variable arguments handling not implemented on this target!\n";
781 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000782 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000783}
784
785
786void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000787 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000788 setValue(&I, Result.first);
789 DAG.setRoot(Result.second);
790}
791
792void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
793 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000794 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000795 I.getType(), DAG);
796 setValue(&I, Result.first);
797 DAG.setRoot(Result.second);
798}
799
Chris Lattner7a60d912005-01-07 07:47:53 +0000800void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000801 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000802 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000803 I.getArgType(), DAG);
804 setValue(&I, Result.first);
805 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000806}
807
808void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000809 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000810}
811
812void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000813 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000814 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000815 setValue(&I, Result.first);
816 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000817}
818
Chris Lattner58cfd792005-01-09 00:00:49 +0000819
820// It is always conservatively correct for llvm.returnaddress and
821// llvm.frameaddress to return 0.
822std::pair<SDOperand, SDOperand>
823TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
824 unsigned Depth, SelectionDAG &DAG) {
825 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000826}
827
Chris Lattner897cd7d2005-01-16 07:28:41 +0000828SDOperand TargetLowering::LowerOperation(SDOperand Op) {
829 assert(0 && "LowerOperation not implemented for this target!");
830 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000831 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000832}
833
Chris Lattner58cfd792005-01-09 00:00:49 +0000834void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
835 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
836 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000837 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000838 setValue(&I, Result.first);
839 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000840}
841
Chris Lattner875def92005-01-11 05:56:49 +0000842void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
843 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000844 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000845 Ops.push_back(getValue(I.getOperand(1)));
846 Ops.push_back(getValue(I.getOperand(2)));
847 Ops.push_back(getValue(I.getOperand(3)));
848 Ops.push_back(getValue(I.getOperand(4)));
849 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000850}
851
Chris Lattner875def92005-01-11 05:56:49 +0000852//===----------------------------------------------------------------------===//
853// SelectionDAGISel code
854//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000855
856unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
857 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
858}
859
860
861
862bool SelectionDAGISel::runOnFunction(Function &Fn) {
863 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
864 RegMap = MF.getSSARegMap();
865 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
866
867 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
868
869 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
870 SelectBasicBlock(I, MF, FuncInfo);
871
872 return true;
873}
874
875
Chris Lattner718b5c22005-01-13 17:59:43 +0000876SDOperand SelectionDAGISel::
877CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000878 SelectionDAG &DAG = SDL.DAG;
Chris Lattner613f79f2005-01-11 22:03:46 +0000879 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +0000880 assert((Op.getOpcode() != ISD::CopyFromReg ||
881 cast<RegSDNode>(Op)->getReg() != Reg) &&
882 "Copy from a reg to the same reg!");
Chris Lattner4108bb02005-01-17 19:43:36 +0000883 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner7a60d912005-01-07 07:47:53 +0000884}
885
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000886/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
887/// single basic block, return that block. Otherwise, return a null pointer.
888static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
889 if (A->use_empty()) return 0;
890 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
891 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
892 ++UI)
893 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
894 return 0; // Disagreement among the users?
Chris Lattner0c56a542005-02-17 19:40:32 +0000895
896 // Okay, there is a single BB user. Only permit this optimization if this is
897 // the entry block, otherwise, we might sink argument loads into loops and
898 // stuff. Later, when we have global instruction selection, this won't be an
899 // issue clearly.
900 if (BB == BB->getParent()->begin())
901 return BB;
902 return 0;
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000903}
904
Chris Lattner16f64df2005-01-17 17:15:02 +0000905void SelectionDAGISel::
906LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
907 std::vector<SDOperand> &UnorderedChains) {
908 // If this is the entry block, emit arguments.
909 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000910 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +0000911
912 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000913 SDOperand OldRoot = SDL.DAG.getRoot();
914
Chris Lattner16f64df2005-01-17 17:15:02 +0000915 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
916
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000917 // If there were side effects accessing the argument list, do not do
918 // anything special.
919 if (OldRoot != SDL.DAG.getRoot()) {
920 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +0000921 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
922 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000923 if (!AI->use_empty()) {
924 SDL.setValue(AI, Args[a]);
925 SDOperand Copy =
926 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
927 UnorderedChains.push_back(Copy);
928 }
929 } else {
930 // Otherwise, if any argument is only accessed in a single basic block,
931 // emit that argument only to that basic block.
932 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +0000933 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
934 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000935 if (!AI->use_empty()) {
936 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
937 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
938 std::make_pair(AI, a)));
939 } else {
940 SDL.setValue(AI, Args[a]);
941 SDOperand Copy =
942 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
943 UnorderedChains.push_back(Copy);
944 }
945 }
946 }
947 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000948
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000949 // See if there are any block-local arguments that need to be emitted in this
950 // block.
951
952 if (!FuncInfo.BlockLocalArguments.empty()) {
953 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
954 FuncInfo.BlockLocalArguments.lower_bound(BB);
955 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
956 // Lower the arguments into this block.
957 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
958
959 // Set up the value mapping for the local arguments.
960 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
961 ++BLAI)
962 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
963
964 // Any dead arguments will just be ignored here.
965 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000966 }
967}
968
969
Chris Lattner7a60d912005-01-07 07:47:53 +0000970void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
971 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
972 FunctionLoweringInfo &FuncInfo) {
973 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +0000974
975 std::vector<SDOperand> UnorderedChains;
Chris Lattner7a60d912005-01-07 07:47:53 +0000976
Chris Lattner16f64df2005-01-17 17:15:02 +0000977 // Lower any arguments needed in this block.
978 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +0000979
980 BB = FuncInfo.MBBMap[LLVMBB];
981 SDL.setCurrentBasicBlock(BB);
982
983 // Lower all of the non-terminator instructions.
984 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
985 I != E; ++I)
986 SDL.visit(*I);
987
988 // Ensure that all instructions which are used outside of their defining
989 // blocks are available as virtual registers.
990 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +0000991 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +0000992 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000993 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +0000994 UnorderedChains.push_back(
995 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +0000996 }
997
998 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
999 // ensure constants are generated when needed. Remember the virtual registers
1000 // that need to be added to the Machine PHI nodes as input. We cannot just
1001 // directly add them, because expansion might result in multiple MBB's for one
1002 // BB. As such, the start of the BB might correspond to a different MBB than
1003 // the end.
1004 //
1005
1006 // Emit constants only once even if used by multiple PHI nodes.
1007 std::map<Constant*, unsigned> ConstantsOut;
1008
1009 // Check successor nodes PHI nodes that expect a constant to be available from
1010 // this block.
1011 TerminatorInst *TI = LLVMBB->getTerminator();
1012 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1013 BasicBlock *SuccBB = TI->getSuccessor(succ);
1014 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1015 PHINode *PN;
1016
1017 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1018 // nodes and Machine PHI nodes, but the incoming operands have not been
1019 // emitted yet.
1020 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001021 (PN = dyn_cast<PHINode>(I)); ++I)
1022 if (!PN->use_empty()) {
1023 unsigned Reg;
1024 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1025 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1026 unsigned &RegOut = ConstantsOut[C];
1027 if (RegOut == 0) {
1028 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001029 UnorderedChains.push_back(
1030 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001031 }
1032 Reg = RegOut;
1033 } else {
1034 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001035 if (Reg == 0) {
1036 assert(isa<AllocaInst>(PHIOp) &&
1037 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1038 "Didn't codegen value into a register!??");
1039 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001040 UnorderedChains.push_back(
1041 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001042 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001043 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00001044
1045 // Remember that this register needs to added to the machine PHI node as
1046 // the input for this MBB.
1047 unsigned NumElements =
1048 TLI.getNumElements(TLI.getValueType(PN->getType()));
1049 for (unsigned i = 0, e = NumElements; i != e; ++i)
1050 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001051 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001052 }
1053 ConstantsOut.clear();
1054
Chris Lattner718b5c22005-01-13 17:59:43 +00001055 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001056 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001057 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001058 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1059 }
1060
Chris Lattner7a60d912005-01-07 07:47:53 +00001061 // Lower the terminator after the copies are emitted.
1062 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001063
1064 // Make sure the root of the DAG is up-to-date.
1065 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001066}
1067
1068void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1069 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001070 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001071 CurDAG = &DAG;
1072 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1073
1074 // First step, lower LLVM code to some DAG. This DAG may use operations and
1075 // types that are not supported by the target.
1076 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1077
1078 DEBUG(std::cerr << "Lowered selection DAG:\n");
1079 DEBUG(DAG.dump());
1080
1081 // Second step, hack on the DAG until it only uses operations and types that
1082 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001083 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001084
1085 DEBUG(std::cerr << "Legalized selection DAG:\n");
1086 DEBUG(DAG.dump());
1087
Chris Lattner5ca31d92005-03-30 01:10:47 +00001088 // Third, instruction select all of the operations to machine code, adding the
1089 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001090 InstructionSelectBasicBlock(DAG);
1091
Chris Lattnere05a4612005-01-12 03:41:21 +00001092 if (ViewDAGs) DAG.viewGraph();
1093
Chris Lattner7a60d912005-01-07 07:47:53 +00001094 DEBUG(std::cerr << "Selected machine code:\n");
1095 DEBUG(BB->dump());
1096
Chris Lattner5ca31d92005-03-30 01:10:47 +00001097 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001098 // PHI nodes in successors.
1099 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1100 MachineInstr *PHI = PHINodesToUpdate[i].first;
1101 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1102 "This is not a machine PHI node that we are updating!");
1103 PHI->addRegOperand(PHINodesToUpdate[i].second);
1104 PHI->addMachineBasicBlockOperand(BB);
1105 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001106
1107 // Finally, add the CFG edges from the last selected MBB to the successor
1108 // MBBs.
1109 TerminatorInst *TI = LLVMBB->getTerminator();
1110 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1111 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1112 BB->addSuccessor(Succ0MBB);
1113 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001114}