blob: 87997ce7b52171bebe5a14734b79e0702bfb6fc3 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/SelectionDAG.h"
25#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetFrameInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetMachine.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/Support/Debug.h"
33#include <map>
34#include <iostream>
35using namespace llvm;
36
Chris Lattnere05a4612005-01-12 03:41:21 +000037#ifndef _NDEBUG
38static cl::opt<bool>
39ViewDAGs("view-isel-dags", cl::Hidden,
40 cl::desc("Pop up a window to show isel dags as they are selected"));
41#else
42static const bool ViewDAGS = 0;
43#endif
44
Chris Lattner7a60d912005-01-07 07:47:53 +000045namespace llvm {
46 //===--------------------------------------------------------------------===//
47 /// FunctionLoweringInfo - This contains information that is global to a
48 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000049 class FunctionLoweringInfo {
50 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000051 TargetLowering &TLI;
52 Function &Fn;
53 MachineFunction &MF;
54 SSARegMap *RegMap;
55
56 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
57
58 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
59 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
60
61 /// ValueMap - Since we emit code for the function a basic block at a time,
62 /// we must remember which virtual registers hold the values for
63 /// cross-basic-block values.
64 std::map<const Value*, unsigned> ValueMap;
65
66 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
67 /// the entry block. This allows the allocas to be efficiently referenced
68 /// anywhere in the function.
69 std::map<const AllocaInst*, int> StaticAllocaMap;
70
Chris Lattnere3c2cf42005-01-17 17:55:19 +000071 /// BlockLocalArguments - If any arguments are only used in a single basic
72 /// block, and if the target can access the arguments without side-effects,
73 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
74 /// track of which arguments are local to each BB.
75 std::multimap<BasicBlock*, std::pair<Argument*,
76 unsigned> > BlockLocalArguments;
77
78
Chris Lattner7a60d912005-01-07 07:47:53 +000079 unsigned MakeReg(MVT::ValueType VT) {
80 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
81 }
82
83 unsigned CreateRegForValue(const Value *V) {
84 MVT::ValueType VT = TLI.getValueType(V->getType());
85 // The common case is that we will only create one register for this
86 // value. If we have that case, create and return the virtual register.
87 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000088 if (NV == 1) {
89 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000090 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000091 }
Chris Lattner7a60d912005-01-07 07:47:53 +000092
93 // If this value is represented with multiple target registers, make sure
94 // to create enough consequtive registers of the right (smaller) type.
95 unsigned NT = VT-1; // Find the type to use.
96 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
97 --NT;
98
99 unsigned R = MakeReg((MVT::ValueType)NT);
100 for (unsigned i = 1; i != NV; ++i)
101 MakeReg((MVT::ValueType)NT);
102 return R;
103 }
104
105 unsigned InitializeRegForValue(const Value *V) {
106 unsigned &R = ValueMap[V];
107 assert(R == 0 && "Already initialized this value register!");
108 return R = CreateRegForValue(V);
109 }
110 };
111}
112
113/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
114/// PHI nodes or outside of the basic block that defines it.
115static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
116 if (isa<PHINode>(I)) return true;
117 BasicBlock *BB = I->getParent();
118 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
119 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
120 return true;
121 return false;
122}
123
124FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
125 Function &fn, MachineFunction &mf)
126 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
127
128 // Initialize the mapping of values to registers. This is only set up for
129 // instruction values that are used outside of the block that defines
130 // them.
131 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
132 InitializeRegForValue(AI);
133
134 Function::iterator BB = Fn.begin(), E = Fn.end();
135 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
136 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
137 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
138 const Type *Ty = AI->getAllocatedType();
139 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
140 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
141 TySize *= CUI->getValue(); // Get total allocated size.
142 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000143 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000144 }
145
146 for (; BB != E; ++BB)
Chris Lattnerd0061952005-01-08 19:52:31 +0000147 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000148 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
149 if (!isa<AllocaInst>(I) ||
150 !StaticAllocaMap.count(cast<AllocaInst>(I)))
151 InitializeRegForValue(I);
152
153 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
154 // also creates the initial PHI MachineInstrs, though none of the input
155 // operands are populated.
156 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
157 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
158 MBBMap[BB] = MBB;
159 MF.getBasicBlockList().push_back(MBB);
160
161 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
162 // appropriate.
163 PHINode *PN;
164 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000165 (PN = dyn_cast<PHINode>(I)); ++I)
166 if (!PN->use_empty()) {
167 unsigned NumElements =
168 TLI.getNumElements(TLI.getValueType(PN->getType()));
169 unsigned PHIReg = ValueMap[PN];
170 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
171 for (unsigned i = 0; i != NumElements; ++i)
172 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
173 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 }
175}
176
177
178
179//===----------------------------------------------------------------------===//
180/// SelectionDAGLowering - This is the common target-independent lowering
181/// implementation that is parameterized by a TargetLowering object.
182/// Also, targets can overload any lowering method.
183///
184namespace llvm {
185class SelectionDAGLowering {
186 MachineBasicBlock *CurMBB;
187
188 std::map<const Value*, SDOperand> NodeMap;
189
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
295 MVT::ValueType RegVT = VT;
296 if (TLI.getTypeAction(VT) == 1) // Must promote this value?
297 RegVT = TLI.getTypeToTransformTo(VT);
298
299 N = DAG.getCopyFromReg(VMI->second, RegVT, DAG.getEntryNode());
300
301 if (RegVT != VT)
302 if (MVT::isFloatingPoint(VT))
303 N = DAG.getNode(ISD::FP_ROUND, VT, N);
304 else
305 N = DAG.getNode(ISD::TRUNCATE, VT, N);
306
307 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000308 }
309
310 const SDOperand &setValue(const Value *V, SDOperand NewN) {
311 SDOperand &N = NodeMap[V];
312 assert(N.Val == 0 && "Already set a value for this node!");
313 return N = NewN;
314 }
315
316 // Terminator instructions.
317 void visitRet(ReturnInst &I);
318 void visitBr(BranchInst &I);
319 void visitUnreachable(UnreachableInst &I) { /* noop */ }
320
321 // These all get lowered before this pass.
322 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
323 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
324 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
325
326 //
327 void visitBinary(User &I, unsigned Opcode);
328 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
329 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
330 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
331 void visitDiv(User &I) {
332 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
333 }
334 void visitRem(User &I) {
335 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
336 }
337 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
338 void visitOr (User &I) { visitBinary(I, ISD::OR); }
339 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
340 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
341 void visitShr(User &I) {
342 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
343 }
344
345 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
346 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
347 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
348 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
349 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
350 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
351 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
352
353 void visitGetElementPtr(User &I);
354 void visitCast(User &I);
355 void visitSelect(User &I);
356 //
357
358 void visitMalloc(MallocInst &I);
359 void visitFree(FreeInst &I);
360 void visitAlloca(AllocaInst &I);
361 void visitLoad(LoadInst &I);
362 void visitStore(StoreInst &I);
363 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
364 void visitCall(CallInst &I);
365
Chris Lattner7a60d912005-01-07 07:47:53 +0000366 void visitVAStart(CallInst &I);
367 void visitVANext(VANextInst &I);
368 void visitVAArg(VAArgInst &I);
369 void visitVAEnd(CallInst &I);
370 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000371 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000372
Chris Lattner875def92005-01-11 05:56:49 +0000373 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000374
375 void visitUserOp1(Instruction &I) {
376 assert(0 && "UserOp1 should not exist at instruction selection time!");
377 abort();
378 }
379 void visitUserOp2(Instruction &I) {
380 assert(0 && "UserOp2 should not exist at instruction selection time!");
381 abort();
382 }
383};
384} // end namespace llvm
385
386void SelectionDAGLowering::visitRet(ReturnInst &I) {
387 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000388 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000389 return;
390 }
391
392 SDOperand Op1 = getValue(I.getOperand(0));
393 switch (Op1.getValueType()) {
394 default: assert(0 && "Unknown value type!");
395 case MVT::i1:
396 case MVT::i8:
397 case MVT::i16:
398 // Extend integer types to 32-bits.
399 if (I.getOperand(0)->getType()->isSigned())
400 Op1 = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Op1);
401 else
402 Op1 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op1);
403 break;
404 case MVT::f32:
405 // Extend float to double.
406 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
407 break;
408 case MVT::i32:
409 case MVT::i64:
410 case MVT::f64:
411 break; // No extension needed!
412 }
413
Chris Lattner4108bb02005-01-17 19:43:36 +0000414 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000415}
416
417void SelectionDAGLowering::visitBr(BranchInst &I) {
418 // Update machine-CFG edges.
419 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
420 CurMBB->addSuccessor(Succ0MBB);
421
422 // Figure out which block is immediately after the current one.
423 MachineBasicBlock *NextBlock = 0;
424 MachineFunction::iterator BBI = CurMBB;
425 if (++BBI != CurMBB->getParent()->end())
426 NextBlock = BBI;
427
428 if (I.isUnconditional()) {
429 // If this is not a fall-through branch, emit the branch.
430 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000431 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000432 DAG.getBasicBlock(Succ0MBB)));
433 } else {
434 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
435 CurMBB->addSuccessor(Succ1MBB);
436
437 SDOperand Cond = getValue(I.getCondition());
438
439 if (Succ1MBB == NextBlock) {
440 // If the condition is false, fall through. This means we should branch
441 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000442 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 Cond, DAG.getBasicBlock(Succ0MBB)));
444 } else if (Succ0MBB == NextBlock) {
445 // If the condition is true, fall through. This means we should branch if
446 // the condition is false to Succ #1. Invert the condition first.
447 SDOperand True = DAG.getConstant(1, Cond.getValueType());
448 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000449 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 Cond, DAG.getBasicBlock(Succ1MBB)));
451 } else {
452 // Neither edge is a fall through. If the comparison is true, jump to
453 // Succ#0, otherwise branch unconditionally to succ #1.
Chris Lattner4108bb02005-01-17 19:43:36 +0000454 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner4108bb02005-01-17 19:43:36 +0000456 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner7a60d912005-01-07 07:47:53 +0000457 DAG.getBasicBlock(Succ1MBB)));
458 }
459 }
460}
461
462void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
463 SDOperand Op1 = getValue(I.getOperand(0));
464 SDOperand Op2 = getValue(I.getOperand(1));
465 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
466}
467
468void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
469 ISD::CondCode UnsignedOpcode) {
470 SDOperand Op1 = getValue(I.getOperand(0));
471 SDOperand Op2 = getValue(I.getOperand(1));
472 ISD::CondCode Opcode = SignedOpcode;
473 if (I.getOperand(0)->getType()->isUnsigned())
474 Opcode = UnsignedOpcode;
475 setValue(&I, DAG.getSetCC(Opcode, Op1, Op2));
476}
477
478void SelectionDAGLowering::visitSelect(User &I) {
479 SDOperand Cond = getValue(I.getOperand(0));
480 SDOperand TrueVal = getValue(I.getOperand(1));
481 SDOperand FalseVal = getValue(I.getOperand(2));
482 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
483 TrueVal, FalseVal));
484}
485
486void SelectionDAGLowering::visitCast(User &I) {
487 SDOperand N = getValue(I.getOperand(0));
488 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
489 MVT::ValueType DestTy = TLI.getValueType(I.getType());
490
491 if (N.getValueType() == DestTy) {
492 setValue(&I, N); // noop cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000493 } else if (isInteger(SrcTy)) {
494 if (isInteger(DestTy)) { // Int -> Int cast
495 if (DestTy < SrcTy) // Truncating cast?
496 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
497 else if (I.getOperand(0)->getType()->isSigned())
498 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
499 else
500 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
501 } else { // Int -> FP cast
502 if (I.getOperand(0)->getType()->isSigned())
503 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
504 else
505 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
506 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000508 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
509 if (isFloatingPoint(DestTy)) { // FP -> FP cast
510 if (DestTy < SrcTy) // Rounding cast?
511 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
512 else
513 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
514 } else { // FP -> Int cast.
515 if (I.getType()->isSigned())
516 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
517 else
518 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
519 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 }
521}
522
523void SelectionDAGLowering::visitGetElementPtr(User &I) {
524 SDOperand N = getValue(I.getOperand(0));
525 const Type *Ty = I.getOperand(0)->getType();
526 const Type *UIntPtrTy = TD.getIntPtrType();
527
528 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
529 OI != E; ++OI) {
530 Value *Idx = *OI;
531 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
532 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
533 if (Field) {
534 // N = N + Offset
535 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
536 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
537 getIntPtrConstant(Offset));
538 }
539 Ty = StTy->getElementType(Field);
540 } else {
541 Ty = cast<SequentialType>(Ty)->getElementType();
542 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
543 // N = N + Idx * ElementSize;
544 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000545 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
546
547 // If the index is smaller or larger than intptr_t, truncate or extend
548 // it.
549 if (IdxN.getValueType() < Scale.getValueType()) {
550 if (Idx->getType()->isSigned())
551 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
552 else
553 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
554 } else if (IdxN.getValueType() > Scale.getValueType())
555 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
556
557 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
558
Chris Lattner7a60d912005-01-07 07:47:53 +0000559 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
560 }
561 }
562 }
563 setValue(&I, N);
564}
565
566void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
567 // If this is a fixed sized alloca in the entry block of the function,
568 // allocate it statically on the stack.
569 if (FuncInfo.StaticAllocaMap.count(&I))
570 return; // getValue will auto-populate this.
571
572 const Type *Ty = I.getAllocatedType();
573 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
574 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
575
576 SDOperand AllocSize = getValue(I.getArraySize());
577
578 assert(AllocSize.getValueType() == TLI.getPointerTy() &&
579 "FIXME: should extend or truncate to pointer size!");
580
581 AllocSize = DAG.getNode(ISD::MUL, TLI.getPointerTy(), AllocSize,
582 getIntPtrConstant(TySize));
583
584 // Handle alignment. If the requested alignment is less than or equal to the
585 // stack alignment, ignore it and round the size of the allocation up to the
586 // stack alignment size. If the size is greater than the stack alignment, we
587 // note this in the DYNAMIC_STACKALLOC node.
588 unsigned StackAlign =
589 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
590 if (Align <= StackAlign) {
591 Align = 0;
592 // Add SA-1 to the size.
593 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
594 getIntPtrConstant(StackAlign-1));
595 // Mask out the low bits for alignment purposes.
596 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
597 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
598 }
599
600 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattner4108bb02005-01-17 19:43:36 +0000601 getRoot(), AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000602 getIntPtrConstant(Align));
603 DAG.setRoot(setValue(&I, DSA).getValue(1));
604
605 // Inform the Frame Information that we have just allocated a variable-sized
606 // object.
607 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
608}
609
610
611void SelectionDAGLowering::visitLoad(LoadInst &I) {
612 SDOperand Ptr = getValue(I.getOperand(0));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000613
614 SDOperand Root;
615 if (I.isVolatile())
616 Root = getRoot();
617 else {
618 // Do not serialize non-volatile loads against each other.
619 Root = DAG.getRoot();
620 }
621
622 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr);
623 setValue(&I, L);
624
625 if (I.isVolatile())
626 DAG.setRoot(L.getValue(1));
627 else
628 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000629}
630
631
632void SelectionDAGLowering::visitStore(StoreInst &I) {
633 Value *SrcV = I.getOperand(0);
634 SDOperand Src = getValue(SrcV);
635 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner4108bb02005-01-17 19:43:36 +0000636 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr));
Chris Lattner7a60d912005-01-07 07:47:53 +0000637}
638
639void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000640 const char *RenameFn = 0;
Chris Lattner7a60d912005-01-07 07:47:53 +0000641 if (Function *F = I.getCalledFunction())
642 switch (F->getIntrinsicID()) {
643 case 0: break; // Not an intrinsic.
644 case Intrinsic::vastart: visitVAStart(I); return;
645 case Intrinsic::vaend: visitVAEnd(I); return;
646 case Intrinsic::vacopy: visitVACopy(I); return;
Chris Lattner58cfd792005-01-09 00:00:49 +0000647 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
648 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000649 default:
650 // FIXME: IMPLEMENT THESE.
651 // readport, writeport, readio, writeio
652 assert(0 && "This intrinsic is not implemented yet!");
653 return;
Chris Lattner18d2b342005-01-08 22:48:57 +0000654 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
655 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
Chris Lattner875def92005-01-11 05:56:49 +0000656 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
657 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
658 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Chris Lattner7a60d912005-01-07 07:47:53 +0000659
660 case Intrinsic::isunordered:
661 setValue(&I, DAG.getSetCC(ISD::SETUO, getValue(I.getOperand(1)),
662 getValue(I.getOperand(2))));
663 return;
664 }
665
Chris Lattner18d2b342005-01-08 22:48:57 +0000666 SDOperand Callee;
667 if (!RenameFn)
668 Callee = getValue(I.getOperand(0));
669 else
670 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000671 std::vector<std::pair<SDOperand, const Type*> > Args;
672
673 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
674 Value *Arg = I.getOperand(i);
675 SDOperand ArgNode = getValue(Arg);
676 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
677 }
678
Chris Lattner1f45cd72005-01-08 19:26:18 +0000679 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000680 TLI.LowerCallTo(getRoot(), I.getType(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000681 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000682 setValue(&I, Result.first);
683 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000684}
685
686void SelectionDAGLowering::visitMalloc(MallocInst &I) {
687 SDOperand Src = getValue(I.getOperand(0));
688
689 MVT::ValueType IntPtr = TLI.getPointerTy();
690 // FIXME: Extend or truncate to the intptr size.
691 assert(Src.getValueType() == IntPtr && "Need to adjust the amount!");
692
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 Lattner1f45cd72005-01-08 19:26:18 +0000700
701 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000702 TLI.LowerCallTo(getRoot(), I.getType(),
Chris Lattner1f45cd72005-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 Lattner7a60d912005-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 Lattner1f45cd72005-01-08 19:26:18 +0000714 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000715 TLI.LowerCallTo(getRoot(), Type::VoidTy,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000716 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
717 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000718}
719
Chris Lattner58cfd792005-01-09 00:00:49 +0000720std::pair<SDOperand, SDOperand>
721TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000722 // We have no sane default behavior, just emit a useful error message and bail
723 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000724 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000725 abort();
726}
727
Chris Lattner58cfd792005-01-09 00:00:49 +0000728SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
729 SelectionDAG &DAG) {
730 // Default to a noop.
731 return Chain;
732}
733
734std::pair<SDOperand,SDOperand>
735TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
736 // Default to returning the input list.
737 return std::make_pair(L, Chain);
738}
739
740std::pair<SDOperand,SDOperand>
741TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
742 const Type *ArgTy, SelectionDAG &DAG) {
743 // We have no sane default behavior, just emit a useful error message and bail
744 // out.
745 std::cerr << "Variable arguments handling not implemented on this target!\n";
746 abort();
747}
748
749
750void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000751 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000752 setValue(&I, Result.first);
753 DAG.setRoot(Result.second);
754}
755
756void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
757 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000758 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000759 I.getType(), DAG);
760 setValue(&I, Result.first);
761 DAG.setRoot(Result.second);
762}
763
Chris Lattner7a60d912005-01-07 07:47:53 +0000764void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000765 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000766 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000767 I.getArgType(), DAG);
768 setValue(&I, Result.first);
769 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000770}
771
772void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000773 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000774}
775
776void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000777 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000778 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000779 setValue(&I, Result.first);
780 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000781}
782
Chris Lattner58cfd792005-01-09 00:00:49 +0000783
784// It is always conservatively correct for llvm.returnaddress and
785// llvm.frameaddress to return 0.
786std::pair<SDOperand, SDOperand>
787TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
788 unsigned Depth, SelectionDAG &DAG) {
789 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000790}
791
Chris Lattner897cd7d2005-01-16 07:28:41 +0000792SDOperand TargetLowering::LowerOperation(SDOperand Op) {
793 assert(0 && "LowerOperation not implemented for this target!");
794 abort();
795}
796
Chris Lattner58cfd792005-01-09 00:00:49 +0000797void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
798 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
799 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000800 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000801 setValue(&I, Result.first);
802 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000803}
804
Chris Lattner875def92005-01-11 05:56:49 +0000805void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
806 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000807 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000808 Ops.push_back(getValue(I.getOperand(1)));
809 Ops.push_back(getValue(I.getOperand(2)));
810 Ops.push_back(getValue(I.getOperand(3)));
811 Ops.push_back(getValue(I.getOperand(4)));
812 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000813}
814
Chris Lattner875def92005-01-11 05:56:49 +0000815//===----------------------------------------------------------------------===//
816// SelectionDAGISel code
817//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000818
819unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
820 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
821}
822
823
824
825bool SelectionDAGISel::runOnFunction(Function &Fn) {
826 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
827 RegMap = MF.getSSARegMap();
828 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
829
830 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
831
832 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
833 SelectBasicBlock(I, MF, FuncInfo);
834
835 return true;
836}
837
838
Chris Lattner718b5c22005-01-13 17:59:43 +0000839SDOperand SelectionDAGISel::
840CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000841 SelectionDAG &DAG = SDL.DAG;
Chris Lattner613f79f2005-01-11 22:03:46 +0000842 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +0000843 assert((Op.getOpcode() != ISD::CopyFromReg ||
844 cast<RegSDNode>(Op)->getReg() != Reg) &&
845 "Copy from a reg to the same reg!");
Chris Lattner209f5852005-01-16 02:23:07 +0000846 MVT::ValueType VT = Op.getValueType();
847 if (TLI.getTypeAction(VT) == 1) { // Must promote this value?
848 if (MVT::isFloatingPoint(VT))
849 Op = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(VT), Op);
850 else
851 Op = DAG.getNode(ISD::ZERO_EXTEND, TLI.getTypeToTransformTo(VT), Op);
852 }
853
Chris Lattner4108bb02005-01-17 19:43:36 +0000854 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner7a60d912005-01-07 07:47:53 +0000855}
856
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000857/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
858/// single basic block, return that block. Otherwise, return a null pointer.
859static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
860 if (A->use_empty()) return 0;
861 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
862 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
863 ++UI)
864 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
865 return 0; // Disagreement among the users?
866 return BB;
867}
868
Chris Lattner16f64df2005-01-17 17:15:02 +0000869void SelectionDAGISel::
870LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
871 std::vector<SDOperand> &UnorderedChains) {
872 // If this is the entry block, emit arguments.
873 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000874 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +0000875
876 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000877 SDOperand OldRoot = SDL.DAG.getRoot();
878
Chris Lattner16f64df2005-01-17 17:15:02 +0000879 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
880
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000881 // If there were side effects accessing the argument list, do not do
882 // anything special.
883 if (OldRoot != SDL.DAG.getRoot()) {
884 unsigned a = 0;
885 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI,++a)
886 if (!AI->use_empty()) {
887 SDL.setValue(AI, Args[a]);
888 SDOperand Copy =
889 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
890 UnorderedChains.push_back(Copy);
891 }
892 } else {
893 // Otherwise, if any argument is only accessed in a single basic block,
894 // emit that argument only to that basic block.
895 unsigned a = 0;
896 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI,++a)
897 if (!AI->use_empty()) {
898 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
899 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
900 std::make_pair(AI, a)));
901 } else {
902 SDL.setValue(AI, Args[a]);
903 SDOperand Copy =
904 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
905 UnorderedChains.push_back(Copy);
906 }
907 }
908 }
909 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000910
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000911 // See if there are any block-local arguments that need to be emitted in this
912 // block.
913
914 if (!FuncInfo.BlockLocalArguments.empty()) {
915 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
916 FuncInfo.BlockLocalArguments.lower_bound(BB);
917 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
918 // Lower the arguments into this block.
919 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
920
921 // Set up the value mapping for the local arguments.
922 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
923 ++BLAI)
924 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
925
926 // Any dead arguments will just be ignored here.
927 }
Chris Lattner16f64df2005-01-17 17:15:02 +0000928 }
929}
930
931
Chris Lattner7a60d912005-01-07 07:47:53 +0000932void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
933 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
934 FunctionLoweringInfo &FuncInfo) {
935 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +0000936
937 std::vector<SDOperand> UnorderedChains;
Chris Lattner7a60d912005-01-07 07:47:53 +0000938
Chris Lattner16f64df2005-01-17 17:15:02 +0000939 // Lower any arguments needed in this block.
940 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +0000941
942 BB = FuncInfo.MBBMap[LLVMBB];
943 SDL.setCurrentBasicBlock(BB);
944
945 // Lower all of the non-terminator instructions.
946 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
947 I != E; ++I)
948 SDL.visit(*I);
949
950 // Ensure that all instructions which are used outside of their defining
951 // blocks are available as virtual registers.
952 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +0000953 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +0000954 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000955 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +0000956 UnorderedChains.push_back(
957 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +0000958 }
959
960 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
961 // ensure constants are generated when needed. Remember the virtual registers
962 // that need to be added to the Machine PHI nodes as input. We cannot just
963 // directly add them, because expansion might result in multiple MBB's for one
964 // BB. As such, the start of the BB might correspond to a different MBB than
965 // the end.
966 //
967
968 // Emit constants only once even if used by multiple PHI nodes.
969 std::map<Constant*, unsigned> ConstantsOut;
970
971 // Check successor nodes PHI nodes that expect a constant to be available from
972 // this block.
973 TerminatorInst *TI = LLVMBB->getTerminator();
974 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
975 BasicBlock *SuccBB = TI->getSuccessor(succ);
976 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
977 PHINode *PN;
978
979 // At this point we know that there is a 1-1 correspondence between LLVM PHI
980 // nodes and Machine PHI nodes, but the incoming operands have not been
981 // emitted yet.
982 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000983 (PN = dyn_cast<PHINode>(I)); ++I)
984 if (!PN->use_empty()) {
985 unsigned Reg;
986 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
987 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
988 unsigned &RegOut = ConstantsOut[C];
989 if (RegOut == 0) {
990 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +0000991 UnorderedChains.push_back(
992 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +0000993 }
994 Reg = RegOut;
995 } else {
996 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +0000997 if (Reg == 0) {
998 assert(isa<AllocaInst>(PHIOp) &&
999 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1000 "Didn't codegen value into a register!??");
1001 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001002 UnorderedChains.push_back(
1003 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001004 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001005 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00001006
1007 // Remember that this register needs to added to the machine PHI node as
1008 // the input for this MBB.
1009 unsigned NumElements =
1010 TLI.getNumElements(TLI.getValueType(PN->getType()));
1011 for (unsigned i = 0, e = NumElements; i != e; ++i)
1012 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001013 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001014 }
1015 ConstantsOut.clear();
1016
Chris Lattner718b5c22005-01-13 17:59:43 +00001017 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001018 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001019 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001020 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1021 }
1022
Chris Lattner7a60d912005-01-07 07:47:53 +00001023 // Lower the terminator after the copies are emitted.
1024 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001025
1026 // Make sure the root of the DAG is up-to-date.
1027 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001028}
1029
1030void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1031 FunctionLoweringInfo &FuncInfo) {
1032 SelectionDAG DAG(TLI.getTargetMachine(), MF);
1033 CurDAG = &DAG;
1034 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1035
1036 // First step, lower LLVM code to some DAG. This DAG may use operations and
1037 // types that are not supported by the target.
1038 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1039
1040 DEBUG(std::cerr << "Lowered selection DAG:\n");
1041 DEBUG(DAG.dump());
1042
1043 // Second step, hack on the DAG until it only uses operations and types that
1044 // the target supports.
1045 DAG.Legalize(TLI);
1046
1047 DEBUG(std::cerr << "Legalized selection DAG:\n");
1048 DEBUG(DAG.dump());
1049
1050 // Finally, instruction select all of the operations to machine code, adding
1051 // the code to the MachineBasicBlock.
1052 InstructionSelectBasicBlock(DAG);
1053
Chris Lattnere05a4612005-01-12 03:41:21 +00001054 if (ViewDAGs) DAG.viewGraph();
1055
Chris Lattner7a60d912005-01-07 07:47:53 +00001056 DEBUG(std::cerr << "Selected machine code:\n");
1057 DEBUG(BB->dump());
1058
1059 // Finally, now that we know what the last MBB the LLVM BB expanded is, update
1060 // PHI nodes in successors.
1061 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1062 MachineInstr *PHI = PHINodesToUpdate[i].first;
1063 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1064 "This is not a machine PHI node that we are updating!");
1065 PHI->addRegOperand(PHINodesToUpdate[i].second);
1066 PHI->addMachineBasicBlockOperand(BB);
1067 }
1068}