blob: d6ec50ae166e757e37e04a8ff853abbf7b634c57 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// 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.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/SelectionDAG.h"
25#include "llvm/CodeGen/SSARegMap.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetFrameInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetMachine.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/Support/Debug.h"
33#include <map>
34#include <iostream>
35using namespace llvm;
36
Chris Lattner7944d9d2005-01-12 03:41:21 +000037#ifndef _NDEBUG
38static cl::opt<bool>
39ViewDAGs("view-isel-dags", cl::Hidden,
40 cl::desc("Pop up a window to show isel dags as they are selected"));
41#else
42static const bool ViewDAGS = 0;
43#endif
44
Chris Lattner1c08c712005-01-07 07:47:53 +000045namespace llvm {
46 //===--------------------------------------------------------------------===//
47 /// FunctionLoweringInfo - This contains information that is global to a
48 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000049 class FunctionLoweringInfo {
50 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000051 TargetLowering &TLI;
52 Function &Fn;
53 MachineFunction &MF;
54 SSARegMap *RegMap;
55
56 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
57
58 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
59 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
60
61 /// ValueMap - Since we emit code for the function a basic block at a time,
62 /// we must remember which virtual registers hold the values for
63 /// cross-basic-block values.
64 std::map<const Value*, unsigned> ValueMap;
65
66 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
67 /// the entry block. This allows the allocas to be efficiently referenced
68 /// anywhere in the function.
69 std::map<const AllocaInst*, int> StaticAllocaMap;
70
Chris Lattner0afa8e32005-01-17 17:55:19 +000071 /// BlockLocalArguments - If any arguments are only used in a single basic
72 /// block, and if the target can access the arguments without side-effects,
73 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
74 /// track of which arguments are local to each BB.
75 std::multimap<BasicBlock*, std::pair<Argument*,
76 unsigned> > BlockLocalArguments;
77
78
Chris Lattner1c08c712005-01-07 07:47:53 +000079 unsigned MakeReg(MVT::ValueType VT) {
80 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
81 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000082
Chris Lattner1c08c712005-01-07 07:47:53 +000083 unsigned CreateRegForValue(const Value *V) {
84 MVT::ValueType VT = TLI.getValueType(V->getType());
85 // The common case is that we will only create one register for this
86 // value. If we have that case, create and return the virtual register.
87 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +000088 if (NV == 1) {
89 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000090 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000091 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000092
Chris Lattner1c08c712005-01-07 07:47:53 +000093 // 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;
Misha Brukmanedf128a2005-04-21 22:36:52 +000098
Chris Lattner1c08c712005-01-07 07:47:53 +000099 unsigned R = MakeReg((MVT::ValueType)NT);
100 for (unsigned i = 1; i != NV; ++i)
101 MakeReg((MVT::ValueType)NT);
102 return R;
103 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000104
Chris Lattner1c08c712005-01-07 07:47:53 +0000105 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,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000125 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000126 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
127
128 // Initialize the mapping of values to registers. This is only set up for
129 // instruction values that are used outside of the block that defines
130 // them.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000131 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); AI != E; ++AI)
Chris Lattner1c08c712005-01-07 07:47:53 +0000132 InitializeRegForValue(AI);
133
134 Function::iterator BB = Fn.begin(), E = Fn.end();
135 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
136 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
137 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
138 const Type *Ty = AI->getAllocatedType();
139 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
140 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
141 TySize *= CUI->getValue(); // Get total allocated size.
142 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000143 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000144 }
145
146 for (; BB != E; ++BB)
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000147 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000148 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
149 if (!isa<AllocaInst>(I) ||
150 !StaticAllocaMap.count(cast<AllocaInst>(I)))
151 InitializeRegForValue(I);
152
153 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
154 // also creates the initial PHI MachineInstrs, though none of the input
155 // operands are populated.
156 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
157 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
158 MBBMap[BB] = MBB;
159 MF.getBasicBlockList().push_back(MBB);
160
161 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
162 // appropriate.
163 PHINode *PN;
164 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000165 (PN = dyn_cast<PHINode>(I)); ++I)
166 if (!PN->use_empty()) {
167 unsigned NumElements =
168 TLI.getNumElements(TLI.getValueType(PN->getType()));
169 unsigned PHIReg = ValueMap[PN];
170 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
171 for (unsigned i = 0; i != NumElements; ++i)
172 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
173 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 }
175}
176
177
178
179//===----------------------------------------------------------------------===//
180/// SelectionDAGLowering - This is the common target-independent lowering
181/// implementation that is parameterized by a TargetLowering object.
182/// Also, targets can overload any lowering method.
183///
184namespace llvm {
185class SelectionDAGLowering {
186 MachineBasicBlock *CurMBB;
187
188 std::map<const Value*, SDOperand> NodeMap;
189
Chris Lattnerd3948112005-01-17 22:19:26 +0000190 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
191 /// them up and then emit token factor nodes when possible. This allows us to
192 /// get simple disambiguation between loads without worrying about alias
193 /// analysis.
194 std::vector<SDOperand> PendingLoads;
195
Chris Lattner1c08c712005-01-07 07:47:53 +0000196public:
197 // TLI - This is information that describes the available target features we
198 // need for lowering. This indicates when operations are unavailable,
199 // implemented with a libcall, etc.
200 TargetLowering &TLI;
201 SelectionDAG &DAG;
202 const TargetData &TD;
203
204 /// FuncInfo - Information about the function as a whole.
205 ///
206 FunctionLoweringInfo &FuncInfo;
207
208 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000209 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000210 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
211 FuncInfo(funcinfo) {
212 }
213
Chris Lattnera651cf62005-01-17 19:43:36 +0000214 /// getRoot - Return the current virtual root of the Selection DAG.
215 ///
216 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000217 if (PendingLoads.empty())
218 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000219
Chris Lattnerd3948112005-01-17 22:19:26 +0000220 if (PendingLoads.size() == 1) {
221 SDOperand Root = PendingLoads[0];
222 DAG.setRoot(Root);
223 PendingLoads.clear();
224 return Root;
225 }
226
227 // Otherwise, we have to make a token factor node.
228 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
229 PendingLoads.clear();
230 DAG.setRoot(Root);
231 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000232 }
233
Chris Lattner1c08c712005-01-07 07:47:53 +0000234 void visit(Instruction &I) { visit(I.getOpcode(), I); }
235
236 void visit(unsigned Opcode, User &I) {
237 switch (Opcode) {
238 default: assert(0 && "Unknown instruction type encountered!");
239 abort();
240 // Build the switch statement using the Instruction.def file.
241#define HANDLE_INST(NUM, OPCODE, CLASS) \
242 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
243#include "llvm/Instruction.def"
244 }
245 }
246
247 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
248
249
250 SDOperand getIntPtrConstant(uint64_t Val) {
251 return DAG.getConstant(Val, TLI.getPointerTy());
252 }
253
254 SDOperand getValue(const Value *V) {
255 SDOperand &N = NodeMap[V];
256 if (N.Val) return N;
257
258 MVT::ValueType VT = TLI.getValueType(V->getType());
259 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
261 visit(CE->getOpcode(), *CE);
262 assert(N.Val && "visit didn't populate the ValueMap!");
263 return N;
264 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
265 return N = DAG.getGlobalAddress(GV, VT);
266 } else if (isa<ConstantPointerNull>(C)) {
267 return N = DAG.getConstant(0, TLI.getPointerTy());
268 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000269 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000270 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
271 return N = DAG.getConstantFP(CFP->getValue(), VT);
272 } else {
273 // Canonicalize all constant ints to be unsigned.
274 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
275 }
276
277 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
278 std::map<const AllocaInst*, int>::iterator SI =
279 FuncInfo.StaticAllocaMap.find(AI);
280 if (SI != FuncInfo.StaticAllocaMap.end())
281 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
282 }
283
284 std::map<const Value*, unsigned>::const_iterator VMI =
285 FuncInfo.ValueMap.find(V);
286 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000287
Chris Lattneref5cd1d2005-01-18 17:54:55 +0000288 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode());
Chris Lattner1c08c712005-01-07 07:47:53 +0000289 }
290
291 const SDOperand &setValue(const Value *V, SDOperand NewN) {
292 SDOperand &N = NodeMap[V];
293 assert(N.Val == 0 && "Already set a value for this node!");
294 return N = NewN;
295 }
296
297 // Terminator instructions.
298 void visitRet(ReturnInst &I);
299 void visitBr(BranchInst &I);
300 void visitUnreachable(UnreachableInst &I) { /* noop */ }
301
302 // These all get lowered before this pass.
303 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
304 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
305 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
306
307 //
308 void visitBinary(User &I, unsigned Opcode);
309 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000310 void visitSub(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000311 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
312 void visitDiv(User &I) {
313 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
314 }
315 void visitRem(User &I) {
316 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
317 }
318 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
319 void visitOr (User &I) { visitBinary(I, ISD::OR); }
320 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
321 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
322 void visitShr(User &I) {
323 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
324 }
325
326 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
327 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
328 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
329 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
330 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
331 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
332 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
333
334 void visitGetElementPtr(User &I);
335 void visitCast(User &I);
336 void visitSelect(User &I);
337 //
338
339 void visitMalloc(MallocInst &I);
340 void visitFree(FreeInst &I);
341 void visitAlloca(AllocaInst &I);
342 void visitLoad(LoadInst &I);
343 void visitStore(StoreInst &I);
344 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
345 void visitCall(CallInst &I);
346
Chris Lattner1c08c712005-01-07 07:47:53 +0000347 void visitVAStart(CallInst &I);
348 void visitVANext(VANextInst &I);
349 void visitVAArg(VAArgInst &I);
350 void visitVAEnd(CallInst &I);
351 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000352 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000353
Chris Lattner7041ee32005-01-11 05:56:49 +0000354 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000355
356 void visitUserOp1(Instruction &I) {
357 assert(0 && "UserOp1 should not exist at instruction selection time!");
358 abort();
359 }
360 void visitUserOp2(Instruction &I) {
361 assert(0 && "UserOp2 should not exist at instruction selection time!");
362 abort();
363 }
364};
365} // end namespace llvm
366
367void SelectionDAGLowering::visitRet(ReturnInst &I) {
368 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000369 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 return;
371 }
372
373 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000374 MVT::ValueType TmpVT;
375
Chris Lattner1c08c712005-01-07 07:47:53 +0000376 switch (Op1.getValueType()) {
377 default: assert(0 && "Unknown value type!");
378 case MVT::i1:
379 case MVT::i8:
380 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000381 case MVT::i32:
382 // If this is a machine where 32-bits is legal or expanded, promote to
383 // 32-bits, otherwise, promote to 64-bits.
384 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
385 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000386 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000387 TmpVT = MVT::i32;
388
389 // Extend integer types to result type.
390 if (I.getOperand(0)->getType()->isSigned())
391 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
392 else
393 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000394 break;
395 case MVT::f32:
396 // Extend float to double.
397 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
398 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000399 case MVT::i64:
400 case MVT::f64:
401 break; // No extension needed!
402 }
403
Chris Lattnera651cf62005-01-17 19:43:36 +0000404 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000405}
406
407void SelectionDAGLowering::visitBr(BranchInst &I) {
408 // Update machine-CFG edges.
409 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000410
411 // Figure out which block is immediately after the current one.
412 MachineBasicBlock *NextBlock = 0;
413 MachineFunction::iterator BBI = CurMBB;
414 if (++BBI != CurMBB->getParent()->end())
415 NextBlock = BBI;
416
417 if (I.isUnconditional()) {
418 // If this is not a fall-through branch, emit the branch.
419 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000420 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000421 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000422 } else {
423 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000424
425 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 if (Succ1MBB == NextBlock) {
427 // If the condition is false, fall through. This means we should branch
428 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000429 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000430 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 } else if (Succ0MBB == NextBlock) {
432 // If the condition is true, fall through. This means we should branch if
433 // the condition is false to Succ #1. Invert the condition first.
434 SDOperand True = DAG.getConstant(1, Cond.getValueType());
435 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000436 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000437 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000438 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000439 std::vector<SDOperand> Ops;
440 Ops.push_back(getRoot());
441 Ops.push_back(Cond);
442 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
443 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
444 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000445 }
446 }
447}
448
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000449void SelectionDAGLowering::visitSub(User &I) {
450 // -0.0 - X --> fneg
451 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
452 if (CFP->isExactlyValue(-0.0)) {
453 SDOperand Op2 = getValue(I.getOperand(1));
454 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
455 return;
456 }
457
458 visitBinary(I, ISD::SUB);
459}
460
Chris Lattner1c08c712005-01-07 07:47:53 +0000461void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
462 SDOperand Op1 = getValue(I.getOperand(0));
463 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000464
465 if (isa<ShiftInst>(I))
466 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2);
467
Chris Lattner1c08c712005-01-07 07:47:53 +0000468 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
469}
470
471void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
472 ISD::CondCode UnsignedOpcode) {
473 SDOperand Op1 = getValue(I.getOperand(0));
474 SDOperand Op2 = getValue(I.getOperand(1));
475 ISD::CondCode Opcode = SignedOpcode;
476 if (I.getOperand(0)->getType()->isUnsigned())
477 Opcode = UnsignedOpcode;
Chris Lattnerf30b73b2005-01-18 02:52:03 +0000478 setValue(&I, DAG.getSetCC(Opcode, MVT::i1, Op1, Op2));
Chris Lattner1c08c712005-01-07 07:47:53 +0000479}
480
481void SelectionDAGLowering::visitSelect(User &I) {
482 SDOperand Cond = getValue(I.getOperand(0));
483 SDOperand TrueVal = getValue(I.getOperand(1));
484 SDOperand FalseVal = getValue(I.getOperand(2));
485 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
486 TrueVal, FalseVal));
487}
488
489void SelectionDAGLowering::visitCast(User &I) {
490 SDOperand N = getValue(I.getOperand(0));
491 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
492 MVT::ValueType DestTy = TLI.getValueType(I.getType());
493
494 if (N.getValueType() == DestTy) {
495 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000496 } else if (DestTy == MVT::i1) {
497 // Cast to bool is a comparison against zero, not truncation to zero.
498 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
499 DAG.getConstantFP(0.0, N.getValueType());
500 setValue(&I, DAG.getSetCC(ISD::SETNE, MVT::i1, N, Zero));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000501 } else if (isInteger(SrcTy)) {
502 if (isInteger(DestTy)) { // Int -> Int cast
503 if (DestTy < SrcTy) // Truncating cast?
504 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
505 else if (I.getOperand(0)->getType()->isSigned())
506 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
507 else
508 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
509 } else { // Int -> FP cast
510 if (I.getOperand(0)->getType()->isSigned())
511 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
512 else
513 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
514 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000515 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000516 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
517 if (isFloatingPoint(DestTy)) { // FP -> FP cast
518 if (DestTy < SrcTy) // Rounding cast?
519 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
520 else
521 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
522 } else { // FP -> Int cast.
523 if (I.getType()->isSigned())
524 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
525 else
526 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
527 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000528 }
529}
530
531void SelectionDAGLowering::visitGetElementPtr(User &I) {
532 SDOperand N = getValue(I.getOperand(0));
533 const Type *Ty = I.getOperand(0)->getType();
534 const Type *UIntPtrTy = TD.getIntPtrType();
535
536 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
537 OI != E; ++OI) {
538 Value *Idx = *OI;
539 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
540 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
541 if (Field) {
542 // N = N + Offset
543 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
544 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000545 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000546 }
547 Ty = StTy->getElementType(Field);
548 } else {
549 Ty = cast<SequentialType>(Ty)->getElementType();
550 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
551 // N = N + Idx * ElementSize;
552 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner7cc47772005-01-07 21:56:57 +0000553 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
554
555 // If the index is smaller or larger than intptr_t, truncate or extend
556 // it.
557 if (IdxN.getValueType() < Scale.getValueType()) {
558 if (Idx->getType()->isSigned())
559 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
560 else
561 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
562 } else if (IdxN.getValueType() > Scale.getValueType())
563 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
564
565 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner1c08c712005-01-07 07:47:53 +0000566 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
567 }
568 }
569 }
570 setValue(&I, N);
571}
572
573void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
574 // If this is a fixed sized alloca in the entry block of the function,
575 // allocate it statically on the stack.
576 if (FuncInfo.StaticAllocaMap.count(&I))
577 return; // getValue will auto-populate this.
578
579 const Type *Ty = I.getAllocatedType();
580 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
581 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
582
583 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000584 MVT::ValueType IntPtr = TLI.getPointerTy();
585 if (IntPtr < AllocSize.getValueType())
586 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
587 else if (IntPtr > AllocSize.getValueType())
588 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000589
Chris Lattner68cd65e2005-01-22 23:04:37 +0000590 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000591 getIntPtrConstant(TySize));
592
593 // Handle alignment. If the requested alignment is less than or equal to the
594 // stack alignment, ignore it and round the size of the allocation up to the
595 // stack alignment size. If the size is greater than the stack alignment, we
596 // note this in the DYNAMIC_STACKALLOC node.
597 unsigned StackAlign =
598 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
599 if (Align <= StackAlign) {
600 Align = 0;
601 // Add SA-1 to the size.
602 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
603 getIntPtrConstant(StackAlign-1));
604 // Mask out the low bits for alignment purposes.
605 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
606 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
607 }
608
609 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattnera651cf62005-01-17 19:43:36 +0000610 getRoot(), AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000611 getIntPtrConstant(Align));
612 DAG.setRoot(setValue(&I, DSA).getValue(1));
613
614 // Inform the Frame Information that we have just allocated a variable-sized
615 // object.
616 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
617}
618
619
620void SelectionDAGLowering::visitLoad(LoadInst &I) {
621 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000622
Chris Lattnerd3948112005-01-17 22:19:26 +0000623 SDOperand Root;
624 if (I.isVolatile())
625 Root = getRoot();
626 else {
627 // Do not serialize non-volatile loads against each other.
628 Root = DAG.getRoot();
629 }
630
Chris Lattner369e6db2005-05-09 04:08:33 +0000631 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Chris Lattnerfd414a22005-05-09 04:28:51 +0000632 DAG.getSrcValue(I.getOperand(0)));
Chris Lattnerd3948112005-01-17 22:19:26 +0000633 setValue(&I, L);
634
635 if (I.isVolatile())
636 DAG.setRoot(L.getValue(1));
637 else
638 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000639}
640
641
642void SelectionDAGLowering::visitStore(StoreInst &I) {
643 Value *SrcV = I.getOperand(0);
644 SDOperand Src = getValue(SrcV);
645 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000646 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Chris Lattnerfd414a22005-05-09 04:28:51 +0000647 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000648}
649
650void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +0000651 const char *RenameFn = 0;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000652 SDOperand Tmp;
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 if (Function *F = I.getCalledFunction())
Chris Lattnerc0f18152005-04-02 05:26:53 +0000654 if (F->isExternal())
655 switch (F->getIntrinsicID()) {
656 case 0: // Not an LLVM intrinsic.
657 if (F->getName() == "fabs" || F->getName() == "fabsf") {
658 if (I.getNumOperands() == 2 && // Basic sanity checks.
659 I.getOperand(1)->getType()->isFloatingPoint() &&
660 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000661 Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000662 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
663 return;
664 }
665 }
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000666 else if (F->getName() == "sin" || F->getName() == "sinf") {
667 if (I.getNumOperands() == 2 && // Basic sanity checks.
668 I.getOperand(1)->getType()->isFloatingPoint() &&
669 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000670 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000671 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
672 return;
673 }
674 }
675 else if (F->getName() == "cos" || F->getName() == "cosf") {
676 if (I.getNumOperands() == 2 && // Basic sanity checks.
677 I.getOperand(1)->getType()->isFloatingPoint() &&
678 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000679 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000680 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
681 return;
682 }
683 }
Chris Lattnerc0f18152005-04-02 05:26:53 +0000684 break;
685 case Intrinsic::vastart: visitVAStart(I); return;
686 case Intrinsic::vaend: visitVAEnd(I); return;
687 case Intrinsic::vacopy: visitVACopy(I); return;
688 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
689 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000690
Chris Lattnerc0f18152005-04-02 05:26:53 +0000691 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
692 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
693 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
694 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
695 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000696
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000697 case Intrinsic::readport:
698 case Intrinsic::readio:
699 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
700 ISD::READPORT : ISD::READIO,
701 TLI.getValueType(I.getType()), getRoot(),
702 getValue(I.getOperand(1)));
703 setValue(&I, Tmp);
704 DAG.setRoot(Tmp.getValue(1));
705 return;
706 case Intrinsic::writeport:
707 case Intrinsic::writeio:
708 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
709 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
710 getRoot(), getValue(I.getOperand(1)),
711 getValue(I.getOperand(2))));
712 return;
Chris Lattner7ea0ade2005-05-05 17:55:17 +0000713 case Intrinsic::dbg_stoppoint:
714 case Intrinsic::dbg_region_start:
715 case Intrinsic::dbg_region_end:
716 case Intrinsic::dbg_func_start:
717 case Intrinsic::dbg_declare:
718 if (I.getType() != Type::VoidTy)
719 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
720 return;
721
Chris Lattnerc0f18152005-04-02 05:26:53 +0000722 case Intrinsic::isunordered:
723 setValue(&I, DAG.getSetCC(ISD::SETUO, MVT::i1,getValue(I.getOperand(1)),
724 getValue(I.getOperand(2))));
725 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000726
727 case Intrinsic::sqrt:
728 setValue(&I, DAG.getNode(ISD::FSQRT,
729 getValue(I.getOperand(1)).getValueType(),
730 getValue(I.getOperand(1))));
731 return;
732
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000733 case Intrinsic::pcmarker:
734 Tmp = getValue(I.getOperand(1));
735 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000736 return;
Andrew Lenharth691ef2b2005-05-03 17:19:30 +0000737 case Intrinsic::cttz:
738 setValue(&I, DAG.getNode(ISD::CTTZ,
739 getValue(I.getOperand(1)).getValueType(),
740 getValue(I.getOperand(1))));
741 return;
742 case Intrinsic::ctlz:
743 setValue(&I, DAG.getNode(ISD::CTLZ,
744 getValue(I.getOperand(1)).getValueType(),
745 getValue(I.getOperand(1))));
746 return;
747 case Intrinsic::ctpop:
748 setValue(&I, DAG.getNode(ISD::CTPOP,
749 getValue(I.getOperand(1)).getValueType(),
750 getValue(I.getOperand(1))));
751 return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000752 default:
753 std::cerr << I;
754 assert(0 && "This intrinsic is not implemented yet!");
755 return;
Chris Lattnerc0f18152005-04-02 05:26:53 +0000756 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000757
Chris Lattner64e14b12005-01-08 22:48:57 +0000758 SDOperand Callee;
759 if (!RenameFn)
760 Callee = getValue(I.getOperand(0));
761 else
762 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +0000763 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000764
Chris Lattner1c08c712005-01-07 07:47:53 +0000765 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
766 Value *Arg = I.getOperand(i);
767 SDOperand ArgNode = getValue(Arg);
768 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
769 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000770
Nate Begeman8e21e712005-03-26 01:29:23 +0000771 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
772 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000773
Chris Lattnercf5734d2005-01-08 19:26:18 +0000774 std::pair<SDOperand,SDOperand> Result =
Nate Begeman8e21e712005-03-26 01:29:23 +0000775 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +0000776 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +0000777 setValue(&I, Result.first);
778 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000779}
780
781void SelectionDAGLowering::visitMalloc(MallocInst &I) {
782 SDOperand Src = getValue(I.getOperand(0));
783
784 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +0000785
786 if (IntPtr < Src.getValueType())
787 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
788 else if (IntPtr > Src.getValueType())
789 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +0000790
791 // Scale the source by the type size.
792 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
793 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
794 Src, getIntPtrConstant(ElementSize));
795
796 std::vector<std::pair<SDOperand, const Type*> > Args;
797 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +0000798
799 std::pair<SDOperand,SDOperand> Result =
Misha Brukmanedf128a2005-04-21 22:36:52 +0000800 TLI.LowerCallTo(getRoot(), I.getType(), false,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000801 DAG.getExternalSymbol("malloc", IntPtr),
802 Args, DAG);
803 setValue(&I, Result.first); // Pointers always fit in registers
804 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000805}
806
807void SelectionDAGLowering::visitFree(FreeInst &I) {
808 std::vector<std::pair<SDOperand, const Type*> > Args;
809 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
810 TLI.getTargetData().getIntPtrType()));
811 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +0000812 std::pair<SDOperand,SDOperand> Result =
Nate Begeman8e21e712005-03-26 01:29:23 +0000813 TLI.LowerCallTo(getRoot(), Type::VoidTy, false,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000814 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
815 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000816}
817
Chris Lattner39ae3622005-01-09 00:00:49 +0000818std::pair<SDOperand, SDOperand>
819TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000820 // We have no sane default behavior, just emit a useful error message and bail
821 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +0000822 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000823 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000824 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner1c08c712005-01-07 07:47:53 +0000825}
826
Chris Lattner39ae3622005-01-09 00:00:49 +0000827SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
828 SelectionDAG &DAG) {
829 // Default to a noop.
830 return Chain;
831}
832
833std::pair<SDOperand,SDOperand>
834TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
835 // Default to returning the input list.
836 return std::make_pair(L, Chain);
837}
838
839std::pair<SDOperand,SDOperand>
840TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
841 const Type *ArgTy, SelectionDAG &DAG) {
842 // We have no sane default behavior, just emit a useful error message and bail
843 // out.
844 std::cerr << "Variable arguments handling not implemented on this target!\n";
845 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000846 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +0000847}
848
849
850void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000851 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000852 setValue(&I, Result.first);
853 DAG.setRoot(Result.second);
854}
855
856void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
857 std::pair<SDOperand,SDOperand> Result =
Misha Brukmanedf128a2005-04-21 22:36:52 +0000858 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000859 I.getType(), DAG);
860 setValue(&I, Result.first);
861 DAG.setRoot(Result.second);
862}
863
Chris Lattner1c08c712005-01-07 07:47:53 +0000864void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000865 std::pair<SDOperand,SDOperand> Result =
Misha Brukmanedf128a2005-04-21 22:36:52 +0000866 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000867 I.getArgType(), DAG);
868 setValue(&I, Result.first);
869 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000870}
871
872void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000873 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000874}
875
876void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000877 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000878 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000879 setValue(&I, Result.first);
880 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000881}
882
Chris Lattner39ae3622005-01-09 00:00:49 +0000883
884// It is always conservatively correct for llvm.returnaddress and
885// llvm.frameaddress to return 0.
886std::pair<SDOperand, SDOperand>
887TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
888 unsigned Depth, SelectionDAG &DAG) {
889 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +0000890}
891
Chris Lattner171453a2005-01-16 07:28:41 +0000892SDOperand TargetLowering::LowerOperation(SDOperand Op) {
893 assert(0 && "LowerOperation not implemented for this target!");
894 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000895 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +0000896}
897
Chris Lattner39ae3622005-01-09 00:00:49 +0000898void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
899 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
900 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000901 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000902 setValue(&I, Result.first);
903 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000904}
905
Chris Lattner7041ee32005-01-11 05:56:49 +0000906void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
907 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +0000908 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +0000909 Ops.push_back(getValue(I.getOperand(1)));
910 Ops.push_back(getValue(I.getOperand(2)));
911 Ops.push_back(getValue(I.getOperand(3)));
912 Ops.push_back(getValue(I.getOperand(4)));
913 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000914}
915
Chris Lattner7041ee32005-01-11 05:56:49 +0000916//===----------------------------------------------------------------------===//
917// SelectionDAGISel code
918//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000919
920unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
921 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
922}
923
924
925
926bool SelectionDAGISel::runOnFunction(Function &Fn) {
927 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
928 RegMap = MF.getSSARegMap();
929 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
930
931 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
932
933 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
934 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000935
Chris Lattner1c08c712005-01-07 07:47:53 +0000936 return true;
937}
938
939
Chris Lattnerddb870b2005-01-13 17:59:43 +0000940SDOperand SelectionDAGISel::
941CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000942 SelectionDAG &DAG = SDL.DAG;
Chris Lattnerf1fdaca2005-01-11 22:03:46 +0000943 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +0000944 assert((Op.getOpcode() != ISD::CopyFromReg ||
945 cast<RegSDNode>(Op)->getReg() != Reg) &&
946 "Copy from a reg to the same reg!");
Chris Lattnera651cf62005-01-17 19:43:36 +0000947 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner1c08c712005-01-07 07:47:53 +0000948}
949
Chris Lattner0afa8e32005-01-17 17:55:19 +0000950/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
951/// single basic block, return that block. Otherwise, return a null pointer.
952static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
953 if (A->use_empty()) return 0;
954 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
955 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
956 ++UI)
957 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
958 return 0; // Disagreement among the users?
Chris Lattneraa781b32005-02-17 19:40:32 +0000959
960 // Okay, there is a single BB user. Only permit this optimization if this is
961 // the entry block, otherwise, we might sink argument loads into loops and
962 // stuff. Later, when we have global instruction selection, this won't be an
963 // issue clearly.
964 if (BB == BB->getParent()->begin())
965 return BB;
966 return 0;
Chris Lattner0afa8e32005-01-17 17:55:19 +0000967}
968
Chris Lattner068a81e2005-01-17 17:15:02 +0000969void SelectionDAGISel::
970LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
971 std::vector<SDOperand> &UnorderedChains) {
972 // If this is the entry block, emit arguments.
973 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +0000974 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner068a81e2005-01-17 17:15:02 +0000975
976 if (BB == &F.front()) {
Chris Lattner0afa8e32005-01-17 17:55:19 +0000977 SDOperand OldRoot = SDL.DAG.getRoot();
978
Chris Lattner068a81e2005-01-17 17:15:02 +0000979 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
980
Chris Lattner0afa8e32005-01-17 17:55:19 +0000981 // If there were side effects accessing the argument list, do not do
982 // anything special.
983 if (OldRoot != SDL.DAG.getRoot()) {
984 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +0000985 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
986 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +0000987 if (!AI->use_empty()) {
988 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000989 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +0000990 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
991 UnorderedChains.push_back(Copy);
992 }
993 } else {
994 // Otherwise, if any argument is only accessed in a single basic block,
995 // emit that argument only to that basic block.
996 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +0000997 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
998 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +0000999 if (!AI->use_empty()) {
1000 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1001 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1002 std::make_pair(AI, a)));
1003 } else {
1004 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001005 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +00001006 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1007 UnorderedChains.push_back(Copy);
1008 }
1009 }
1010 }
1011 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001012
Chris Lattner0afa8e32005-01-17 17:55:19 +00001013 // See if there are any block-local arguments that need to be emitted in this
1014 // block.
1015
1016 if (!FuncInfo.BlockLocalArguments.empty()) {
1017 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1018 FuncInfo.BlockLocalArguments.lower_bound(BB);
1019 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1020 // Lower the arguments into this block.
1021 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001022
Chris Lattner0afa8e32005-01-17 17:55:19 +00001023 // Set up the value mapping for the local arguments.
1024 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1025 ++BLAI)
1026 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001027
Chris Lattner0afa8e32005-01-17 17:55:19 +00001028 // Any dead arguments will just be ignored here.
1029 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001030 }
1031}
1032
1033
Chris Lattner1c08c712005-01-07 07:47:53 +00001034void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1035 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1036 FunctionLoweringInfo &FuncInfo) {
1037 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001038
1039 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001040
Chris Lattner068a81e2005-01-17 17:15:02 +00001041 // Lower any arguments needed in this block.
1042 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001043
1044 BB = FuncInfo.MBBMap[LLVMBB];
1045 SDL.setCurrentBasicBlock(BB);
1046
1047 // Lower all of the non-terminator instructions.
1048 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1049 I != E; ++I)
1050 SDL.visit(*I);
1051
1052 // Ensure that all instructions which are used outside of their defining
1053 // blocks are available as virtual registers.
1054 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001055 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001056 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001057 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001058 UnorderedChains.push_back(
1059 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001060 }
1061
1062 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1063 // ensure constants are generated when needed. Remember the virtual registers
1064 // that need to be added to the Machine PHI nodes as input. We cannot just
1065 // directly add them, because expansion might result in multiple MBB's for one
1066 // BB. As such, the start of the BB might correspond to a different MBB than
1067 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001068 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001069
1070 // Emit constants only once even if used by multiple PHI nodes.
1071 std::map<Constant*, unsigned> ConstantsOut;
1072
1073 // Check successor nodes PHI nodes that expect a constant to be available from
1074 // this block.
1075 TerminatorInst *TI = LLVMBB->getTerminator();
1076 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1077 BasicBlock *SuccBB = TI->getSuccessor(succ);
1078 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1079 PHINode *PN;
1080
1081 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1082 // nodes and Machine PHI nodes, but the incoming operands have not been
1083 // emitted yet.
1084 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001085 (PN = dyn_cast<PHINode>(I)); ++I)
1086 if (!PN->use_empty()) {
1087 unsigned Reg;
1088 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1089 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1090 unsigned &RegOut = ConstantsOut[C];
1091 if (RegOut == 0) {
1092 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001093 UnorderedChains.push_back(
1094 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001095 }
1096 Reg = RegOut;
1097 } else {
1098 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001099 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001100 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001101 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1102 "Didn't codegen value into a register!??");
1103 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001104 UnorderedChains.push_back(
1105 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001106 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001107 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001108
Chris Lattnerf44fd882005-01-07 21:34:19 +00001109 // Remember that this register needs to added to the machine PHI node as
1110 // the input for this MBB.
1111 unsigned NumElements =
1112 TLI.getNumElements(TLI.getValueType(PN->getType()));
1113 for (unsigned i = 0, e = NumElements; i != e; ++i)
1114 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001115 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001116 }
1117 ConstantsOut.clear();
1118
Chris Lattnerddb870b2005-01-13 17:59:43 +00001119 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001120 if (!UnorderedChains.empty()) {
Chris Lattnerd3948112005-01-17 22:19:26 +00001121 UnorderedChains.push_back(SDL.getRoot());
Chris Lattnerddb870b2005-01-13 17:59:43 +00001122 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1123 }
1124
Chris Lattner1c08c712005-01-07 07:47:53 +00001125 // Lower the terminator after the copies are emitted.
1126 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001127
1128 // Make sure the root of the DAG is up-to-date.
1129 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001130}
1131
1132void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1133 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001134 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001135 CurDAG = &DAG;
1136 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1137
1138 // First step, lower LLVM code to some DAG. This DAG may use operations and
1139 // types that are not supported by the target.
1140 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1141
1142 DEBUG(std::cerr << "Lowered selection DAG:\n");
1143 DEBUG(DAG.dump());
1144
1145 // Second step, hack on the DAG until it only uses operations and types that
1146 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001147 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001148
1149 DEBUG(std::cerr << "Legalized selection DAG:\n");
1150 DEBUG(DAG.dump());
1151
Chris Lattnera33ef482005-03-30 01:10:47 +00001152 // Third, instruction select all of the operations to machine code, adding the
1153 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001154 InstructionSelectBasicBlock(DAG);
1155
Chris Lattner7944d9d2005-01-12 03:41:21 +00001156 if (ViewDAGs) DAG.viewGraph();
1157
Chris Lattner1c08c712005-01-07 07:47:53 +00001158 DEBUG(std::cerr << "Selected machine code:\n");
1159 DEBUG(BB->dump());
1160
Chris Lattnera33ef482005-03-30 01:10:47 +00001161 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001162 // PHI nodes in successors.
1163 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1164 MachineInstr *PHI = PHINodesToUpdate[i].first;
1165 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1166 "This is not a machine PHI node that we are updating!");
1167 PHI->addRegOperand(PHINodesToUpdate[i].second);
1168 PHI->addMachineBasicBlockOperand(BB);
1169 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001170
1171 // Finally, add the CFG edges from the last selected MBB to the successor
1172 // MBBs.
1173 TerminatorInst *TI = LLVMBB->getTerminator();
1174 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1175 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1176 BB->addSuccessor(Succ0MBB);
1177 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001178}