blob: c4df0cdc27fb3ca7886079be20882bb06e0fe50c [file] [log] [blame]
Chris Lattner1c08c712005-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 Lattner7944d9d2005-01-12 03:41:21 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/Support/Debug.h"
33#include <map>
34#include <iostream>
35using namespace llvm;
36
Chris Lattner7944d9d2005-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 Lattner1c08c712005-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 Lattnerf26bc8e2005-01-08 19:52:31 +000049 class FunctionLoweringInfo {
50 public:
Chris Lattner1c08c712005-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 Lattner0afa8e32005-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 Lattner1c08c712005-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 Lattnerfb849802005-01-16 00:37:38 +000088 if (NV == 1) {
89 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000090 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000091 }
Chris Lattner1c08c712005-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 Lattnere4d5c442005-03-15 04:54:21 +0000131 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); AI != E; ++AI)
Chris Lattner1c08c712005-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 Lattnerf26bc8e2005-01-08 19:52:31 +0000143 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000144 }
145
146 for (; BB != E; ++BB)
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000147 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner1c08c712005-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 Lattnerf44fd882005-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 Lattner1c08c712005-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 Lattnerd3948112005-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 Lattner1c08c712005-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 Lattnera651cf62005-01-17 19:43:36 +0000214 /// getRoot - Return the current virtual root of the Selection DAG.
215 ///
216 SDOperand getRoot() {
Chris Lattnerd3948112005-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 Lattnera651cf62005-01-17 19:43:36 +0000232 }
233
Chris Lattner1c08c712005-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 Lattnerc8ea3c42005-01-16 02:23:07 +0000294
Chris Lattneref5cd1d2005-01-18 17:54:55 +0000295 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode());
Chris Lattner1c08c712005-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); }
317 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
318 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 Lattner1c08c712005-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 Lattner39ae3622005-01-09 00:00:49 +0000359 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000360
Chris Lattner7041ee32005-01-11 05:56:49 +0000361 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-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 Lattnera651cf62005-01-17 19:43:36 +0000376 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000377 return;
378 }
379
380 SDOperand Op1 = getValue(I.getOperand(0));
381 switch (Op1.getValueType()) {
382 default: assert(0 && "Unknown value type!");
383 case MVT::i1:
384 case MVT::i8:
385 case MVT::i16:
386 // Extend integer types to 32-bits.
387 if (I.getOperand(0)->getType()->isSigned())
388 Op1 = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Op1);
389 else
390 Op1 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op1);
391 break;
392 case MVT::f32:
393 // Extend float to double.
394 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
395 break;
396 case MVT::i32:
397 case MVT::i64:
398 case MVT::f64:
399 break; // No extension needed!
400 }
401
Chris Lattnera651cf62005-01-17 19:43:36 +0000402 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000403}
404
405void SelectionDAGLowering::visitBr(BranchInst &I) {
406 // Update machine-CFG edges.
407 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
408 CurMBB->addSuccessor(Succ0MBB);
409
410 // Figure out which block is immediately after the current one.
411 MachineBasicBlock *NextBlock = 0;
412 MachineFunction::iterator BBI = CurMBB;
413 if (++BBI != CurMBB->getParent()->end())
414 NextBlock = BBI;
415
416 if (I.isUnconditional()) {
417 // If this is not a fall-through branch, emit the branch.
418 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000419 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 DAG.getBasicBlock(Succ0MBB)));
421 } else {
422 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
423 CurMBB->addSuccessor(Succ1MBB);
424
425 SDOperand Cond = getValue(I.getCondition());
426
427 if (Succ1MBB == NextBlock) {
428 // If the condition is false, fall through. This means we should branch
429 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000430 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 Cond, DAG.getBasicBlock(Succ0MBB)));
432 } else if (Succ0MBB == NextBlock) {
433 // If the condition is true, fall through. This means we should branch if
434 // the condition is false to Succ #1. Invert the condition first.
435 SDOperand True = DAG.getConstant(1, Cond.getValueType());
436 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000437 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner1c08c712005-01-07 07:47:53 +0000438 Cond, DAG.getBasicBlock(Succ1MBB)));
439 } else {
440 // Neither edge is a fall through. If the comparison is true, jump to
441 // Succ#0, otherwise branch unconditionally to succ #1.
Chris Lattnera651cf62005-01-17 19:43:36 +0000442 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner1c08c712005-01-07 07:47:53 +0000443 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattnera651cf62005-01-17 19:43:36 +0000444 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner1c08c712005-01-07 07:47:53 +0000445 DAG.getBasicBlock(Succ1MBB)));
446 }
447 }
448}
449
450void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
451 SDOperand Op1 = getValue(I.getOperand(0));
452 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000453
454 if (isa<ShiftInst>(I))
455 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2);
456
Chris Lattner1c08c712005-01-07 07:47:53 +0000457 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
458}
459
460void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
461 ISD::CondCode UnsignedOpcode) {
462 SDOperand Op1 = getValue(I.getOperand(0));
463 SDOperand Op2 = getValue(I.getOperand(1));
464 ISD::CondCode Opcode = SignedOpcode;
465 if (I.getOperand(0)->getType()->isUnsigned())
466 Opcode = UnsignedOpcode;
Chris Lattnerf30b73b2005-01-18 02:52:03 +0000467 setValue(&I, DAG.getSetCC(Opcode, MVT::i1, Op1, Op2));
Chris Lattner1c08c712005-01-07 07:47:53 +0000468}
469
470void SelectionDAGLowering::visitSelect(User &I) {
471 SDOperand Cond = getValue(I.getOperand(0));
472 SDOperand TrueVal = getValue(I.getOperand(1));
473 SDOperand FalseVal = getValue(I.getOperand(2));
474 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
475 TrueVal, FalseVal));
476}
477
478void SelectionDAGLowering::visitCast(User &I) {
479 SDOperand N = getValue(I.getOperand(0));
480 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
481 MVT::ValueType DestTy = TLI.getValueType(I.getType());
482
483 if (N.getValueType() == DestTy) {
484 setValue(&I, N); // noop cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000485 } else if (isInteger(SrcTy)) {
486 if (isInteger(DestTy)) { // Int -> Int cast
487 if (DestTy < SrcTy) // Truncating cast?
488 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
489 else if (I.getOperand(0)->getType()->isSigned())
490 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
491 else
492 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
493 } else { // Int -> FP cast
494 if (I.getOperand(0)->getType()->isSigned())
495 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
496 else
497 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
498 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000500 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
501 if (isFloatingPoint(DestTy)) { // FP -> FP cast
502 if (DestTy < SrcTy) // Rounding cast?
503 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
504 else
505 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
506 } else { // FP -> Int cast.
507 if (I.getType()->isSigned())
508 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
509 else
510 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
511 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000512 }
513}
514
515void SelectionDAGLowering::visitGetElementPtr(User &I) {
516 SDOperand N = getValue(I.getOperand(0));
517 const Type *Ty = I.getOperand(0)->getType();
518 const Type *UIntPtrTy = TD.getIntPtrType();
519
520 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
521 OI != E; ++OI) {
522 Value *Idx = *OI;
523 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
524 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
525 if (Field) {
526 // N = N + Offset
527 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
528 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
529 getIntPtrConstant(Offset));
530 }
531 Ty = StTy->getElementType(Field);
532 } else {
533 Ty = cast<SequentialType>(Ty)->getElementType();
534 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
535 // N = N + Idx * ElementSize;
536 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner7cc47772005-01-07 21:56:57 +0000537 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
538
539 // If the index is smaller or larger than intptr_t, truncate or extend
540 // it.
541 if (IdxN.getValueType() < Scale.getValueType()) {
542 if (Idx->getType()->isSigned())
543 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
544 else
545 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
546 } else if (IdxN.getValueType() > Scale.getValueType())
547 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
548
549 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
550
Chris Lattner1c08c712005-01-07 07:47:53 +0000551 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
552 }
553 }
554 }
555 setValue(&I, N);
556}
557
558void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
559 // If this is a fixed sized alloca in the entry block of the function,
560 // allocate it statically on the stack.
561 if (FuncInfo.StaticAllocaMap.count(&I))
562 return; // getValue will auto-populate this.
563
564 const Type *Ty = I.getAllocatedType();
565 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
566 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
567
568 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000569 MVT::ValueType IntPtr = TLI.getPointerTy();
570 if (IntPtr < AllocSize.getValueType())
571 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
572 else if (IntPtr > AllocSize.getValueType())
573 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000574
Chris Lattner68cd65e2005-01-22 23:04:37 +0000575 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000576 getIntPtrConstant(TySize));
577
578 // Handle alignment. If the requested alignment is less than or equal to the
579 // stack alignment, ignore it and round the size of the allocation up to the
580 // stack alignment size. If the size is greater than the stack alignment, we
581 // note this in the DYNAMIC_STACKALLOC node.
582 unsigned StackAlign =
583 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
584 if (Align <= StackAlign) {
585 Align = 0;
586 // Add SA-1 to the size.
587 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
588 getIntPtrConstant(StackAlign-1));
589 // Mask out the low bits for alignment purposes.
590 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
591 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
592 }
593
594 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattnera651cf62005-01-17 19:43:36 +0000595 getRoot(), AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000596 getIntPtrConstant(Align));
597 DAG.setRoot(setValue(&I, DSA).getValue(1));
598
599 // Inform the Frame Information that we have just allocated a variable-sized
600 // object.
601 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
602}
603
604
605void SelectionDAGLowering::visitLoad(LoadInst &I) {
606 SDOperand Ptr = getValue(I.getOperand(0));
Chris Lattnerd3948112005-01-17 22:19:26 +0000607
608 SDOperand Root;
609 if (I.isVolatile())
610 Root = getRoot();
611 else {
612 // Do not serialize non-volatile loads against each other.
613 Root = DAG.getRoot();
614 }
615
616 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr);
617 setValue(&I, L);
618
619 if (I.isVolatile())
620 DAG.setRoot(L.getValue(1));
621 else
622 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000623}
624
625
626void SelectionDAGLowering::visitStore(StoreInst &I) {
627 Value *SrcV = I.getOperand(0);
628 SDOperand Src = getValue(SrcV);
629 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnera651cf62005-01-17 19:43:36 +0000630 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr));
Chris Lattner1c08c712005-01-07 07:47:53 +0000631}
632
633void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +0000634 const char *RenameFn = 0;
Chris Lattner1c08c712005-01-07 07:47:53 +0000635 if (Function *F = I.getCalledFunction())
636 switch (F->getIntrinsicID()) {
637 case 0: break; // Not an intrinsic.
638 case Intrinsic::vastart: visitVAStart(I); return;
639 case Intrinsic::vaend: visitVAEnd(I); return;
640 case Intrinsic::vacopy: visitVACopy(I); return;
Chris Lattner39ae3622005-01-09 00:00:49 +0000641 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
642 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000643 default:
644 // FIXME: IMPLEMENT THESE.
645 // readport, writeport, readio, writeio
646 assert(0 && "This intrinsic is not implemented yet!");
647 return;
Chris Lattner64e14b12005-01-08 22:48:57 +0000648 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
649 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
Chris Lattner7041ee32005-01-11 05:56:49 +0000650 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
651 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
652 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Chris Lattner1c08c712005-01-07 07:47:53 +0000653
654 case Intrinsic::isunordered:
Chris Lattnerf30b73b2005-01-18 02:52:03 +0000655 setValue(&I, DAG.getSetCC(ISD::SETUO, MVT::i1, getValue(I.getOperand(1)),
Chris Lattner1c08c712005-01-07 07:47:53 +0000656 getValue(I.getOperand(2))));
657 return;
658 }
659
Chris Lattner64e14b12005-01-08 22:48:57 +0000660 SDOperand Callee;
661 if (!RenameFn)
662 Callee = getValue(I.getOperand(0));
663 else
664 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +0000665 std::vector<std::pair<SDOperand, const Type*> > Args;
666
667 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
668 Value *Arg = I.getOperand(i);
669 SDOperand ArgNode = getValue(Arg);
670 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
671 }
672
Nate Begeman8e21e712005-03-26 01:29:23 +0000673 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
674 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
675
Chris Lattnercf5734d2005-01-08 19:26:18 +0000676 std::pair<SDOperand,SDOperand> Result =
Nate Begeman8e21e712005-03-26 01:29:23 +0000677 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +0000678 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +0000679 setValue(&I, Result.first);
680 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000681}
682
683void SelectionDAGLowering::visitMalloc(MallocInst &I) {
684 SDOperand Src = getValue(I.getOperand(0));
685
686 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +0000687
688 if (IntPtr < Src.getValueType())
689 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
690 else if (IntPtr > Src.getValueType())
691 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +0000692
693 // Scale the source by the type size.
694 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
695 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
696 Src, getIntPtrConstant(ElementSize));
697
698 std::vector<std::pair<SDOperand, const Type*> > Args;
699 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +0000700
701 std::pair<SDOperand,SDOperand> Result =
Nate Begeman8e21e712005-03-26 01:29:23 +0000702 TLI.LowerCallTo(getRoot(), I.getType(), false,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000703 DAG.getExternalSymbol("malloc", IntPtr),
704 Args, DAG);
705 setValue(&I, Result.first); // Pointers always fit in registers
706 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707}
708
709void SelectionDAGLowering::visitFree(FreeInst &I) {
710 std::vector<std::pair<SDOperand, const Type*> > Args;
711 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
712 TLI.getTargetData().getIntPtrType()));
713 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +0000714 std::pair<SDOperand,SDOperand> Result =
Nate Begeman8e21e712005-03-26 01:29:23 +0000715 TLI.LowerCallTo(getRoot(), Type::VoidTy, false,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000716 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
717 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000718}
719
Chris Lattner39ae3622005-01-09 00:00:49 +0000720std::pair<SDOperand, SDOperand>
721TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000722 // We have no sane default behavior, just emit a useful error message and bail
723 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +0000724 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000725 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000726 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner1c08c712005-01-07 07:47:53 +0000727}
728
Chris Lattner39ae3622005-01-09 00:00:49 +0000729SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
730 SelectionDAG &DAG) {
731 // Default to a noop.
732 return Chain;
733}
734
735std::pair<SDOperand,SDOperand>
736TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
737 // Default to returning the input list.
738 return std::make_pair(L, Chain);
739}
740
741std::pair<SDOperand,SDOperand>
742TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
743 const Type *ArgTy, SelectionDAG &DAG) {
744 // We have no sane default behavior, just emit a useful error message and bail
745 // out.
746 std::cerr << "Variable arguments handling not implemented on this target!\n";
747 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000748 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +0000749}
750
751
752void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000753 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000754 setValue(&I, Result.first);
755 DAG.setRoot(Result.second);
756}
757
758void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
759 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000760 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000761 I.getType(), DAG);
762 setValue(&I, Result.first);
763 DAG.setRoot(Result.second);
764}
765
Chris Lattner1c08c712005-01-07 07:47:53 +0000766void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000767 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000768 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000769 I.getArgType(), DAG);
770 setValue(&I, Result.first);
771 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000772}
773
774void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000775 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000776}
777
778void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000779 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000780 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000781 setValue(&I, Result.first);
782 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000783}
784
Chris Lattner39ae3622005-01-09 00:00:49 +0000785
786// It is always conservatively correct for llvm.returnaddress and
787// llvm.frameaddress to return 0.
788std::pair<SDOperand, SDOperand>
789TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
790 unsigned Depth, SelectionDAG &DAG) {
791 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +0000792}
793
Chris Lattner171453a2005-01-16 07:28:41 +0000794SDOperand TargetLowering::LowerOperation(SDOperand Op) {
795 assert(0 && "LowerOperation not implemented for this target!");
796 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000797 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +0000798}
799
Chris Lattner39ae3622005-01-09 00:00:49 +0000800void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
801 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
802 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000803 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000804 setValue(&I, Result.first);
805 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000806}
807
Chris Lattner7041ee32005-01-11 05:56:49 +0000808void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
809 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +0000810 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +0000811 Ops.push_back(getValue(I.getOperand(1)));
812 Ops.push_back(getValue(I.getOperand(2)));
813 Ops.push_back(getValue(I.getOperand(3)));
814 Ops.push_back(getValue(I.getOperand(4)));
815 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000816}
817
Chris Lattner7041ee32005-01-11 05:56:49 +0000818//===----------------------------------------------------------------------===//
819// SelectionDAGISel code
820//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000821
822unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
823 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
824}
825
826
827
828bool SelectionDAGISel::runOnFunction(Function &Fn) {
829 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
830 RegMap = MF.getSSARegMap();
831 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
832
833 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
834
835 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
836 SelectBasicBlock(I, MF, FuncInfo);
837
838 return true;
839}
840
841
Chris Lattnerddb870b2005-01-13 17:59:43 +0000842SDOperand SelectionDAGISel::
843CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000844 SelectionDAG &DAG = SDL.DAG;
Chris Lattnerf1fdaca2005-01-11 22:03:46 +0000845 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +0000846 assert((Op.getOpcode() != ISD::CopyFromReg ||
847 cast<RegSDNode>(Op)->getReg() != Reg) &&
848 "Copy from a reg to the same reg!");
Chris Lattnera651cf62005-01-17 19:43:36 +0000849 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner1c08c712005-01-07 07:47:53 +0000850}
851
Chris Lattner0afa8e32005-01-17 17:55:19 +0000852/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
853/// single basic block, return that block. Otherwise, return a null pointer.
854static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
855 if (A->use_empty()) return 0;
856 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
857 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
858 ++UI)
859 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
860 return 0; // Disagreement among the users?
Chris Lattneraa781b32005-02-17 19:40:32 +0000861
862 // Okay, there is a single BB user. Only permit this optimization if this is
863 // the entry block, otherwise, we might sink argument loads into loops and
864 // stuff. Later, when we have global instruction selection, this won't be an
865 // issue clearly.
866 if (BB == BB->getParent()->begin())
867 return BB;
868 return 0;
Chris Lattner0afa8e32005-01-17 17:55:19 +0000869}
870
Chris Lattner068a81e2005-01-17 17:15:02 +0000871void SelectionDAGISel::
872LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
873 std::vector<SDOperand> &UnorderedChains) {
874 // If this is the entry block, emit arguments.
875 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +0000876 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner068a81e2005-01-17 17:15:02 +0000877
878 if (BB == &F.front()) {
Chris Lattner0afa8e32005-01-17 17:55:19 +0000879 SDOperand OldRoot = SDL.DAG.getRoot();
880
Chris Lattner068a81e2005-01-17 17:15:02 +0000881 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
882
Chris Lattner0afa8e32005-01-17 17:55:19 +0000883 // If there were side effects accessing the argument list, do not do
884 // anything special.
885 if (OldRoot != SDL.DAG.getRoot()) {
886 unsigned a = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000887 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +0000888 if (!AI->use_empty()) {
889 SDL.setValue(AI, Args[a]);
890 SDOperand Copy =
891 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
892 UnorderedChains.push_back(Copy);
893 }
894 } else {
895 // Otherwise, if any argument is only accessed in a single basic block,
896 // emit that argument only to that basic block.
897 unsigned a = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000898 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +0000899 if (!AI->use_empty()) {
900 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
901 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
902 std::make_pair(AI, a)));
903 } else {
904 SDL.setValue(AI, Args[a]);
905 SDOperand Copy =
906 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
907 UnorderedChains.push_back(Copy);
908 }
909 }
910 }
911 }
Chris Lattner068a81e2005-01-17 17:15:02 +0000912
Chris Lattner0afa8e32005-01-17 17:55:19 +0000913 // See if there are any block-local arguments that need to be emitted in this
914 // block.
915
916 if (!FuncInfo.BlockLocalArguments.empty()) {
917 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
918 FuncInfo.BlockLocalArguments.lower_bound(BB);
919 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
920 // Lower the arguments into this block.
921 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
922
923 // Set up the value mapping for the local arguments.
924 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
925 ++BLAI)
926 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
927
928 // Any dead arguments will just be ignored here.
929 }
Chris Lattner068a81e2005-01-17 17:15:02 +0000930 }
931}
932
933
Chris Lattner1c08c712005-01-07 07:47:53 +0000934void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
935 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
936 FunctionLoweringInfo &FuncInfo) {
937 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +0000938
939 std::vector<SDOperand> UnorderedChains;
Chris Lattner1c08c712005-01-07 07:47:53 +0000940
Chris Lattner068a81e2005-01-17 17:15:02 +0000941 // Lower any arguments needed in this block.
942 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +0000943
944 BB = FuncInfo.MBBMap[LLVMBB];
945 SDL.setCurrentBasicBlock(BB);
946
947 // Lower all of the non-terminator instructions.
948 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
949 I != E; ++I)
950 SDL.visit(*I);
951
952 // Ensure that all instructions which are used outside of their defining
953 // blocks are available as virtual registers.
954 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +0000955 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +0000956 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000957 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +0000958 UnorderedChains.push_back(
959 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +0000960 }
961
962 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
963 // ensure constants are generated when needed. Remember the virtual registers
964 // that need to be added to the Machine PHI nodes as input. We cannot just
965 // directly add them, because expansion might result in multiple MBB's for one
966 // BB. As such, the start of the BB might correspond to a different MBB than
967 // the end.
968 //
969
970 // Emit constants only once even if used by multiple PHI nodes.
971 std::map<Constant*, unsigned> ConstantsOut;
972
973 // Check successor nodes PHI nodes that expect a constant to be available from
974 // this block.
975 TerminatorInst *TI = LLVMBB->getTerminator();
976 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
977 BasicBlock *SuccBB = TI->getSuccessor(succ);
978 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
979 PHINode *PN;
980
981 // At this point we know that there is a 1-1 correspondence between LLVM PHI
982 // nodes and Machine PHI nodes, but the incoming operands have not been
983 // emitted yet.
984 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000985 (PN = dyn_cast<PHINode>(I)); ++I)
986 if (!PN->use_empty()) {
987 unsigned Reg;
988 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
989 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
990 unsigned &RegOut = ConstantsOut[C];
991 if (RegOut == 0) {
992 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +0000993 UnorderedChains.push_back(
994 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +0000995 }
996 Reg = RegOut;
997 } else {
998 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +0000999 if (Reg == 0) {
1000 assert(isa<AllocaInst>(PHIOp) &&
1001 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1002 "Didn't codegen value into a register!??");
1003 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001004 UnorderedChains.push_back(
1005 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001006 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001007 }
Chris Lattnerf44fd882005-01-07 21:34:19 +00001008
1009 // Remember that this register needs to added to the machine PHI node as
1010 // the input for this MBB.
1011 unsigned NumElements =
1012 TLI.getNumElements(TLI.getValueType(PN->getType()));
1013 for (unsigned i = 0, e = NumElements; i != e; ++i)
1014 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001015 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001016 }
1017 ConstantsOut.clear();
1018
Chris Lattnerddb870b2005-01-13 17:59:43 +00001019 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001020 if (!UnorderedChains.empty()) {
Chris Lattnerd3948112005-01-17 22:19:26 +00001021 UnorderedChains.push_back(SDL.getRoot());
Chris Lattnerddb870b2005-01-13 17:59:43 +00001022 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1023 }
1024
Chris Lattner1c08c712005-01-07 07:47:53 +00001025 // Lower the terminator after the copies are emitted.
1026 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001027
1028 // Make sure the root of the DAG is up-to-date.
1029 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001030}
1031
1032void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1033 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001034 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001035 CurDAG = &DAG;
1036 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1037
1038 // First step, lower LLVM code to some DAG. This DAG may use operations and
1039 // types that are not supported by the target.
1040 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1041
1042 DEBUG(std::cerr << "Lowered selection DAG:\n");
1043 DEBUG(DAG.dump());
1044
1045 // Second step, hack on the DAG until it only uses operations and types that
1046 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001047 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001048
1049 DEBUG(std::cerr << "Legalized selection DAG:\n");
1050 DEBUG(DAG.dump());
1051
1052 // Finally, instruction select all of the operations to machine code, adding
1053 // the code to the MachineBasicBlock.
1054 InstructionSelectBasicBlock(DAG);
1055
Chris Lattner7944d9d2005-01-12 03:41:21 +00001056 if (ViewDAGs) DAG.viewGraph();
1057
Chris Lattner1c08c712005-01-07 07:47:53 +00001058 DEBUG(std::cerr << "Selected machine code:\n");
1059 DEBUG(BB->dump());
1060
1061 // Finally, now that we know what the last MBB the LLVM BB expanded is, update
1062 // PHI nodes in successors.
1063 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1064 MachineInstr *PHI = PHINodesToUpdate[i].first;
1065 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1066 "This is not a machine PHI node that we are updating!");
1067 PHI->addRegOperand(PHINodesToUpdate[i].second);
1068 PHI->addMachineBasicBlockOperand(BB);
1069 }
1070}