blob: e088845daa8845344041c77406134365a7b623ce [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-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"
Chris Lattner2e77db62005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/SelectionDAG.h"
26#include "llvm/CodeGen/SSARegMap.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetFrameInfo.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetLowering.h"
31#include "llvm/Target/TargetMachine.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000032#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Support/Debug.h"
34#include <map>
35#include <iostream>
36using namespace llvm;
37
Chris Lattnere05a4612005-01-12 03:41:21 +000038#ifndef _NDEBUG
39static cl::opt<bool>
40ViewDAGs("view-isel-dags", cl::Hidden,
41 cl::desc("Pop up a window to show isel dags as they are selected"));
42#else
43static const bool ViewDAGS = 0;
44#endif
45
Chris Lattner7a60d912005-01-07 07:47:53 +000046namespace llvm {
47 //===--------------------------------------------------------------------===//
48 /// FunctionLoweringInfo - This contains information that is global to a
49 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000050 class FunctionLoweringInfo {
51 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000052 TargetLowering &TLI;
53 Function &Fn;
54 MachineFunction &MF;
55 SSARegMap *RegMap;
56
57 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
58
59 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
60 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
61
62 /// ValueMap - Since we emit code for the function a basic block at a time,
63 /// we must remember which virtual registers hold the values for
64 /// cross-basic-block values.
65 std::map<const Value*, unsigned> ValueMap;
66
67 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
68 /// the entry block. This allows the allocas to be efficiently referenced
69 /// anywhere in the function.
70 std::map<const AllocaInst*, int> StaticAllocaMap;
71
Chris Lattnere3c2cf42005-01-17 17:55:19 +000072 /// BlockLocalArguments - If any arguments are only used in a single basic
73 /// block, and if the target can access the arguments without side-effects,
74 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
75 /// track of which arguments are local to each BB.
76 std::multimap<BasicBlock*, std::pair<Argument*,
77 unsigned> > BlockLocalArguments;
78
79
Chris Lattner7a60d912005-01-07 07:47:53 +000080 unsigned MakeReg(MVT::ValueType VT) {
81 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
82 }
Misha Brukman835702a2005-04-21 22:36:52 +000083
Chris Lattner7a60d912005-01-07 07:47:53 +000084 unsigned CreateRegForValue(const Value *V) {
85 MVT::ValueType VT = TLI.getValueType(V->getType());
86 // The common case is that we will only create one register for this
87 // value. If we have that case, create and return the virtual register.
88 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000089 if (NV == 1) {
90 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000091 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000092 }
Misha Brukman835702a2005-04-21 22:36:52 +000093
Chris Lattner7a60d912005-01-07 07:47:53 +000094 // If this value is represented with multiple target registers, make sure
95 // to create enough consequtive registers of the right (smaller) type.
96 unsigned NT = VT-1; // Find the type to use.
97 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
98 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000099
Chris Lattner7a60d912005-01-07 07:47:53 +0000100 unsigned R = MakeReg((MVT::ValueType)NT);
101 for (unsigned i = 1; i != NV; ++i)
102 MakeReg((MVT::ValueType)NT);
103 return R;
104 }
Misha Brukman835702a2005-04-21 22:36:52 +0000105
Chris Lattner7a60d912005-01-07 07:47:53 +0000106 unsigned InitializeRegForValue(const Value *V) {
107 unsigned &R = ValueMap[V];
108 assert(R == 0 && "Already initialized this value register!");
109 return R = CreateRegForValue(V);
110 }
111 };
112}
113
114/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
115/// PHI nodes or outside of the basic block that defines it.
116static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
117 if (isa<PHINode>(I)) return true;
118 BasicBlock *BB = I->getParent();
119 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
120 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
121 return true;
122 return false;
123}
124
125FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000126 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000127 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
128
129 // Initialize the mapping of values to registers. This is only set up for
130 // instruction values that are used outside of the block that defines
131 // them.
Chris Lattner490769c2005-05-11 18:57:06 +0000132 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
133 AI != E; ++AI)
Chris Lattner7a60d912005-01-07 07:47:53 +0000134 InitializeRegForValue(AI);
135
136 Function::iterator BB = Fn.begin(), E = Fn.end();
137 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
138 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
139 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
140 const Type *Ty = AI->getAllocatedType();
141 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
142 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
143 TySize *= CUI->getValue(); // Get total allocated size.
144 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000145 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000146 }
147
148 for (; BB != E; ++BB)
Chris Lattnerd0061952005-01-08 19:52:31 +0000149 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
151 if (!isa<AllocaInst>(I) ||
152 !StaticAllocaMap.count(cast<AllocaInst>(I)))
153 InitializeRegForValue(I);
154
155 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
156 // also creates the initial PHI MachineInstrs, though none of the input
157 // operands are populated.
158 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
159 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
160 MBBMap[BB] = MBB;
161 MF.getBasicBlockList().push_back(MBB);
162
163 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
164 // appropriate.
165 PHINode *PN;
166 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000167 (PN = dyn_cast<PHINode>(I)); ++I)
168 if (!PN->use_empty()) {
169 unsigned NumElements =
170 TLI.getNumElements(TLI.getValueType(PN->getType()));
171 unsigned PHIReg = ValueMap[PN];
172 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
173 for (unsigned i = 0; i != NumElements; ++i)
174 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
175 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 }
177}
178
179
180
181//===----------------------------------------------------------------------===//
182/// SelectionDAGLowering - This is the common target-independent lowering
183/// implementation that is parameterized by a TargetLowering object.
184/// Also, targets can overload any lowering method.
185///
186namespace llvm {
187class SelectionDAGLowering {
188 MachineBasicBlock *CurMBB;
189
190 std::map<const Value*, SDOperand> NodeMap;
191
Chris Lattner4d9651c2005-01-17 22:19:26 +0000192 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
193 /// them up and then emit token factor nodes when possible. This allows us to
194 /// get simple disambiguation between loads without worrying about alias
195 /// analysis.
196 std::vector<SDOperand> PendingLoads;
197
Chris Lattner7a60d912005-01-07 07:47:53 +0000198public:
199 // TLI - This is information that describes the available target features we
200 // need for lowering. This indicates when operations are unavailable,
201 // implemented with a libcall, etc.
202 TargetLowering &TLI;
203 SelectionDAG &DAG;
204 const TargetData &TD;
205
206 /// FuncInfo - Information about the function as a whole.
207 ///
208 FunctionLoweringInfo &FuncInfo;
209
210 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000211 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000212 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
213 FuncInfo(funcinfo) {
214 }
215
Chris Lattner4108bb02005-01-17 19:43:36 +0000216 /// getRoot - Return the current virtual root of the Selection DAG.
217 ///
218 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000219 if (PendingLoads.empty())
220 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000221
Chris Lattner4d9651c2005-01-17 22:19:26 +0000222 if (PendingLoads.size() == 1) {
223 SDOperand Root = PendingLoads[0];
224 DAG.setRoot(Root);
225 PendingLoads.clear();
226 return Root;
227 }
228
229 // Otherwise, we have to make a token factor node.
230 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
231 PendingLoads.clear();
232 DAG.setRoot(Root);
233 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000234 }
235
Chris Lattner7a60d912005-01-07 07:47:53 +0000236 void visit(Instruction &I) { visit(I.getOpcode(), I); }
237
238 void visit(unsigned Opcode, User &I) {
239 switch (Opcode) {
240 default: assert(0 && "Unknown instruction type encountered!");
241 abort();
242 // Build the switch statement using the Instruction.def file.
243#define HANDLE_INST(NUM, OPCODE, CLASS) \
244 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
245#include "llvm/Instruction.def"
246 }
247 }
248
249 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
250
251
252 SDOperand getIntPtrConstant(uint64_t Val) {
253 return DAG.getConstant(Val, TLI.getPointerTy());
254 }
255
256 SDOperand getValue(const Value *V) {
257 SDOperand &N = NodeMap[V];
258 if (N.Val) return N;
259
260 MVT::ValueType VT = TLI.getValueType(V->getType());
261 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
262 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
263 visit(CE->getOpcode(), *CE);
264 assert(N.Val && "visit didn't populate the ValueMap!");
265 return N;
266 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
267 return N = DAG.getGlobalAddress(GV, VT);
268 } else if (isa<ConstantPointerNull>(C)) {
269 return N = DAG.getConstant(0, TLI.getPointerTy());
270 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000271 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000272 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
273 return N = DAG.getConstantFP(CFP->getValue(), VT);
274 } else {
275 // Canonicalize all constant ints to be unsigned.
276 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
277 }
278
279 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
280 std::map<const AllocaInst*, int>::iterator SI =
281 FuncInfo.StaticAllocaMap.find(AI);
282 if (SI != FuncInfo.StaticAllocaMap.end())
283 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
284 }
285
286 std::map<const Value*, unsigned>::const_iterator VMI =
287 FuncInfo.ValueMap.find(V);
288 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000289
Chris Lattner9f2c4a52005-01-18 17:54:55 +0000290 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode());
Chris Lattner7a60d912005-01-07 07:47:53 +0000291 }
292
293 const SDOperand &setValue(const Value *V, SDOperand NewN) {
294 SDOperand &N = NodeMap[V];
295 assert(N.Val == 0 && "Already set a value for this node!");
296 return N = NewN;
297 }
298
299 // Terminator instructions.
300 void visitRet(ReturnInst &I);
301 void visitBr(BranchInst &I);
302 void visitUnreachable(UnreachableInst &I) { /* noop */ }
303
304 // These all get lowered before this pass.
305 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
306 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
307 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
308
309 //
310 void visitBinary(User &I, unsigned Opcode);
311 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000312 void visitSub(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000313 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
314 void visitDiv(User &I) {
315 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
316 }
317 void visitRem(User &I) {
318 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
319 }
320 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
321 void visitOr (User &I) { visitBinary(I, ISD::OR); }
322 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
323 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
324 void visitShr(User &I) {
325 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
326 }
327
328 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
329 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
330 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
331 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
332 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
333 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
334 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
335
336 void visitGetElementPtr(User &I);
337 void visitCast(User &I);
338 void visitSelect(User &I);
339 //
340
341 void visitMalloc(MallocInst &I);
342 void visitFree(FreeInst &I);
343 void visitAlloca(AllocaInst &I);
344 void visitLoad(LoadInst &I);
345 void visitStore(StoreInst &I);
346 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
347 void visitCall(CallInst &I);
348
Chris Lattner7a60d912005-01-07 07:47:53 +0000349 void visitVAStart(CallInst &I);
350 void visitVANext(VANextInst &I);
351 void visitVAArg(VAArgInst &I);
352 void visitVAEnd(CallInst &I);
353 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000354 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000355
Chris Lattner875def92005-01-11 05:56:49 +0000356 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000357
358 void visitUserOp1(Instruction &I) {
359 assert(0 && "UserOp1 should not exist at instruction selection time!");
360 abort();
361 }
362 void visitUserOp2(Instruction &I) {
363 assert(0 && "UserOp2 should not exist at instruction selection time!");
364 abort();
365 }
366};
367} // end namespace llvm
368
369void SelectionDAGLowering::visitRet(ReturnInst &I) {
370 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000371 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000372 return;
373 }
374
375 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000376 MVT::ValueType TmpVT;
377
Chris Lattner7a60d912005-01-07 07:47:53 +0000378 switch (Op1.getValueType()) {
379 default: assert(0 && "Unknown value type!");
380 case MVT::i1:
381 case MVT::i8:
382 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000383 case MVT::i32:
384 // If this is a machine where 32-bits is legal or expanded, promote to
385 // 32-bits, otherwise, promote to 64-bits.
386 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
387 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000388 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000389 TmpVT = MVT::i32;
390
391 // Extend integer types to result type.
392 if (I.getOperand(0)->getType()->isSigned())
393 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
394 else
395 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000396 break;
397 case MVT::f32:
398 // Extend float to double.
399 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
400 break;
Chris Lattner7a60d912005-01-07 07:47:53 +0000401 case MVT::i64:
402 case MVT::f64:
403 break; // No extension needed!
404 }
405
Chris Lattner4108bb02005-01-17 19:43:36 +0000406 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000407}
408
409void SelectionDAGLowering::visitBr(BranchInst &I) {
410 // Update machine-CFG edges.
411 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000412
413 // Figure out which block is immediately after the current one.
414 MachineBasicBlock *NextBlock = 0;
415 MachineFunction::iterator BBI = CurMBB;
416 if (++BBI != CurMBB->getParent()->end())
417 NextBlock = BBI;
418
419 if (I.isUnconditional()) {
420 // If this is not a fall-through branch, emit the branch.
421 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000422 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000423 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000424 } else {
425 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000426
427 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 if (Succ1MBB == NextBlock) {
429 // If the condition is false, fall through. This means we should branch
430 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000431 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000432 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 } else if (Succ0MBB == NextBlock) {
434 // If the condition is true, fall through. This means we should branch if
435 // the condition is false to Succ #1. Invert the condition first.
436 SDOperand True = DAG.getConstant(1, Cond.getValueType());
437 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000438 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000439 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000441 std::vector<SDOperand> Ops;
442 Ops.push_back(getRoot());
443 Ops.push_back(Cond);
444 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
445 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
446 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000447 }
448 }
449}
450
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000451void SelectionDAGLowering::visitSub(User &I) {
452 // -0.0 - X --> fneg
453 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
454 if (CFP->isExactlyValue(-0.0)) {
455 SDOperand Op2 = getValue(I.getOperand(1));
456 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
457 return;
458 }
459
460 visitBinary(I, ISD::SUB);
461}
462
Chris Lattner7a60d912005-01-07 07:47:53 +0000463void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
464 SDOperand Op1 = getValue(I.getOperand(0));
465 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000466
467 if (isa<ShiftInst>(I))
468 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2);
469
Chris Lattner7a60d912005-01-07 07:47:53 +0000470 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
471}
472
473void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
474 ISD::CondCode UnsignedOpcode) {
475 SDOperand Op1 = getValue(I.getOperand(0));
476 SDOperand Op2 = getValue(I.getOperand(1));
477 ISD::CondCode Opcode = SignedOpcode;
478 if (I.getOperand(0)->getType()->isUnsigned())
479 Opcode = UnsignedOpcode;
Chris Lattnerb07e2d22005-01-18 02:52:03 +0000480 setValue(&I, DAG.getSetCC(Opcode, MVT::i1, Op1, Op2));
Chris Lattner7a60d912005-01-07 07:47:53 +0000481}
482
483void SelectionDAGLowering::visitSelect(User &I) {
484 SDOperand Cond = getValue(I.getOperand(0));
485 SDOperand TrueVal = getValue(I.getOperand(1));
486 SDOperand FalseVal = getValue(I.getOperand(2));
487 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
488 TrueVal, FalseVal));
489}
490
491void SelectionDAGLowering::visitCast(User &I) {
492 SDOperand N = getValue(I.getOperand(0));
493 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
494 MVT::ValueType DestTy = TLI.getValueType(I.getType());
495
496 if (N.getValueType() == DestTy) {
497 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000498 } else if (DestTy == MVT::i1) {
499 // Cast to bool is a comparison against zero, not truncation to zero.
500 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
501 DAG.getConstantFP(0.0, N.getValueType());
502 setValue(&I, DAG.getSetCC(ISD::SETNE, MVT::i1, N, Zero));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000503 } else if (isInteger(SrcTy)) {
504 if (isInteger(DestTy)) { // Int -> Int cast
505 if (DestTy < SrcTy) // Truncating cast?
506 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
507 else if (I.getOperand(0)->getType()->isSigned())
508 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
509 else
510 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
511 } else { // Int -> FP cast
512 if (I.getOperand(0)->getType()->isSigned())
513 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
514 else
515 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
516 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000517 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000518 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
519 if (isFloatingPoint(DestTy)) { // FP -> FP cast
520 if (DestTy < SrcTy) // Rounding cast?
521 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
522 else
523 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
524 } else { // FP -> Int cast.
525 if (I.getType()->isSigned())
526 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
527 else
528 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
529 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000530 }
531}
532
533void SelectionDAGLowering::visitGetElementPtr(User &I) {
534 SDOperand N = getValue(I.getOperand(0));
535 const Type *Ty = I.getOperand(0)->getType();
536 const Type *UIntPtrTy = TD.getIntPtrType();
537
538 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
539 OI != E; ++OI) {
540 Value *Idx = *OI;
541 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
542 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
543 if (Field) {
544 // N = N + Offset
545 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
546 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000547 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 }
549 Ty = StTy->getElementType(Field);
550 } else {
551 Ty = cast<SequentialType>(Ty)->getElementType();
552 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
553 // N = N + Idx * ElementSize;
554 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000555 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
556
557 // If the index is smaller or larger than intptr_t, truncate or extend
558 // it.
559 if (IdxN.getValueType() < Scale.getValueType()) {
560 if (Idx->getType()->isSigned())
561 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
562 else
563 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
564 } else if (IdxN.getValueType() > Scale.getValueType())
565 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
566
567 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
569 }
570 }
571 }
572 setValue(&I, N);
573}
574
575void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
576 // If this is a fixed sized alloca in the entry block of the function,
577 // allocate it statically on the stack.
578 if (FuncInfo.StaticAllocaMap.count(&I))
579 return; // getValue will auto-populate this.
580
581 const Type *Ty = I.getAllocatedType();
582 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
583 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
584
585 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000586 MVT::ValueType IntPtr = TLI.getPointerTy();
587 if (IntPtr < AllocSize.getValueType())
588 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
589 else if (IntPtr > AllocSize.getValueType())
590 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000591
Chris Lattnereccb73d2005-01-22 23:04:37 +0000592 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000593 getIntPtrConstant(TySize));
594
595 // Handle alignment. If the requested alignment is less than or equal to the
596 // stack alignment, ignore it and round the size of the allocation up to the
597 // stack alignment size. If the size is greater than the stack alignment, we
598 // note this in the DYNAMIC_STACKALLOC node.
599 unsigned StackAlign =
600 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
601 if (Align <= StackAlign) {
602 Align = 0;
603 // Add SA-1 to the size.
604 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
605 getIntPtrConstant(StackAlign-1));
606 // Mask out the low bits for alignment purposes.
607 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
608 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
609 }
610
611 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, AllocSize.getValueType(),
Chris Lattner4108bb02005-01-17 19:43:36 +0000612 getRoot(), AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000613 getIntPtrConstant(Align));
614 DAG.setRoot(setValue(&I, DSA).getValue(1));
615
616 // Inform the Frame Information that we have just allocated a variable-sized
617 // object.
618 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
619}
620
621
622void SelectionDAGLowering::visitLoad(LoadInst &I) {
623 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000624
Chris Lattner4d9651c2005-01-17 22:19:26 +0000625 SDOperand Root;
626 if (I.isVolatile())
627 Root = getRoot();
628 else {
629 // Do not serialize non-volatile loads against each other.
630 Root = DAG.getRoot();
631 }
632
Chris Lattnerf5675a02005-05-09 04:08:33 +0000633 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Chris Lattner57d294f2005-05-09 04:28:51 +0000634 DAG.getSrcValue(I.getOperand(0)));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000635 setValue(&I, L);
636
637 if (I.isVolatile())
638 DAG.setRoot(L.getValue(1));
639 else
640 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000641}
642
643
644void SelectionDAGLowering::visitStore(StoreInst &I) {
645 Value *SrcV = I.getOperand(0);
646 SDOperand Src = getValue(SrcV);
647 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000648 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Chris Lattner57d294f2005-05-09 04:28:51 +0000649 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000650}
651
652void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000653 const char *RenameFn = 0;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000654 SDOperand Tmp;
Chris Lattner7a60d912005-01-07 07:47:53 +0000655 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000656 if (F->isExternal())
657 switch (F->getIntrinsicID()) {
658 case 0: // Not an LLVM intrinsic.
659 if (F->getName() == "fabs" || F->getName() == "fabsf") {
660 if (I.getNumOperands() == 2 && // Basic sanity checks.
661 I.getOperand(1)->getType()->isFloatingPoint() &&
662 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000663 Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000664 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
665 return;
666 }
667 }
Chris Lattner80026402005-04-30 04:43:14 +0000668 else if (F->getName() == "sin" || F->getName() == "sinf") {
669 if (I.getNumOperands() == 2 && // Basic sanity checks.
670 I.getOperand(1)->getType()->isFloatingPoint() &&
671 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000672 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000673 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
674 return;
675 }
676 }
677 else if (F->getName() == "cos" || F->getName() == "cosf") {
678 if (I.getNumOperands() == 2 && // Basic sanity checks.
679 I.getOperand(1)->getType()->isFloatingPoint() &&
680 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000681 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000682 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
683 return;
684 }
685 }
Chris Lattner0c140002005-04-02 05:26:53 +0000686 break;
687 case Intrinsic::vastart: visitVAStart(I); return;
688 case Intrinsic::vaend: visitVAEnd(I); return;
689 case Intrinsic::vacopy: visitVACopy(I); return;
690 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
691 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000692
Chris Lattner0c140002005-04-02 05:26:53 +0000693 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
694 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
695 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
696 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
697 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukman835702a2005-04-21 22:36:52 +0000698
Chris Lattner20eaeae2005-05-09 20:22:36 +0000699 case Intrinsic::readport:
700 case Intrinsic::readio:
701 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
702 ISD::READPORT : ISD::READIO,
703 TLI.getValueType(I.getType()), getRoot(),
704 getValue(I.getOperand(1)));
705 setValue(&I, Tmp);
706 DAG.setRoot(Tmp.getValue(1));
707 return;
708 case Intrinsic::writeport:
709 case Intrinsic::writeio:
710 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
711 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
712 getRoot(), getValue(I.getOperand(1)),
713 getValue(I.getOperand(2))));
714 return;
Chris Lattner78761562005-05-05 17:55:17 +0000715 case Intrinsic::dbg_stoppoint:
716 case Intrinsic::dbg_region_start:
717 case Intrinsic::dbg_region_end:
718 case Intrinsic::dbg_func_start:
719 case Intrinsic::dbg_declare:
720 if (I.getType() != Type::VoidTy)
721 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
722 return;
723
Chris Lattner0c140002005-04-02 05:26:53 +0000724 case Intrinsic::isunordered:
725 setValue(&I, DAG.getSetCC(ISD::SETUO, MVT::i1,getValue(I.getOperand(1)),
726 getValue(I.getOperand(2))));
727 return;
Chris Lattner80026402005-04-30 04:43:14 +0000728
729 case Intrinsic::sqrt:
730 setValue(&I, DAG.getNode(ISD::FSQRT,
731 getValue(I.getOperand(1)).getValueType(),
732 getValue(I.getOperand(1))));
733 return;
734
Chris Lattner20eaeae2005-05-09 20:22:36 +0000735 case Intrinsic::pcmarker:
736 Tmp = getValue(I.getOperand(1));
737 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattner0c140002005-04-02 05:26:53 +0000738 return;
Andrew Lenharth5e177822005-05-03 17:19:30 +0000739 case Intrinsic::cttz:
740 setValue(&I, DAG.getNode(ISD::CTTZ,
741 getValue(I.getOperand(1)).getValueType(),
742 getValue(I.getOperand(1))));
743 return;
744 case Intrinsic::ctlz:
745 setValue(&I, DAG.getNode(ISD::CTLZ,
746 getValue(I.getOperand(1)).getValueType(),
747 getValue(I.getOperand(1))));
748 return;
749 case Intrinsic::ctpop:
750 setValue(&I, DAG.getNode(ISD::CTPOP,
751 getValue(I.getOperand(1)).getValueType(),
752 getValue(I.getOperand(1))));
753 return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000754 default:
755 std::cerr << I;
756 assert(0 && "This intrinsic is not implemented yet!");
757 return;
Chris Lattner0c140002005-04-02 05:26:53 +0000758 }
Misha Brukman835702a2005-04-21 22:36:52 +0000759
Chris Lattner18d2b342005-01-08 22:48:57 +0000760 SDOperand Callee;
761 if (!RenameFn)
762 Callee = getValue(I.getOperand(0));
763 else
764 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000765 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukman835702a2005-04-21 22:36:52 +0000766
Chris Lattner7a60d912005-01-07 07:47:53 +0000767 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
768 Value *Arg = I.getOperand(i);
769 SDOperand ArgNode = getValue(Arg);
770 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
771 }
Misha Brukman835702a2005-04-21 22:36:52 +0000772
Nate Begemanf6565252005-03-26 01:29:23 +0000773 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
774 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000775
Chris Lattner1f45cd72005-01-08 19:26:18 +0000776 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000777 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000778 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000779 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000780 setValue(&I, Result.first);
781 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000782}
783
784void SelectionDAGLowering::visitMalloc(MallocInst &I) {
785 SDOperand Src = getValue(I.getOperand(0));
786
787 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000788
789 if (IntPtr < Src.getValueType())
790 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
791 else if (IntPtr > Src.getValueType())
792 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000793
794 // Scale the source by the type size.
795 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
796 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
797 Src, getIntPtrConstant(ElementSize));
798
799 std::vector<std::pair<SDOperand, const Type*> > Args;
800 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000801
802 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000803 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000804 DAG.getExternalSymbol("malloc", IntPtr),
805 Args, DAG);
806 setValue(&I, Result.first); // Pointers always fit in registers
807 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000808}
809
810void SelectionDAGLowering::visitFree(FreeInst &I) {
811 std::vector<std::pair<SDOperand, const Type*> > Args;
812 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
813 TLI.getTargetData().getIntPtrType()));
814 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000815 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000816 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000817 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
818 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000819}
820
Chris Lattner58cfd792005-01-09 00:00:49 +0000821std::pair<SDOperand, SDOperand>
822TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000823 // We have no sane default behavior, just emit a useful error message and bail
824 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000825 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000826 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000827 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner7a60d912005-01-07 07:47:53 +0000828}
829
Chris Lattner58cfd792005-01-09 00:00:49 +0000830SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
831 SelectionDAG &DAG) {
832 // Default to a noop.
833 return Chain;
834}
835
836std::pair<SDOperand,SDOperand>
837TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
838 // Default to returning the input list.
839 return std::make_pair(L, Chain);
840}
841
842std::pair<SDOperand,SDOperand>
843TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
844 const Type *ArgTy, SelectionDAG &DAG) {
845 // We have no sane default behavior, just emit a useful error message and bail
846 // out.
847 std::cerr << "Variable arguments handling not implemented on this target!\n";
848 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000849 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000850}
851
852
853void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000854 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000855 setValue(&I, Result.first);
856 DAG.setRoot(Result.second);
857}
858
859void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
860 std::pair<SDOperand,SDOperand> Result =
Misha Brukman835702a2005-04-21 22:36:52 +0000861 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000862 I.getType(), DAG);
863 setValue(&I, Result.first);
864 DAG.setRoot(Result.second);
865}
866
Chris Lattner7a60d912005-01-07 07:47:53 +0000867void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000868 std::pair<SDOperand,SDOperand> Result =
Misha Brukman835702a2005-04-21 22:36:52 +0000869 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner58cfd792005-01-09 00:00:49 +0000870 I.getArgType(), DAG);
871 setValue(&I, Result.first);
872 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000873}
874
875void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000876 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000877}
878
879void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000880 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000881 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000882 setValue(&I, Result.first);
883 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000884}
885
Chris Lattner58cfd792005-01-09 00:00:49 +0000886
887// It is always conservatively correct for llvm.returnaddress and
888// llvm.frameaddress to return 0.
889std::pair<SDOperand, SDOperand>
890TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
891 unsigned Depth, SelectionDAG &DAG) {
892 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000893}
894
Chris Lattner897cd7d2005-01-16 07:28:41 +0000895SDOperand TargetLowering::LowerOperation(SDOperand Op) {
896 assert(0 && "LowerOperation not implemented for this target!");
897 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000898 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000899}
900
Chris Lattner58cfd792005-01-09 00:00:49 +0000901void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
902 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
903 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000904 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000905 setValue(&I, Result.first);
906 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000907}
908
Chris Lattner875def92005-01-11 05:56:49 +0000909void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
910 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000911 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000912 Ops.push_back(getValue(I.getOperand(1)));
913 Ops.push_back(getValue(I.getOperand(2)));
914 Ops.push_back(getValue(I.getOperand(3)));
915 Ops.push_back(getValue(I.getOperand(4)));
916 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000917}
918
Chris Lattner875def92005-01-11 05:56:49 +0000919//===----------------------------------------------------------------------===//
920// SelectionDAGISel code
921//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000922
923unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
924 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
925}
926
927
928
929bool SelectionDAGISel::runOnFunction(Function &Fn) {
930 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
931 RegMap = MF.getSSARegMap();
932 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
933
934 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
935
936 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
937 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +0000938
Chris Lattner7a60d912005-01-07 07:47:53 +0000939 return true;
940}
941
942
Chris Lattner718b5c22005-01-13 17:59:43 +0000943SDOperand SelectionDAGISel::
944CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000945 SelectionDAG &DAG = SDL.DAG;
Chris Lattner613f79f2005-01-11 22:03:46 +0000946 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +0000947 assert((Op.getOpcode() != ISD::CopyFromReg ||
948 cast<RegSDNode>(Op)->getReg() != Reg) &&
949 "Copy from a reg to the same reg!");
Chris Lattner4108bb02005-01-17 19:43:36 +0000950 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner7a60d912005-01-07 07:47:53 +0000951}
952
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000953/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
954/// single basic block, return that block. Otherwise, return a null pointer.
955static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
956 if (A->use_empty()) return 0;
957 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
958 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
959 ++UI)
960 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
961 return 0; // Disagreement among the users?
Chris Lattner0c56a542005-02-17 19:40:32 +0000962
963 // Okay, there is a single BB user. Only permit this optimization if this is
964 // the entry block, otherwise, we might sink argument loads into loops and
965 // stuff. Later, when we have global instruction selection, this won't be an
966 // issue clearly.
967 if (BB == BB->getParent()->begin())
968 return BB;
969 return 0;
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000970}
971
Chris Lattner16f64df2005-01-17 17:15:02 +0000972void SelectionDAGISel::
973LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
974 std::vector<SDOperand> &UnorderedChains) {
975 // If this is the entry block, emit arguments.
976 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000977 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +0000978
979 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000980 SDOperand OldRoot = SDL.DAG.getRoot();
981
Chris Lattner16f64df2005-01-17 17:15:02 +0000982 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
983
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000984 // If there were side effects accessing the argument list, do not do
985 // anything special.
986 if (OldRoot != SDL.DAG.getRoot()) {
987 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +0000988 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
989 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000990 if (!AI->use_empty()) {
991 SDL.setValue(AI, Args[a]);
Misha Brukman835702a2005-04-21 22:36:52 +0000992 SDOperand Copy =
Chris Lattnere3c2cf42005-01-17 17:55:19 +0000993 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
994 UnorderedChains.push_back(Copy);
995 }
996 } else {
997 // Otherwise, if any argument is only accessed in a single basic block,
998 // emit that argument only to that basic block.
999 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +00001000 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1001 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001002 if (!AI->use_empty()) {
1003 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1004 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1005 std::make_pair(AI, a)));
1006 } else {
1007 SDL.setValue(AI, Args[a]);
Misha Brukman835702a2005-04-21 22:36:52 +00001008 SDOperand Copy =
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001009 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1010 UnorderedChains.push_back(Copy);
1011 }
1012 }
1013 }
Chris Lattnerd0b0ecc2005-05-13 07:33:32 +00001014
1015 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001016 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001017
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001018 // See if there are any block-local arguments that need to be emitted in this
1019 // block.
1020
1021 if (!FuncInfo.BlockLocalArguments.empty()) {
1022 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1023 FuncInfo.BlockLocalArguments.lower_bound(BB);
1024 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1025 // Lower the arguments into this block.
1026 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukman835702a2005-04-21 22:36:52 +00001027
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001028 // Set up the value mapping for the local arguments.
1029 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1030 ++BLAI)
1031 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukman835702a2005-04-21 22:36:52 +00001032
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001033 // Any dead arguments will just be ignored here.
1034 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001035 }
1036}
1037
1038
Chris Lattner7a60d912005-01-07 07:47:53 +00001039void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1040 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1041 FunctionLoweringInfo &FuncInfo) {
1042 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001043
1044 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001045
Chris Lattner16f64df2005-01-17 17:15:02 +00001046 // Lower any arguments needed in this block.
1047 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001048
1049 BB = FuncInfo.MBBMap[LLVMBB];
1050 SDL.setCurrentBasicBlock(BB);
1051
1052 // Lower all of the non-terminator instructions.
1053 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1054 I != E; ++I)
1055 SDL.visit(*I);
1056
1057 // Ensure that all instructions which are used outside of their defining
1058 // blocks are available as virtual registers.
1059 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001060 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001061 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001062 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001063 UnorderedChains.push_back(
1064 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001065 }
1066
1067 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1068 // ensure constants are generated when needed. Remember the virtual registers
1069 // that need to be added to the Machine PHI nodes as input. We cannot just
1070 // directly add them, because expansion might result in multiple MBB's for one
1071 // BB. As such, the start of the BB might correspond to a different MBB than
1072 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001073 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001074
1075 // Emit constants only once even if used by multiple PHI nodes.
1076 std::map<Constant*, unsigned> ConstantsOut;
1077
1078 // Check successor nodes PHI nodes that expect a constant to be available from
1079 // this block.
1080 TerminatorInst *TI = LLVMBB->getTerminator();
1081 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1082 BasicBlock *SuccBB = TI->getSuccessor(succ);
1083 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1084 PHINode *PN;
1085
1086 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1087 // nodes and Machine PHI nodes, but the incoming operands have not been
1088 // emitted yet.
1089 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001090 (PN = dyn_cast<PHINode>(I)); ++I)
1091 if (!PN->use_empty()) {
1092 unsigned Reg;
1093 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1094 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1095 unsigned &RegOut = ConstantsOut[C];
1096 if (RegOut == 0) {
1097 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001098 UnorderedChains.push_back(
1099 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001100 }
1101 Reg = RegOut;
1102 } else {
1103 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001104 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001105 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001106 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1107 "Didn't codegen value into a register!??");
1108 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001109 UnorderedChains.push_back(
1110 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001111 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001112 }
Misha Brukman835702a2005-04-21 22:36:52 +00001113
Chris Lattner8ea875f2005-01-07 21:34:19 +00001114 // Remember that this register needs to added to the machine PHI node as
1115 // the input for this MBB.
1116 unsigned NumElements =
1117 TLI.getNumElements(TLI.getValueType(PN->getType()));
1118 for (unsigned i = 0, e = NumElements; i != e; ++i)
1119 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001120 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001121 }
1122 ConstantsOut.clear();
1123
Chris Lattner718b5c22005-01-13 17:59:43 +00001124 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001125 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001126 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001127 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1128 }
1129
Chris Lattner7a60d912005-01-07 07:47:53 +00001130 // Lower the terminator after the copies are emitted.
1131 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001132
1133 // Make sure the root of the DAG is up-to-date.
1134 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001135}
1136
1137void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1138 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001139 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001140 CurDAG = &DAG;
1141 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1142
1143 // First step, lower LLVM code to some DAG. This DAG may use operations and
1144 // types that are not supported by the target.
1145 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1146
1147 DEBUG(std::cerr << "Lowered selection DAG:\n");
1148 DEBUG(DAG.dump());
1149
1150 // Second step, hack on the DAG until it only uses operations and types that
1151 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001152 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001153
1154 DEBUG(std::cerr << "Legalized selection DAG:\n");
1155 DEBUG(DAG.dump());
1156
Chris Lattner5ca31d92005-03-30 01:10:47 +00001157 // Third, instruction select all of the operations to machine code, adding the
1158 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001159 InstructionSelectBasicBlock(DAG);
1160
Chris Lattnere05a4612005-01-12 03:41:21 +00001161 if (ViewDAGs) DAG.viewGraph();
1162
Chris Lattner7a60d912005-01-07 07:47:53 +00001163 DEBUG(std::cerr << "Selected machine code:\n");
1164 DEBUG(BB->dump());
1165
Chris Lattner5ca31d92005-03-30 01:10:47 +00001166 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001167 // PHI nodes in successors.
1168 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1169 MachineInstr *PHI = PHINodesToUpdate[i].first;
1170 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1171 "This is not a machine PHI node that we are updating!");
1172 PHI->addRegOperand(PHINodesToUpdate[i].second);
1173 PHI->addMachineBasicBlockOperand(BB);
1174 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001175
1176 // Finally, add the CFG edges from the last selected MBB to the successor
1177 // MBBs.
1178 TerminatorInst *TI = LLVMBB->getTerminator();
1179 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1180 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1181 BB->addSuccessor(Succ0MBB);
1182 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001183}