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