blob: 52bcc9ab75c8ee038dc9013b4a1c70fede9871fe [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"
Chris Lattneradf6a962005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-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 Lattner7944d9d2005-01-12 03:41:21 +000032#include "llvm/Support/CommandLine.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/Support/Debug.h"
34#include <map>
35#include <iostream>
36using namespace llvm;
37
Chris Lattner7944d9d2005-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 Lattner1c08c712005-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 Lattnerf26bc8e2005-01-08 19:52:31 +000050 class FunctionLoweringInfo {
51 public:
Chris Lattner1c08c712005-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 Lattner0afa8e32005-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 Lattner1c08c712005-01-07 07:47:53 +000080 unsigned MakeReg(MVT::ValueType VT) {
81 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
82 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000083
Chris Lattner1c08c712005-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 Lattnerfb849802005-01-16 00:37:38 +000089 if (NV == 1) {
90 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000091 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000092 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000093
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +000099
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +0000105
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +0000126 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-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 Lattner16ce0df2005-05-11 18:57:06 +0000132 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
133 AI != E; ++AI)
Chris Lattner1c08c712005-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);
Chris Lattnera8217e32005-05-13 23:14:17 +0000143
144 // If the alignment of the value is smaller than the size of the value,
145 // and if the size of the value is particularly small (<= 8 bytes),
146 // round up to the size of the value for potentially better performance.
147 //
148 // FIXME: This could be made better with a preferred alignment hook in
149 // TargetData. It serves primarily to 8-byte align doubles for X86.
150 if (Align < TySize && TySize <= 8) Align = TySize;
151
Chris Lattner1c08c712005-01-07 07:47:53 +0000152 TySize *= CUI->getValue(); // Get total allocated size.
153 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000154 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000155 }
156
157 for (; BB != E; ++BB)
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000158 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000159 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
160 if (!isa<AllocaInst>(I) ||
161 !StaticAllocaMap.count(cast<AllocaInst>(I)))
162 InitializeRegForValue(I);
163
164 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
165 // also creates the initial PHI MachineInstrs, though none of the input
166 // operands are populated.
167 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
168 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
169 MBBMap[BB] = MBB;
170 MF.getBasicBlockList().push_back(MBB);
171
172 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
173 // appropriate.
174 PHINode *PN;
175 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000176 (PN = dyn_cast<PHINode>(I)); ++I)
177 if (!PN->use_empty()) {
178 unsigned NumElements =
179 TLI.getNumElements(TLI.getValueType(PN->getType()));
180 unsigned PHIReg = ValueMap[PN];
181 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
182 for (unsigned i = 0; i != NumElements; ++i)
183 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
184 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000185 }
186}
187
188
189
190//===----------------------------------------------------------------------===//
191/// SelectionDAGLowering - This is the common target-independent lowering
192/// implementation that is parameterized by a TargetLowering object.
193/// Also, targets can overload any lowering method.
194///
195namespace llvm {
196class SelectionDAGLowering {
197 MachineBasicBlock *CurMBB;
198
199 std::map<const Value*, SDOperand> NodeMap;
200
Chris Lattnerd3948112005-01-17 22:19:26 +0000201 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
202 /// them up and then emit token factor nodes when possible. This allows us to
203 /// get simple disambiguation between loads without worrying about alias
204 /// analysis.
205 std::vector<SDOperand> PendingLoads;
206
Chris Lattner1c08c712005-01-07 07:47:53 +0000207public:
208 // TLI - This is information that describes the available target features we
209 // need for lowering. This indicates when operations are unavailable,
210 // implemented with a libcall, etc.
211 TargetLowering &TLI;
212 SelectionDAG &DAG;
213 const TargetData &TD;
214
215 /// FuncInfo - Information about the function as a whole.
216 ///
217 FunctionLoweringInfo &FuncInfo;
218
219 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000220 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000221 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
222 FuncInfo(funcinfo) {
223 }
224
Chris Lattnera651cf62005-01-17 19:43:36 +0000225 /// getRoot - Return the current virtual root of the Selection DAG.
226 ///
227 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000228 if (PendingLoads.empty())
229 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000230
Chris Lattnerd3948112005-01-17 22:19:26 +0000231 if (PendingLoads.size() == 1) {
232 SDOperand Root = PendingLoads[0];
233 DAG.setRoot(Root);
234 PendingLoads.clear();
235 return Root;
236 }
237
238 // Otherwise, we have to make a token factor node.
239 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
240 PendingLoads.clear();
241 DAG.setRoot(Root);
242 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000243 }
244
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 void visit(Instruction &I) { visit(I.getOpcode(), I); }
246
247 void visit(unsigned Opcode, User &I) {
248 switch (Opcode) {
249 default: assert(0 && "Unknown instruction type encountered!");
250 abort();
251 // Build the switch statement using the Instruction.def file.
252#define HANDLE_INST(NUM, OPCODE, CLASS) \
253 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
254#include "llvm/Instruction.def"
255 }
256 }
257
258 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
259
260
261 SDOperand getIntPtrConstant(uint64_t Val) {
262 return DAG.getConstant(Val, TLI.getPointerTy());
263 }
264
265 SDOperand getValue(const Value *V) {
266 SDOperand &N = NodeMap[V];
267 if (N.Val) return N;
268
269 MVT::ValueType VT = TLI.getValueType(V->getType());
270 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
271 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
272 visit(CE->getOpcode(), *CE);
273 assert(N.Val && "visit didn't populate the ValueMap!");
274 return N;
275 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
276 return N = DAG.getGlobalAddress(GV, VT);
277 } else if (isa<ConstantPointerNull>(C)) {
278 return N = DAG.getConstant(0, TLI.getPointerTy());
279 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000280 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000281 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
282 return N = DAG.getConstantFP(CFP->getValue(), VT);
283 } else {
284 // Canonicalize all constant ints to be unsigned.
285 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
286 }
287
288 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
289 std::map<const AllocaInst*, int>::iterator SI =
290 FuncInfo.StaticAllocaMap.find(AI);
291 if (SI != FuncInfo.StaticAllocaMap.end())
292 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
293 }
294
295 std::map<const Value*, unsigned>::const_iterator VMI =
296 FuncInfo.ValueMap.find(V);
297 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000298
Chris Lattneref5cd1d2005-01-18 17:54:55 +0000299 return N = DAG.getCopyFromReg(VMI->second, VT, DAG.getEntryNode());
Chris Lattner1c08c712005-01-07 07:47:53 +0000300 }
301
302 const SDOperand &setValue(const Value *V, SDOperand NewN) {
303 SDOperand &N = NodeMap[V];
304 assert(N.Val == 0 && "Already set a value for this node!");
305 return N = NewN;
306 }
307
308 // Terminator instructions.
309 void visitRet(ReturnInst &I);
310 void visitBr(BranchInst &I);
311 void visitUnreachable(UnreachableInst &I) { /* noop */ }
312
313 // These all get lowered before this pass.
314 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
315 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
316 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
317
318 //
319 void visitBinary(User &I, unsigned Opcode);
320 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000321 void visitSub(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
323 void visitDiv(User &I) {
324 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
325 }
326 void visitRem(User &I) {
327 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
328 }
329 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
330 void visitOr (User &I) { visitBinary(I, ISD::OR); }
331 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
332 void visitShl(User &I) { visitBinary(I, ISD::SHL); }
333 void visitShr(User &I) {
334 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
335 }
336
337 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
338 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
339 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
340 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
341 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
342 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
343 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
344
345 void visitGetElementPtr(User &I);
346 void visitCast(User &I);
347 void visitSelect(User &I);
348 //
349
350 void visitMalloc(MallocInst &I);
351 void visitFree(FreeInst &I);
352 void visitAlloca(AllocaInst &I);
353 void visitLoad(LoadInst &I);
354 void visitStore(StoreInst &I);
355 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
356 void visitCall(CallInst &I);
357
Chris Lattner1c08c712005-01-07 07:47:53 +0000358 void visitVAStart(CallInst &I);
359 void visitVANext(VANextInst &I);
360 void visitVAArg(VAArgInst &I);
361 void visitVAEnd(CallInst &I);
362 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000363 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000364
Chris Lattner7041ee32005-01-11 05:56:49 +0000365 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000366
367 void visitUserOp1(Instruction &I) {
368 assert(0 && "UserOp1 should not exist at instruction selection time!");
369 abort();
370 }
371 void visitUserOp2(Instruction &I) {
372 assert(0 && "UserOp2 should not exist at instruction selection time!");
373 abort();
374 }
375};
376} // end namespace llvm
377
378void SelectionDAGLowering::visitRet(ReturnInst &I) {
379 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000380 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000381 return;
382 }
383
384 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000385 MVT::ValueType TmpVT;
386
Chris Lattner1c08c712005-01-07 07:47:53 +0000387 switch (Op1.getValueType()) {
388 default: assert(0 && "Unknown value type!");
389 case MVT::i1:
390 case MVT::i8:
391 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000392 case MVT::i32:
393 // If this is a machine where 32-bits is legal or expanded, promote to
394 // 32-bits, otherwise, promote to 64-bits.
395 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
396 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000397 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000398 TmpVT = MVT::i32;
399
400 // Extend integer types to result type.
401 if (I.getOperand(0)->getType()->isSigned())
402 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
403 else
404 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000405 break;
406 case MVT::f32:
407 // Extend float to double.
408 Op1 = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Op1);
409 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000410 case MVT::i64:
411 case MVT::f64:
412 break; // No extension needed!
413 }
414
Chris Lattnera651cf62005-01-17 19:43:36 +0000415 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000416}
417
418void SelectionDAGLowering::visitBr(BranchInst &I) {
419 // Update machine-CFG edges.
420 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000421
422 // Figure out which block is immediately after the current one.
423 MachineBasicBlock *NextBlock = 0;
424 MachineFunction::iterator BBI = CurMBB;
425 if (++BBI != CurMBB->getParent()->end())
426 NextBlock = BBI;
427
428 if (I.isUnconditional()) {
429 // If this is not a fall-through branch, emit the branch.
430 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000431 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000432 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000433 } else {
434 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000435
436 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000437 if (Succ1MBB == NextBlock) {
438 // If the condition is false, fall through. This means we should branch
439 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000440 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000441 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000442 } else if (Succ0MBB == NextBlock) {
443 // If the condition is true, fall through. This means we should branch if
444 // the condition is false to Succ #1. Invert the condition first.
445 SDOperand True = DAG.getConstant(1, Cond.getValueType());
446 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000447 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000448 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000449 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000450 std::vector<SDOperand> Ops;
451 Ops.push_back(getRoot());
452 Ops.push_back(Cond);
453 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
454 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
455 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000456 }
457 }
458}
459
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000460void SelectionDAGLowering::visitSub(User &I) {
461 // -0.0 - X --> fneg
462 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
463 if (CFP->isExactlyValue(-0.0)) {
464 SDOperand Op2 = getValue(I.getOperand(1));
465 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
466 return;
467 }
468
469 visitBinary(I, ISD::SUB);
470}
471
Chris Lattner1c08c712005-01-07 07:47:53 +0000472void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode) {
473 SDOperand Op1 = getValue(I.getOperand(0));
474 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000475
476 if (isa<ShiftInst>(I))
477 Op2 = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), Op2);
478
Chris Lattner1c08c712005-01-07 07:47:53 +0000479 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
480}
481
482void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
483 ISD::CondCode UnsignedOpcode) {
484 SDOperand Op1 = getValue(I.getOperand(0));
485 SDOperand Op2 = getValue(I.getOperand(1));
486 ISD::CondCode Opcode = SignedOpcode;
487 if (I.getOperand(0)->getType()->isUnsigned())
488 Opcode = UnsignedOpcode;
Chris Lattnerf30b73b2005-01-18 02:52:03 +0000489 setValue(&I, DAG.getSetCC(Opcode, MVT::i1, Op1, Op2));
Chris Lattner1c08c712005-01-07 07:47:53 +0000490}
491
492void SelectionDAGLowering::visitSelect(User &I) {
493 SDOperand Cond = getValue(I.getOperand(0));
494 SDOperand TrueVal = getValue(I.getOperand(1));
495 SDOperand FalseVal = getValue(I.getOperand(2));
496 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
497 TrueVal, FalseVal));
498}
499
500void SelectionDAGLowering::visitCast(User &I) {
501 SDOperand N = getValue(I.getOperand(0));
502 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
503 MVT::ValueType DestTy = TLI.getValueType(I.getType());
504
505 if (N.getValueType() == DestTy) {
506 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000507 } else if (DestTy == MVT::i1) {
508 // Cast to bool is a comparison against zero, not truncation to zero.
509 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
510 DAG.getConstantFP(0.0, N.getValueType());
511 setValue(&I, DAG.getSetCC(ISD::SETNE, MVT::i1, N, Zero));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000512 } else if (isInteger(SrcTy)) {
513 if (isInteger(DestTy)) { // Int -> Int cast
514 if (DestTy < SrcTy) // Truncating cast?
515 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
516 else if (I.getOperand(0)->getType()->isSigned())
517 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
518 else
519 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
520 } else { // Int -> FP cast
521 if (I.getOperand(0)->getType()->isSigned())
522 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
523 else
524 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
525 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000526 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000527 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
528 if (isFloatingPoint(DestTy)) { // FP -> FP cast
529 if (DestTy < SrcTy) // Rounding cast?
530 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
531 else
532 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
533 } else { // FP -> Int cast.
534 if (I.getType()->isSigned())
535 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
536 else
537 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
538 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000539 }
540}
541
542void SelectionDAGLowering::visitGetElementPtr(User &I) {
543 SDOperand N = getValue(I.getOperand(0));
544 const Type *Ty = I.getOperand(0)->getType();
545 const Type *UIntPtrTy = TD.getIntPtrType();
546
547 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
548 OI != E; ++OI) {
549 Value *Idx = *OI;
550 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
551 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
552 if (Field) {
553 // N = N + Offset
554 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
555 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000556 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 }
558 Ty = StTy->getElementType(Field);
559 } else {
560 Ty = cast<SequentialType>(Ty)->getElementType();
561 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
562 // N = N + Idx * ElementSize;
563 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner7cc47772005-01-07 21:56:57 +0000564 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
565
566 // If the index is smaller or larger than intptr_t, truncate or extend
567 // it.
568 if (IdxN.getValueType() < Scale.getValueType()) {
569 if (Idx->getType()->isSigned())
570 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
571 else
572 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
573 } else if (IdxN.getValueType() > Scale.getValueType())
574 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
575
576 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner1c08c712005-01-07 07:47:53 +0000577 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
578 }
579 }
580 }
581 setValue(&I, N);
582}
583
584void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
585 // If this is a fixed sized alloca in the entry block of the function,
586 // allocate it statically on the stack.
587 if (FuncInfo.StaticAllocaMap.count(&I))
588 return; // getValue will auto-populate this.
589
590 const Type *Ty = I.getAllocatedType();
591 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
592 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
593
594 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000595 MVT::ValueType IntPtr = TLI.getPointerTy();
596 if (IntPtr < AllocSize.getValueType())
597 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
598 else if (IntPtr > AllocSize.getValueType())
599 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
Chris Lattner68cd65e2005-01-22 23:04:37 +0000601 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000602 getIntPtrConstant(TySize));
603
604 // Handle alignment. If the requested alignment is less than or equal to the
605 // stack alignment, ignore it and round the size of the allocation up to the
606 // stack alignment size. If the size is greater than the stack alignment, we
607 // note this in the DYNAMIC_STACKALLOC node.
608 unsigned StackAlign =
609 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
610 if (Align <= StackAlign) {
611 Align = 0;
612 // Add SA-1 to the size.
613 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
614 getIntPtrConstant(StackAlign-1));
615 // Mask out the low bits for alignment purposes.
616 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
617 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
618 }
619
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000620 std::vector<MVT::ValueType> VTs;
621 VTs.push_back(AllocSize.getValueType());
622 VTs.push_back(MVT::Other);
623 std::vector<SDOperand> Ops;
624 Ops.push_back(getRoot());
625 Ops.push_back(AllocSize);
626 Ops.push_back(getIntPtrConstant(Align));
627 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000628 DAG.setRoot(setValue(&I, DSA).getValue(1));
629
630 // Inform the Frame Information that we have just allocated a variable-sized
631 // object.
632 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
633}
634
635
636void SelectionDAGLowering::visitLoad(LoadInst &I) {
637 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000638
Chris Lattnerd3948112005-01-17 22:19:26 +0000639 SDOperand Root;
640 if (I.isVolatile())
641 Root = getRoot();
642 else {
643 // Do not serialize non-volatile loads against each other.
644 Root = DAG.getRoot();
645 }
646
Chris Lattner369e6db2005-05-09 04:08:33 +0000647 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Chris Lattnerfd414a22005-05-09 04:28:51 +0000648 DAG.getSrcValue(I.getOperand(0)));
Chris Lattnerd3948112005-01-17 22:19:26 +0000649 setValue(&I, L);
650
651 if (I.isVolatile())
652 DAG.setRoot(L.getValue(1));
653 else
654 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000655}
656
657
658void SelectionDAGLowering::visitStore(StoreInst &I) {
659 Value *SrcV = I.getOperand(0);
660 SDOperand Src = getValue(SrcV);
661 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000662 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Chris Lattnerfd414a22005-05-09 04:28:51 +0000663 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000664}
665
666void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +0000667 const char *RenameFn = 0;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000668 SDOperand Tmp;
Chris Lattner1c08c712005-01-07 07:47:53 +0000669 if (Function *F = I.getCalledFunction())
Chris Lattnerc0f18152005-04-02 05:26:53 +0000670 if (F->isExternal())
671 switch (F->getIntrinsicID()) {
672 case 0: // Not an LLVM intrinsic.
673 if (F->getName() == "fabs" || F->getName() == "fabsf") {
674 if (I.getNumOperands() == 2 && // Basic sanity checks.
675 I.getOperand(1)->getType()->isFloatingPoint() &&
676 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000677 Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000678 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
679 return;
680 }
681 }
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000682 else if (F->getName() == "sin" || F->getName() == "sinf") {
683 if (I.getNumOperands() == 2 && // Basic sanity checks.
684 I.getOperand(1)->getType()->isFloatingPoint() &&
685 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000686 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000687 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
688 return;
689 }
690 }
691 else if (F->getName() == "cos" || F->getName() == "cosf") {
692 if (I.getNumOperands() == 2 && // Basic sanity checks.
693 I.getOperand(1)->getType()->isFloatingPoint() &&
694 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000695 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000696 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
697 return;
698 }
699 }
Chris Lattnerc0f18152005-04-02 05:26:53 +0000700 break;
701 case Intrinsic::vastart: visitVAStart(I); return;
702 case Intrinsic::vaend: visitVAEnd(I); return;
703 case Intrinsic::vacopy: visitVACopy(I); return;
704 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
705 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000706
Chris Lattnerc0f18152005-04-02 05:26:53 +0000707 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
708 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
709 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
710 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
711 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000712
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000713 case Intrinsic::readport:
714 case Intrinsic::readio:
715 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
716 ISD::READPORT : ISD::READIO,
717 TLI.getValueType(I.getType()), getRoot(),
718 getValue(I.getOperand(1)));
719 setValue(&I, Tmp);
720 DAG.setRoot(Tmp.getValue(1));
721 return;
722 case Intrinsic::writeport:
723 case Intrinsic::writeio:
724 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
725 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
726 getRoot(), getValue(I.getOperand(1)),
727 getValue(I.getOperand(2))));
728 return;
Chris Lattner7ea0ade2005-05-05 17:55:17 +0000729 case Intrinsic::dbg_stoppoint:
730 case Intrinsic::dbg_region_start:
731 case Intrinsic::dbg_region_end:
732 case Intrinsic::dbg_func_start:
733 case Intrinsic::dbg_declare:
734 if (I.getType() != Type::VoidTy)
735 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
736 return;
737
Chris Lattnerc0f18152005-04-02 05:26:53 +0000738 case Intrinsic::isunordered:
739 setValue(&I, DAG.getSetCC(ISD::SETUO, MVT::i1,getValue(I.getOperand(1)),
740 getValue(I.getOperand(2))));
741 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000742
743 case Intrinsic::sqrt:
744 setValue(&I, DAG.getNode(ISD::FSQRT,
745 getValue(I.getOperand(1)).getValueType(),
746 getValue(I.getOperand(1))));
747 return;
748
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000749 case Intrinsic::pcmarker:
750 Tmp = getValue(I.getOperand(1));
751 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000752 return;
Andrew Lenharth691ef2b2005-05-03 17:19:30 +0000753 case Intrinsic::cttz:
754 setValue(&I, DAG.getNode(ISD::CTTZ,
755 getValue(I.getOperand(1)).getValueType(),
756 getValue(I.getOperand(1))));
757 return;
758 case Intrinsic::ctlz:
759 setValue(&I, DAG.getNode(ISD::CTLZ,
760 getValue(I.getOperand(1)).getValueType(),
761 getValue(I.getOperand(1))));
762 return;
763 case Intrinsic::ctpop:
764 setValue(&I, DAG.getNode(ISD::CTPOP,
765 getValue(I.getOperand(1)).getValueType(),
766 getValue(I.getOperand(1))));
767 return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000768 default:
769 std::cerr << I;
770 assert(0 && "This intrinsic is not implemented yet!");
771 return;
Chris Lattnerc0f18152005-04-02 05:26:53 +0000772 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000773
Chris Lattner64e14b12005-01-08 22:48:57 +0000774 SDOperand Callee;
775 if (!RenameFn)
776 Callee = getValue(I.getOperand(0));
777 else
778 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +0000779 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000780
Chris Lattner1c08c712005-01-07 07:47:53 +0000781 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
782 Value *Arg = I.getOperand(i);
783 SDOperand ArgNode = getValue(Arg);
784 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
785 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000786
Nate Begeman8e21e712005-03-26 01:29:23 +0000787 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
788 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000789
Chris Lattnercf5734d2005-01-08 19:26:18 +0000790 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +0000791 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +0000792 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +0000793 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +0000794 setValue(&I, Result.first);
795 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000796}
797
798void SelectionDAGLowering::visitMalloc(MallocInst &I) {
799 SDOperand Src = getValue(I.getOperand(0));
800
801 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +0000802
803 if (IntPtr < Src.getValueType())
804 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
805 else if (IntPtr > Src.getValueType())
806 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +0000807
808 // Scale the source by the type size.
809 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
810 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
811 Src, getIntPtrConstant(ElementSize));
812
813 std::vector<std::pair<SDOperand, const Type*> > Args;
814 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +0000815
816 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000817 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000818 DAG.getExternalSymbol("malloc", IntPtr),
819 Args, DAG);
820 setValue(&I, Result.first); // Pointers always fit in registers
821 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000822}
823
824void SelectionDAGLowering::visitFree(FreeInst &I) {
825 std::vector<std::pair<SDOperand, const Type*> > Args;
826 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
827 TLI.getTargetData().getIntPtrType()));
828 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +0000829 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000830 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000831 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
832 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000833}
834
Chris Lattner39ae3622005-01-09 00:00:49 +0000835std::pair<SDOperand, SDOperand>
836TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000837 // We have no sane default behavior, just emit a useful error message and bail
838 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +0000839 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000840 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000841 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner1c08c712005-01-07 07:47:53 +0000842}
843
Chris Lattner39ae3622005-01-09 00:00:49 +0000844SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand L,
845 SelectionDAG &DAG) {
846 // Default to a noop.
847 return Chain;
848}
849
850std::pair<SDOperand,SDOperand>
851TargetLowering::LowerVACopy(SDOperand Chain, SDOperand L, SelectionDAG &DAG) {
852 // Default to returning the input list.
853 return std::make_pair(L, Chain);
854}
855
856std::pair<SDOperand,SDOperand>
857TargetLowering::LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
858 const Type *ArgTy, SelectionDAG &DAG) {
859 // We have no sane default behavior, just emit a useful error message and bail
860 // out.
861 std::cerr << "Variable arguments handling not implemented on this target!\n";
862 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000863 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +0000864}
865
866
867void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000868 std::pair<SDOperand,SDOperand> Result = TLI.LowerVAStart(getRoot(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000869 setValue(&I, Result.first);
870 DAG.setRoot(Result.second);
871}
872
873void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
874 std::pair<SDOperand,SDOperand> Result =
Misha Brukmanedf128a2005-04-21 22:36:52 +0000875 TLI.LowerVAArgNext(false, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000876 I.getType(), DAG);
877 setValue(&I, Result.first);
878 DAG.setRoot(Result.second);
879}
880
Chris Lattner1c08c712005-01-07 07:47:53 +0000881void SelectionDAGLowering::visitVANext(VANextInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000882 std::pair<SDOperand,SDOperand> Result =
Misha Brukmanedf128a2005-04-21 22:36:52 +0000883 TLI.LowerVAArgNext(true, getRoot(), getValue(I.getOperand(0)),
Chris Lattner39ae3622005-01-09 00:00:49 +0000884 I.getArgType(), DAG);
885 setValue(&I, Result.first);
886 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000887}
888
889void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000890 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000891}
892
893void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000894 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000895 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(1)), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000896 setValue(&I, Result.first);
897 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000898}
899
Chris Lattner39ae3622005-01-09 00:00:49 +0000900
901// It is always conservatively correct for llvm.returnaddress and
902// llvm.frameaddress to return 0.
903std::pair<SDOperand, SDOperand>
904TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
905 unsigned Depth, SelectionDAG &DAG) {
906 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +0000907}
908
Chris Lattner50381b62005-05-14 05:50:48 +0000909SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +0000910 assert(0 && "LowerOperation not implemented for this target!");
911 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000912 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +0000913}
914
Chris Lattner39ae3622005-01-09 00:00:49 +0000915void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
916 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
917 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000918 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000919 setValue(&I, Result.first);
920 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000921}
922
Chris Lattner7041ee32005-01-11 05:56:49 +0000923void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
924 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +0000925 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +0000926 Ops.push_back(getValue(I.getOperand(1)));
927 Ops.push_back(getValue(I.getOperand(2)));
928 Ops.push_back(getValue(I.getOperand(3)));
929 Ops.push_back(getValue(I.getOperand(4)));
930 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000931}
932
Chris Lattner7041ee32005-01-11 05:56:49 +0000933//===----------------------------------------------------------------------===//
934// SelectionDAGISel code
935//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000936
937unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
938 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
939}
940
941
942
943bool SelectionDAGISel::runOnFunction(Function &Fn) {
944 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
945 RegMap = MF.getSSARegMap();
946 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
947
948 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
949
950 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
951 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000952
Chris Lattner1c08c712005-01-07 07:47:53 +0000953 return true;
954}
955
956
Chris Lattnerddb870b2005-01-13 17:59:43 +0000957SDOperand SelectionDAGISel::
958CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000959 SelectionDAG &DAG = SDL.DAG;
Chris Lattnerf1fdaca2005-01-11 22:03:46 +0000960 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +0000961 assert((Op.getOpcode() != ISD::CopyFromReg ||
962 cast<RegSDNode>(Op)->getReg() != Reg) &&
963 "Copy from a reg to the same reg!");
Chris Lattnera651cf62005-01-17 19:43:36 +0000964 return DAG.getCopyToReg(SDL.getRoot(), Op, Reg);
Chris Lattner1c08c712005-01-07 07:47:53 +0000965}
966
Chris Lattner0afa8e32005-01-17 17:55:19 +0000967/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
968/// single basic block, return that block. Otherwise, return a null pointer.
969static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
970 if (A->use_empty()) return 0;
971 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
972 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
973 ++UI)
974 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
975 return 0; // Disagreement among the users?
Chris Lattneraa781b32005-02-17 19:40:32 +0000976
977 // Okay, there is a single BB user. Only permit this optimization if this is
978 // the entry block, otherwise, we might sink argument loads into loops and
979 // stuff. Later, when we have global instruction selection, this won't be an
980 // issue clearly.
981 if (BB == BB->getParent()->begin())
982 return BB;
983 return 0;
Chris Lattner0afa8e32005-01-17 17:55:19 +0000984}
985
Chris Lattner068a81e2005-01-17 17:15:02 +0000986void SelectionDAGISel::
987LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
988 std::vector<SDOperand> &UnorderedChains) {
989 // If this is the entry block, emit arguments.
990 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +0000991 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner068a81e2005-01-17 17:15:02 +0000992
993 if (BB == &F.front()) {
Chris Lattner0afa8e32005-01-17 17:55:19 +0000994 SDOperand OldRoot = SDL.DAG.getRoot();
995
Chris Lattner068a81e2005-01-17 17:15:02 +0000996 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
997
Chris Lattner0afa8e32005-01-17 17:55:19 +0000998 // If there were side effects accessing the argument list, do not do
999 // anything special.
1000 if (OldRoot != SDL.DAG.getRoot()) {
1001 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001002 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1003 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001004 if (!AI->use_empty()) {
1005 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001006 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +00001007 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1008 UnorderedChains.push_back(Copy);
1009 }
1010 } else {
1011 // Otherwise, if any argument is only accessed in a single basic block,
1012 // emit that argument only to that basic block.
1013 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001014 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1015 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001016 if (!AI->use_empty()) {
1017 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1018 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1019 std::make_pair(AI, a)));
1020 } else {
1021 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001022 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +00001023 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1024 UnorderedChains.push_back(Copy);
1025 }
1026 }
1027 }
Chris Lattner405ef9e2005-05-13 07:33:32 +00001028
1029 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner0afa8e32005-01-17 17:55:19 +00001030 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001031
Chris Lattner0afa8e32005-01-17 17:55:19 +00001032 // See if there are any block-local arguments that need to be emitted in this
1033 // block.
1034
1035 if (!FuncInfo.BlockLocalArguments.empty()) {
1036 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1037 FuncInfo.BlockLocalArguments.lower_bound(BB);
1038 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1039 // Lower the arguments into this block.
1040 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001041
Chris Lattner0afa8e32005-01-17 17:55:19 +00001042 // Set up the value mapping for the local arguments.
1043 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1044 ++BLAI)
1045 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001046
Chris Lattner0afa8e32005-01-17 17:55:19 +00001047 // Any dead arguments will just be ignored here.
1048 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001049 }
1050}
1051
1052
Chris Lattner1c08c712005-01-07 07:47:53 +00001053void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1054 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1055 FunctionLoweringInfo &FuncInfo) {
1056 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001057
1058 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001059
Chris Lattner068a81e2005-01-17 17:15:02 +00001060 // Lower any arguments needed in this block.
1061 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001062
1063 BB = FuncInfo.MBBMap[LLVMBB];
1064 SDL.setCurrentBasicBlock(BB);
1065
1066 // Lower all of the non-terminator instructions.
1067 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1068 I != E; ++I)
1069 SDL.visit(*I);
1070
1071 // Ensure that all instructions which are used outside of their defining
1072 // blocks are available as virtual registers.
1073 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001074 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001075 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001076 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001077 UnorderedChains.push_back(
1078 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001079 }
1080
1081 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1082 // ensure constants are generated when needed. Remember the virtual registers
1083 // that need to be added to the Machine PHI nodes as input. We cannot just
1084 // directly add them, because expansion might result in multiple MBB's for one
1085 // BB. As such, the start of the BB might correspond to a different MBB than
1086 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001087 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001088
1089 // Emit constants only once even if used by multiple PHI nodes.
1090 std::map<Constant*, unsigned> ConstantsOut;
1091
1092 // Check successor nodes PHI nodes that expect a constant to be available from
1093 // this block.
1094 TerminatorInst *TI = LLVMBB->getTerminator();
1095 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1096 BasicBlock *SuccBB = TI->getSuccessor(succ);
1097 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1098 PHINode *PN;
1099
1100 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1101 // nodes and Machine PHI nodes, but the incoming operands have not been
1102 // emitted yet.
1103 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001104 (PN = dyn_cast<PHINode>(I)); ++I)
1105 if (!PN->use_empty()) {
1106 unsigned Reg;
1107 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1108 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1109 unsigned &RegOut = ConstantsOut[C];
1110 if (RegOut == 0) {
1111 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001112 UnorderedChains.push_back(
1113 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001114 }
1115 Reg = RegOut;
1116 } else {
1117 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001118 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001119 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001120 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1121 "Didn't codegen value into a register!??");
1122 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001123 UnorderedChains.push_back(
1124 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001125 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001126 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001127
Chris Lattnerf44fd882005-01-07 21:34:19 +00001128 // Remember that this register needs to added to the machine PHI node as
1129 // the input for this MBB.
1130 unsigned NumElements =
1131 TLI.getNumElements(TLI.getValueType(PN->getType()));
1132 for (unsigned i = 0, e = NumElements; i != e; ++i)
1133 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001134 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001135 }
1136 ConstantsOut.clear();
1137
Chris Lattnerddb870b2005-01-13 17:59:43 +00001138 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001139 if (!UnorderedChains.empty()) {
Chris Lattnerd3948112005-01-17 22:19:26 +00001140 UnorderedChains.push_back(SDL.getRoot());
Chris Lattnerddb870b2005-01-13 17:59:43 +00001141 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1142 }
1143
Chris Lattner1c08c712005-01-07 07:47:53 +00001144 // Lower the terminator after the copies are emitted.
1145 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001146
1147 // Make sure the root of the DAG is up-to-date.
1148 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001149}
1150
1151void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1152 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001153 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001154 CurDAG = &DAG;
1155 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1156
1157 // First step, lower LLVM code to some DAG. This DAG may use operations and
1158 // types that are not supported by the target.
1159 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1160
1161 DEBUG(std::cerr << "Lowered selection DAG:\n");
1162 DEBUG(DAG.dump());
1163
1164 // Second step, hack on the DAG until it only uses operations and types that
1165 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001166 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001167
1168 DEBUG(std::cerr << "Legalized selection DAG:\n");
1169 DEBUG(DAG.dump());
1170
Chris Lattnera33ef482005-03-30 01:10:47 +00001171 // Third, instruction select all of the operations to machine code, adding the
1172 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001173 InstructionSelectBasicBlock(DAG);
1174
Chris Lattner7944d9d2005-01-12 03:41:21 +00001175 if (ViewDAGs) DAG.viewGraph();
1176
Chris Lattner1c08c712005-01-07 07:47:53 +00001177 DEBUG(std::cerr << "Selected machine code:\n");
1178 DEBUG(BB->dump());
1179
Chris Lattnera33ef482005-03-30 01:10:47 +00001180 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001181 // PHI nodes in successors.
1182 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1183 MachineInstr *PHI = PHINodesToUpdate[i].first;
1184 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1185 "This is not a machine PHI node that we are updating!");
1186 PHI->addRegOperand(PHINodesToUpdate[i].second);
1187 PHI->addMachineBasicBlockOperand(BB);
1188 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001189
1190 // Finally, add the CFG edges from the last selected MBB to the successor
1191 // MBBs.
1192 TerminatorInst *TI = LLVMBB->getTerminator();
1193 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1194 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1195 BB->addSuccessor(Succ0MBB);
1196 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001197}