blob: 743cb24527baca6cb36df9c7355e4c3189a05411 [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"
31#include "llvm/Support/Debug.h"
32#include <map>
33#include <iostream>
34using namespace llvm;
35
36namespace llvm {
37 //===--------------------------------------------------------------------===//
38 /// FunctionLoweringInfo - This contains information that is global to a
39 /// function that is used when lowering a region of the function.
40 struct FunctionLoweringInfo {
41 TargetLowering &TLI;
42 Function &Fn;
43 MachineFunction &MF;
44 SSARegMap *RegMap;
45
46 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
47
48 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
49 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
50
51 /// ValueMap - Since we emit code for the function a basic block at a time,
52 /// we must remember which virtual registers hold the values for
53 /// cross-basic-block values.
54 std::map<const Value*, unsigned> ValueMap;
55
56 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
57 /// the entry block. This allows the allocas to be efficiently referenced
58 /// anywhere in the function.
59 std::map<const AllocaInst*, int> StaticAllocaMap;
60
61 unsigned MakeReg(MVT::ValueType VT) {
62 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
63 }
64
65 unsigned CreateRegForValue(const Value *V) {
66 MVT::ValueType VT = TLI.getValueType(V->getType());
67 // The common case is that we will only create one register for this
68 // value. If we have that case, create and return the virtual register.
69 unsigned NV = TLI.getNumElements(VT);
70 if (NV == 1) return MakeReg(VT);
71
72 // If this value is represented with multiple target registers, make sure
73 // to create enough consequtive registers of the right (smaller) type.
74 unsigned NT = VT-1; // Find the type to use.
75 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
76 --NT;
77
78 unsigned R = MakeReg((MVT::ValueType)NT);
79 for (unsigned i = 1; i != NV; ++i)
80 MakeReg((MVT::ValueType)NT);
81 return R;
82 }
83
84 unsigned InitializeRegForValue(const Value *V) {
85 unsigned &R = ValueMap[V];
86 assert(R == 0 && "Already initialized this value register!");
87 return R = CreateRegForValue(V);
88 }
89 };
90}
91
92/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
93/// PHI nodes or outside of the basic block that defines it.
94static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
95 if (isa<PHINode>(I)) return true;
96 BasicBlock *BB = I->getParent();
97 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
98 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
99 return true;
100 return false;
101}
102
103FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
104 Function &fn, MachineFunction &mf)
105 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
106
107 // Initialize the mapping of values to registers. This is only set up for
108 // instruction values that are used outside of the block that defines
109 // them.
110 for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
111 InitializeRegForValue(AI);
112
113 Function::iterator BB = Fn.begin(), E = Fn.end();
114 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
115 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
116 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
117 const Type *Ty = AI->getAllocatedType();
118 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
119 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
120 TySize *= CUI->getValue(); // Get total allocated size.
121 StaticAllocaMap[AI] =
122 MF.getFrameInfo()->CreateStackObject(TySize, Align);
123 }
124
125 for (; BB != E; ++BB)
126 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
127 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
128 if (!isa<AllocaInst>(I) ||
129 !StaticAllocaMap.count(cast<AllocaInst>(I)))
130 InitializeRegForValue(I);
131
132 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
133 // also creates the initial PHI MachineInstrs, though none of the input
134 // operands are populated.
135 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
136 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
137 MBBMap[BB] = MBB;
138 MF.getBasicBlockList().push_back(MBB);
139
140 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
141 // appropriate.
142 PHINode *PN;
143 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000144 (PN = dyn_cast<PHINode>(I)); ++I)
145 if (!PN->use_empty()) {
146 unsigned NumElements =
147 TLI.getNumElements(TLI.getValueType(PN->getType()));
148 unsigned PHIReg = ValueMap[PN];
149 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
150 for (unsigned i = 0; i != NumElements; ++i)
151 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
152 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000153 }
154}
155
156
157
158//===----------------------------------------------------------------------===//
159/// SelectionDAGLowering - This is the common target-independent lowering
160/// implementation that is parameterized by a TargetLowering object.
161/// Also, targets can overload any lowering method.
162///
163namespace llvm {
164class SelectionDAGLowering {
165 MachineBasicBlock *CurMBB;
166
167 std::map<const Value*, SDOperand> NodeMap;
168
169public:
170 // TLI - This is information that describes the available target features we
171 // need for lowering. This indicates when operations are unavailable,
172 // implemented with a libcall, etc.
173 TargetLowering &TLI;
174 SelectionDAG &DAG;
175 const TargetData &TD;
176
177 /// FuncInfo - Information about the function as a whole.
178 ///
179 FunctionLoweringInfo &FuncInfo;
180
181 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
182 FunctionLoweringInfo &funcinfo)
183 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
184 FuncInfo(funcinfo) {
185 }
186
187 void visit(Instruction &I) { visit(I.getOpcode(), I); }
188
189 void visit(unsigned Opcode, User &I) {
190 switch (Opcode) {
191 default: assert(0 && "Unknown instruction type encountered!");
192 abort();
193 // Build the switch statement using the Instruction.def file.
194#define HANDLE_INST(NUM, OPCODE, CLASS) \
195 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
196#include "llvm/Instruction.def"
197 }
198 }
199
200 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
201
202
203 SDOperand getIntPtrConstant(uint64_t Val) {
204 return DAG.getConstant(Val, TLI.getPointerTy());
205 }
206
207 SDOperand getValue(const Value *V) {
208 SDOperand &N = NodeMap[V];
209 if (N.Val) return N;
210
211 MVT::ValueType VT = TLI.getValueType(V->getType());
212 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
213 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
214 visit(CE->getOpcode(), *CE);
215 assert(N.Val && "visit didn't populate the ValueMap!");
216 return N;
217 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
218 return N = DAG.getGlobalAddress(GV, VT);
219 } else if (isa<ConstantPointerNull>(C)) {
220 return N = DAG.getConstant(0, TLI.getPointerTy());
221 } else if (isa<UndefValue>(C)) {
222 /// FIXME: Implement UNDEFVALUE better.
223 if (MVT::isInteger(VT))
224 return N = DAG.getConstant(0, VT);
225 else if (MVT::isFloatingPoint(VT))
226 return N = DAG.getConstantFP(0, VT);
227 else
228 assert(0 && "Unknown value type!");
229
230 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
231 return N = DAG.getConstantFP(CFP->getValue(), VT);
232 } else {
233 // Canonicalize all constant ints to be unsigned.
234 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
235 }
236
237 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
238 std::map<const AllocaInst*, int>::iterator SI =
239 FuncInfo.StaticAllocaMap.find(AI);
240 if (SI != FuncInfo.StaticAllocaMap.end())
241 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
242 }
243
244 std::map<const Value*, unsigned>::const_iterator VMI =
245 FuncInfo.ValueMap.find(V);
246 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
247 return N = DAG.getCopyFromReg(VMI->second, VT);
248 }
249
250 const SDOperand &setValue(const Value *V, SDOperand NewN) {
251 SDOperand &N = NodeMap[V];
252 assert(N.Val == 0 && "Already set a value for this node!");
253 return N = NewN;
254 }
255
256 // Terminator instructions.
257 void visitRet(ReturnInst &I);
258 void visitBr(BranchInst &I);
259 void visitUnreachable(UnreachableInst &I) { /* noop */ }
260
261 // These all get lowered before this pass.
262 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
263 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
264 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
265
266 //
267 void visitBinary(User &I, unsigned Opcode);
268 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
269 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
270 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
271 void visitDiv(User &I) {
272 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
273 }
274 void visitRem(User &I) {
275 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
276 }
277 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
278 void visitOr (User &I) { visitBinary(I, ISD::OR); }
279 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
280 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
281 void visitShr(User &I) {
282 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
283 }
284
285 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
286 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
287 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
288 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
289 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
290 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
291 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
292
293 void visitGetElementPtr(User &I);
294 void visitCast(User &I);
295 void visitSelect(User &I);
296 //
297
298 void visitMalloc(MallocInst &I);
299 void visitFree(FreeInst &I);
300 void visitAlloca(AllocaInst &I);
301 void visitLoad(LoadInst &I);
302 void visitStore(StoreInst &I);
303 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
304 void visitCall(CallInst &I);
305
306 // FIXME: These should go through the FunctionLoweringInfo object!!!
307 void visitVAStart(CallInst &I);
308 void visitVANext(VANextInst &I);
309 void visitVAArg(VAArgInst &I);
310 void visitVAEnd(CallInst &I);
311 void visitVACopy(CallInst &I);
312 void visitReturnAddress(CallInst &I);
313 void visitFrameAddress(CallInst &I);
314
315 void visitMemSet(CallInst &I);
316 void visitMemCpy(CallInst &I);
317 void visitMemMove(CallInst &I);
318
319 void visitUserOp1(Instruction &I) {
320 assert(0 && "UserOp1 should not exist at instruction selection time!");
321 abort();
322 }
323 void visitUserOp2(Instruction &I) {
324 assert(0 && "UserOp2 should not exist at instruction selection time!");
325 abort();
326 }
327};
328} // end namespace llvm
329
330void SelectionDAGLowering::visitRet(ReturnInst &I) {
331 if (I.getNumOperands() == 0) {
332 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, DAG.getRoot()));
333 return;
334 }
335
336 SDOperand Op1 = getValue(I.getOperand(0));
337 switch (Op1.getValueType()) {
338 default: assert(0 && "Unknown value type!");
339 case MVT::i1:
340 case MVT::i8:
341 case MVT::i16:
342 // Extend integer types to 32-bits.
343 if (I.getOperand(0)->getType()->isSigned())
344 Op1 = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Op1);
345 else
346 Op1 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op1);
347 break;
348 case MVT::f32:
349 // Extend float to double.
350 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
351 break;
352 case MVT::i32:
353 case MVT::i64:
354 case MVT::f64:
355 break; // No extension needed!
356 }
357
358 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, DAG.getRoot(), Op1));
359}
360
361void SelectionDAGLowering::visitBr(BranchInst &I) {
362 // Update machine-CFG edges.
363 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
364 CurMBB->addSuccessor(Succ0MBB);
365
366 // Figure out which block is immediately after the current one.
367 MachineBasicBlock *NextBlock = 0;
368 MachineFunction::iterator BBI = CurMBB;
369 if (++BBI != CurMBB->getParent()->end())
370 NextBlock = BBI;
371
372 if (I.isUnconditional()) {
373 // If this is not a fall-through branch, emit the branch.
374 if (Succ0MBB != NextBlock)
375 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, DAG.getRoot(),
376 DAG.getBasicBlock(Succ0MBB)));
377 } else {
378 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
379 CurMBB->addSuccessor(Succ1MBB);
380
381 SDOperand Cond = getValue(I.getCondition());
382
383 if (Succ1MBB == NextBlock) {
384 // If the condition is false, fall through. This means we should branch
385 // if the condition is true to Succ #0.
386 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
387 Cond, DAG.getBasicBlock(Succ0MBB)));
388 } else if (Succ0MBB == NextBlock) {
389 // If the condition is true, fall through. This means we should branch if
390 // the condition is false to Succ #1. Invert the condition first.
391 SDOperand True = DAG.getConstant(1, Cond.getValueType());
392 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
393 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
394 Cond, DAG.getBasicBlock(Succ1MBB)));
395 } else {
396 // Neither edge is a fall through. If the comparison is true, jump to
397 // Succ#0, otherwise branch unconditionally to succ #1.
398 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, DAG.getRoot(),
399 Cond, DAG.getBasicBlock(Succ0MBB)));
400 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, DAG.getRoot(),
401 DAG.getBasicBlock(Succ1MBB)));
402 }
403 }
404}
405
406void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
407 SDOperand Op1 = getValue(I.getOperand(0));
408 SDOperand Op2 = getValue(I.getOperand(1));
409 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
410}
411
412void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
413 ISD::CondCode UnsignedOpcode) {
414 SDOperand Op1 = getValue(I.getOperand(0));
415 SDOperand Op2 = getValue(I.getOperand(1));
416 ISD::CondCode Opcode = SignedOpcode;
417 if (I.getOperand(0)->getType()->isUnsigned())
418 Opcode = UnsignedOpcode;
419 setValue(&I, DAG.getSetCC(Opcode, Op1, Op2));
420}
421
422void SelectionDAGLowering::visitSelect(User &I) {
423 SDOperand Cond = getValue(I.getOperand(0));
424 SDOperand TrueVal = getValue(I.getOperand(1));
425 SDOperand FalseVal = getValue(I.getOperand(2));
426 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
427 TrueVal, FalseVal));
428}
429
430void SelectionDAGLowering::visitCast(User &I) {
431 SDOperand N = getValue(I.getOperand(0));
432 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
433 MVT::ValueType DestTy = TLI.getValueType(I.getType());
434
435 if (N.getValueType() == DestTy) {
436 setValue(&I, N); // noop cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000437 } else if (isInteger(SrcTy)) {
438 if (isInteger(DestTy)) { // Int -> Int cast
439 if (DestTy < SrcTy) // Truncating cast?
440 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
441 else if (I.getOperand(0)->getType()->isSigned())
442 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
443 else
444 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
445 } else { // Int -> FP cast
446 if (I.getOperand(0)->getType()->isSigned())
447 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
448 else
449 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
450 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000451 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000452 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
453 if (isFloatingPoint(DestTy)) { // FP -> FP cast
454 if (DestTy < SrcTy) // Rounding cast?
455 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
456 else
457 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
458 } else { // FP -> Int cast.
459 if (I.getType()->isSigned())
460 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
461 else
462 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
463 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000464 }
465}
466
467void SelectionDAGLowering::visitGetElementPtr(User &I) {
468 SDOperand N = getValue(I.getOperand(0));
469 const Type *Ty = I.getOperand(0)->getType();
470 const Type *UIntPtrTy = TD.getIntPtrType();
471
472 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
473 OI != E; ++OI) {
474 Value *Idx = *OI;
475 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
476 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
477 if (Field) {
478 // N = N + Offset
479 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
480 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
481 getIntPtrConstant(Offset));
482 }
483 Ty = StTy->getElementType(Field);
484 } else {
485 Ty = cast<SequentialType>(Ty)->getElementType();
486 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
487 // N = N + Idx * ElementSize;
488 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000489 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
490
491 // If the index is smaller or larger than intptr_t, truncate or extend
492 // it.
493 if (IdxN.getValueType() < Scale.getValueType()) {
494 if (Idx->getType()->isSigned())
495 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
496 else
497 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
498 } else if (IdxN.getValueType() > Scale.getValueType())
499 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
500
501 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
502
Chris Lattner7a60d912005-01-07 07:47:53 +0000503 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
504 }
505 }
506 }
507 setValue(&I, N);
508}
509
510void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
511 // If this is a fixed sized alloca in the entry block of the function,
512 // allocate it statically on the stack.
513 if (FuncInfo.StaticAllocaMap.count(&I))
514 return; // getValue will auto-populate this.
515
516 const Type *Ty = I.getAllocatedType();
517 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
518 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
519
520 SDOperand AllocSize = getValue(I.getArraySize());
521
522 assert(AllocSize.getValueType() == TLI.getPointerTy() &&
523 "FIXME: should extend or truncate to pointer size!");
524
525 AllocSize = DAG.getNode(ISD::MUL, TLI.getPointerTy(), AllocSize,
526 getIntPtrConstant(TySize));
527
528 // Handle alignment. If the requested alignment is less than or equal to the
529 // stack alignment, ignore it and round the size of the allocation up to the
530 // stack alignment size. If the size is greater than the stack alignment, we
531 // note this in the DYNAMIC_STACKALLOC node.
532 unsigned StackAlign =
533 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
534 if (Align <= StackAlign) {
535 Align = 0;
536 // Add SA-1 to the size.
537 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
538 getIntPtrConstant(StackAlign-1));
539 // Mask out the low bits for alignment purposes.
540 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
541 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
542 }
543
544 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
545 DAG.getRoot(), AllocSize,
546 getIntPtrConstant(Align));
547 DAG.setRoot(setValue(&I, DSA).getValue(1));
548
549 // Inform the Frame Information that we have just allocated a variable-sized
550 // object.
551 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
552}
553
554
555void SelectionDAGLowering::visitLoad(LoadInst &I) {
556 SDOperand Ptr = getValue(I.getOperand(0));
557 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), DAG.getRoot(), Ptr);
558 DAG.setRoot(setValue(&I, L).getValue(1));
559}
560
561
562void SelectionDAGLowering::visitStore(StoreInst &I) {
563 Value *SrcV = I.getOperand(0);
564 SDOperand Src = getValue(SrcV);
565 SDOperand Ptr = getValue(I.getOperand(1));
566 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, DAG.getRoot(), Src, Ptr));
567 return;
568}
569
570void SelectionDAGLowering::visitCall(CallInst &I) {
571 if (Function *F = I.getCalledFunction())
572 switch (F->getIntrinsicID()) {
573 case 0: break; // Not an intrinsic.
574 case Intrinsic::vastart: visitVAStart(I); return;
575 case Intrinsic::vaend: visitVAEnd(I); return;
576 case Intrinsic::vacopy: visitVACopy(I); return;
577 case Intrinsic::returnaddress:
578 visitReturnAddress(I); return;
579 case Intrinsic::frameaddress:
580 visitFrameAddress(I); return;
581 default:
582 // FIXME: IMPLEMENT THESE.
583 // readport, writeport, readio, writeio
584 assert(0 && "This intrinsic is not implemented yet!");
585 return;
586 case Intrinsic::memcpy: visitMemCpy(I); return;
587 case Intrinsic::memset: visitMemSet(I); return;
588 case Intrinsic::memmove: visitMemMove(I); return;
589
590 case Intrinsic::isunordered:
591 setValue(&I, DAG.getSetCC(ISD::SETUO, getValue(I.getOperand(1)),
592 getValue(I.getOperand(2))));
593 return;
594 }
595
596 SDOperand Callee = getValue(I.getOperand(0));
597 std::vector<std::pair<SDOperand, const Type*> > Args;
598
599 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
600 Value *Arg = I.getOperand(i);
601 SDOperand ArgNode = getValue(Arg);
602 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
603 }
604
Chris Lattner1f45cd72005-01-08 19:26:18 +0000605 std::pair<SDOperand,SDOperand> Result =
606 TLI.LowerCallTo(DAG.getRoot(), I.getType(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000607 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000608 setValue(&I, Result.first);
609 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000610}
611
612void SelectionDAGLowering::visitMalloc(MallocInst &I) {
613 SDOperand Src = getValue(I.getOperand(0));
614
615 MVT::ValueType IntPtr = TLI.getPointerTy();
616 // FIXME: Extend or truncate to the intptr size.
617 assert(Src.getValueType() == IntPtr && "Need to adjust the amount!");
618
619 // Scale the source by the type size.
620 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
621 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
622 Src, getIntPtrConstant(ElementSize));
623
624 std::vector<std::pair<SDOperand, const Type*> > Args;
625 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000626
627 std::pair<SDOperand,SDOperand> Result =
628 TLI.LowerCallTo(DAG.getRoot(), I.getType(),
629 DAG.getExternalSymbol("malloc", IntPtr),
630 Args, DAG);
631 setValue(&I, Result.first); // Pointers always fit in registers
632 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000633}
634
635void SelectionDAGLowering::visitFree(FreeInst &I) {
636 std::vector<std::pair<SDOperand, const Type*> > Args;
637 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
638 TLI.getTargetData().getIntPtrType()));
639 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000640 std::pair<SDOperand,SDOperand> Result =
641 TLI.LowerCallTo(DAG.getRoot(), Type::VoidTy,
642 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
643 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000644}
645
646void SelectionDAGLowering::visitVAStart(CallInst &I) {
647 // We have no sane default behavior, just emit a useful error message and bail
648 // out.
649 std::cerr << "Variable arguments support not implemented for this target!\n";
650 abort();
651}
652
653void SelectionDAGLowering::visitVANext(VANextInst &I) {
654 // We have no sane default behavior, just emit a useful error message and bail
655 // out.
656 std::cerr << "Variable arguments support not implemented for this target!\n";
657 abort();
658}
659void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
660 // We have no sane default behavior, just emit a useful error message and bail
661 // out.
662 std::cerr << "Variable arguments support not implemented for this target!\n";
663 abort();
664}
665
666void SelectionDAGLowering::visitVAEnd(CallInst &I) {
667 // By default, this is a noop. On almost all targets, this is fine.
668}
669
670void SelectionDAGLowering::visitVACopy(CallInst &I) {
671 // By default, vacopy just does a simple pointer copy.
672 setValue(&I, getValue(I.getOperand(1)));
673}
674
675void SelectionDAGLowering::visitReturnAddress(CallInst &I) {
676 // It is always conservatively correct for llvm.returnaddress to return 0.
677 setValue(&I, getIntPtrConstant(0));
678}
679
680void SelectionDAGLowering::visitFrameAddress(CallInst &I) {
681 // It is always conservatively correct for llvm.frameaddress to return 0.
682 setValue(&I, getIntPtrConstant(0));
683}
684
685
686void SelectionDAGLowering::visitMemSet(CallInst &I) {
687 MVT::ValueType IntPtr = TLI.getPointerTy();
688 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
689
690 // Extend the ubyte argument to be an int value for the call.
691 SDOperand Val = getValue(I.getOperand(2));
692 Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Val);
693
694 std::vector<std::pair<SDOperand, const Type*> > Args;
695 Args.push_back(std::make_pair(getValue(I.getOperand(1)), IntPtrTy));
696 Args.push_back(std::make_pair(Val, Type::IntTy));
697 Args.push_back(std::make_pair(getValue(I.getOperand(3)), IntPtrTy));
698
Chris Lattner1f45cd72005-01-08 19:26:18 +0000699 std::pair<SDOperand,SDOperand> Result =
700 TLI.LowerCallTo(DAG.getRoot(), Type::VoidTy,
701 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
702 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000703}
704
705void SelectionDAGLowering::visitMemCpy(CallInst &I) {
706 MVT::ValueType IntPtr = TLI.getPointerTy();
707 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
708
709 std::vector<std::pair<SDOperand, const Type*> > Args;
710 Args.push_back(std::make_pair(getValue(I.getOperand(1)), IntPtrTy));
711 Args.push_back(std::make_pair(getValue(I.getOperand(2)), IntPtrTy));
712 Args.push_back(std::make_pair(getValue(I.getOperand(3)), IntPtrTy));
713
Chris Lattner1f45cd72005-01-08 19:26:18 +0000714 std::pair<SDOperand,SDOperand> Result =
715 TLI.LowerCallTo(DAG.getRoot(), Type::VoidTy,
716 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
717 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000718}
719
720void SelectionDAGLowering::visitMemMove(CallInst &I) {
721 MVT::ValueType IntPtr = TLI.getPointerTy();
722 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
723
724 std::vector<std::pair<SDOperand, const Type*> > Args;
725 Args.push_back(std::make_pair(getValue(I.getOperand(1)), IntPtrTy));
726 Args.push_back(std::make_pair(getValue(I.getOperand(2)), IntPtrTy));
727 Args.push_back(std::make_pair(getValue(I.getOperand(3)), IntPtrTy));
728
Chris Lattner1f45cd72005-01-08 19:26:18 +0000729 std::pair<SDOperand,SDOperand> Result =
730 TLI.LowerCallTo(DAG.getRoot(), Type::VoidTy,
731 DAG.getExternalSymbol("memmove", IntPtr), Args, DAG);
732 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000733}
734
735unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
736 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
737}
738
739
740
741bool SelectionDAGISel::runOnFunction(Function &Fn) {
742 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
743 RegMap = MF.getSSARegMap();
744 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
745
746 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
747
748 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
749 SelectBasicBlock(I, MF, FuncInfo);
750
751 return true;
752}
753
754
755void SelectionDAGISel::CopyValueToVirtualRegister(SelectionDAGLowering &SDL,
756 Value *V, unsigned Reg) {
757 SelectionDAG &DAG = SDL.DAG;
758 DAG.setRoot(DAG.getCopyToReg(DAG.getRoot(), SDL.getValue(V), Reg));
759}
760
761void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
762 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
763 FunctionLoweringInfo &FuncInfo) {
764 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
765
766 // If this is the entry block, emit arguments.
767 Function *F = LLVMBB->getParent();
768 if (LLVMBB == &F->front()) {
769 // FIXME: If an argument is only used in one basic block, we could directly
770 // emit it (ONLY) into that block, not emitting the COPY_TO_VREG node. This
771 // would improve codegen in several cases on X86 by allowing the loads to be
772 // folded into the user operation.
773 std::vector<SDOperand> Args = TLI.LowerArguments(*LLVMBB->getParent(), DAG);
774
775 unsigned a = 0;
776 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI,++a)
777 if (!AI->use_empty()) {
778 SDL.setValue(AI, Args[a]);
779 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
780 }
781 }
782
783 BB = FuncInfo.MBBMap[LLVMBB];
784 SDL.setCurrentBasicBlock(BB);
785
786 // Lower all of the non-terminator instructions.
787 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
788 I != E; ++I)
789 SDL.visit(*I);
790
791 // Ensure that all instructions which are used outside of their defining
792 // blocks are available as virtual registers.
793 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
794 if (!I->use_empty()) {
795 std::map<const Value*, unsigned>::iterator VMI =
796 FuncInfo.ValueMap.find(I);
797 if (VMI != FuncInfo.ValueMap.end())
798 CopyValueToVirtualRegister(SDL, I, VMI->second);
799 }
800
801 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
802 // ensure constants are generated when needed. Remember the virtual registers
803 // that need to be added to the Machine PHI nodes as input. We cannot just
804 // directly add them, because expansion might result in multiple MBB's for one
805 // BB. As such, the start of the BB might correspond to a different MBB than
806 // the end.
807 //
808
809 // Emit constants only once even if used by multiple PHI nodes.
810 std::map<Constant*, unsigned> ConstantsOut;
811
812 // Check successor nodes PHI nodes that expect a constant to be available from
813 // this block.
814 TerminatorInst *TI = LLVMBB->getTerminator();
815 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
816 BasicBlock *SuccBB = TI->getSuccessor(succ);
817 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
818 PHINode *PN;
819
820 // At this point we know that there is a 1-1 correspondence between LLVM PHI
821 // nodes and Machine PHI nodes, but the incoming operands have not been
822 // emitted yet.
823 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000824 (PN = dyn_cast<PHINode>(I)); ++I)
825 if (!PN->use_empty()) {
826 unsigned Reg;
827 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
828 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
829 unsigned &RegOut = ConstantsOut[C];
830 if (RegOut == 0) {
831 RegOut = FuncInfo.CreateRegForValue(C);
832 CopyValueToVirtualRegister(SDL, C, RegOut);
833 }
834 Reg = RegOut;
835 } else {
836 Reg = FuncInfo.ValueMap[PHIOp];
837 assert(Reg && "Didn't codegen value into a register!??");
Chris Lattner7a60d912005-01-07 07:47:53 +0000838 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000839
840 // Remember that this register needs to added to the machine PHI node as
841 // the input for this MBB.
842 unsigned NumElements =
843 TLI.getNumElements(TLI.getValueType(PN->getType()));
844 for (unsigned i = 0, e = NumElements; i != e; ++i)
845 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +0000846 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000847 }
848 ConstantsOut.clear();
849
850 // Lower the terminator after the copies are emitted.
851 SDL.visit(*LLVMBB->getTerminator());
852}
853
854void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
855 FunctionLoweringInfo &FuncInfo) {
856 SelectionDAG DAG(TLI.getTargetMachine(), MF);
857 CurDAG = &DAG;
858 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
859
860 // First step, lower LLVM code to some DAG. This DAG may use operations and
861 // types that are not supported by the target.
862 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
863
864 DEBUG(std::cerr << "Lowered selection DAG:\n");
865 DEBUG(DAG.dump());
866
867 // Second step, hack on the DAG until it only uses operations and types that
868 // the target supports.
869 DAG.Legalize(TLI);
870
871 DEBUG(std::cerr << "Legalized selection DAG:\n");
872 DEBUG(DAG.dump());
873
874 // Finally, instruction select all of the operations to machine code, adding
875 // the code to the MachineBasicBlock.
876 InstructionSelectBasicBlock(DAG);
877
878 DEBUG(std::cerr << "Selected machine code:\n");
879 DEBUG(BB->dump());
880
881 // Finally, now that we know what the last MBB the LLVM BB expanded is, update
882 // PHI nodes in successors.
883 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
884 MachineInstr *PHI = PHINodesToUpdate[i].first;
885 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
886 "This is not a machine PHI node that we are updating!");
887 PHI->addRegOperand(PHINodesToUpdate[i].second);
888 PHI->addMachineBasicBlockOperand(BB);
889 }
890}