blob: 3a344a26601ef292474c7cf0757a188b6ed52260 [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"
Chris Lattnerd4382f02005-09-13 19:30:54 +000027#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetFrameInfo.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetLowering.h"
32#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000034#include "llvm/Support/CommandLine.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/Support/Debug.h"
36#include <map>
37#include <iostream>
38using namespace llvm;
39
Chris Lattner975f5c92005-09-01 18:44:10 +000040#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000041static cl::opt<bool>
42ViewDAGs("view-isel-dags", cl::Hidden,
43 cl::desc("Pop up a window to show isel dags as they are selected"));
44#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000045static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000046#endif
47
Nate Begeman007c6502005-09-07 00:15:36 +000048
Chris Lattner7a60d912005-01-07 07:47:53 +000049namespace llvm {
50 //===--------------------------------------------------------------------===//
51 /// FunctionLoweringInfo - This contains information that is global to a
52 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000053 class FunctionLoweringInfo {
54 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000055 TargetLowering &TLI;
56 Function &Fn;
57 MachineFunction &MF;
58 SSARegMap *RegMap;
59
60 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
61
62 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
64
65 /// ValueMap - Since we emit code for the function a basic block at a time,
66 /// we must remember which virtual registers hold the values for
67 /// cross-basic-block values.
68 std::map<const Value*, unsigned> ValueMap;
69
70 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71 /// the entry block. This allows the allocas to be efficiently referenced
72 /// anywhere in the function.
73 std::map<const AllocaInst*, int> StaticAllocaMap;
74
Chris Lattnere3c2cf42005-01-17 17:55:19 +000075 /// BlockLocalArguments - If any arguments are only used in a single basic
76 /// block, and if the target can access the arguments without side-effects,
77 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
78 /// track of which arguments are local to each BB.
79 std::multimap<BasicBlock*, std::pair<Argument*,
80 unsigned> > BlockLocalArguments;
81
82
Chris Lattner7a60d912005-01-07 07:47:53 +000083 unsigned MakeReg(MVT::ValueType VT) {
84 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
85 }
Misha Brukman835702a2005-04-21 22:36:52 +000086
Chris Lattner7a60d912005-01-07 07:47:53 +000087 unsigned CreateRegForValue(const Value *V) {
88 MVT::ValueType VT = TLI.getValueType(V->getType());
89 // The common case is that we will only create one register for this
90 // value. If we have that case, create and return the virtual register.
91 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000092 if (NV == 1) {
93 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000094 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000095 }
Misha Brukman835702a2005-04-21 22:36:52 +000096
Chris Lattner7a60d912005-01-07 07:47:53 +000097 // If this value is represented with multiple target registers, make sure
98 // to create enough consequtive registers of the right (smaller) type.
99 unsigned NT = VT-1; // Find the type to use.
100 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
101 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000102
Chris Lattner7a60d912005-01-07 07:47:53 +0000103 unsigned R = MakeReg((MVT::ValueType)NT);
104 for (unsigned i = 1; i != NV; ++i)
105 MakeReg((MVT::ValueType)NT);
106 return R;
107 }
Misha Brukman835702a2005-04-21 22:36:52 +0000108
Chris Lattner7a60d912005-01-07 07:47:53 +0000109 unsigned InitializeRegForValue(const Value *V) {
110 unsigned &R = ValueMap[V];
111 assert(R == 0 && "Already initialized this value register!");
112 return R = CreateRegForValue(V);
113 }
114 };
115}
116
117/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118/// PHI nodes or outside of the basic block that defines it.
119static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120 if (isa<PHINode>(I)) return true;
121 BasicBlock *BB = I->getParent();
122 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
124 return true;
125 return false;
126}
127
128FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000129 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000130 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
131
132 // Initialize the mapping of values to registers. This is only set up for
133 // instruction values that are used outside of the block that defines
134 // them.
Chris Lattner490769c2005-05-11 18:57:06 +0000135 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
136 AI != E; ++AI)
Chris Lattner7a60d912005-01-07 07:47:53 +0000137 InitializeRegForValue(AI);
138
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000139 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000140 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
141 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
142 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
143 const Type *Ty = AI->getAllocatedType();
144 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
145 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
Chris Lattnercbefe722005-05-13 23:14:17 +0000146
147 // If the alignment of the value is smaller than the size of the value,
148 // and if the size of the value is particularly small (<= 8 bytes),
149 // round up to the size of the value for potentially better performance.
150 //
151 // FIXME: This could be made better with a preferred alignment hook in
152 // TargetData. It serves primarily to 8-byte align doubles for X86.
153 if (Align < TySize && TySize <= 8) Align = TySize;
154
Chris Lattnerb0b4ec52005-09-02 18:41:28 +0000155 if (CUI->getValue()) // Don't produce zero sized stack objects
156 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000158 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000159 }
160
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000161 for (; BB != EB; ++BB)
162 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000163 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
164 if (!isa<AllocaInst>(I) ||
165 !StaticAllocaMap.count(cast<AllocaInst>(I)))
166 InitializeRegForValue(I);
167
168 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
169 // also creates the initial PHI MachineInstrs, though none of the input
170 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000171 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000172 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
173 MBBMap[BB] = MBB;
174 MF.getBasicBlockList().push_back(MBB);
175
176 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
177 // appropriate.
178 PHINode *PN;
179 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000180 (PN = dyn_cast<PHINode>(I)); ++I)
181 if (!PN->use_empty()) {
182 unsigned NumElements =
183 TLI.getNumElements(TLI.getValueType(PN->getType()));
184 unsigned PHIReg = ValueMap[PN];
185 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
186 for (unsigned i = 0; i != NumElements; ++i)
187 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
188 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000189 }
190}
191
192
193
194//===----------------------------------------------------------------------===//
195/// SelectionDAGLowering - This is the common target-independent lowering
196/// implementation that is parameterized by a TargetLowering object.
197/// Also, targets can overload any lowering method.
198///
199namespace llvm {
200class SelectionDAGLowering {
201 MachineBasicBlock *CurMBB;
202
203 std::map<const Value*, SDOperand> NodeMap;
204
Chris Lattner4d9651c2005-01-17 22:19:26 +0000205 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
206 /// them up and then emit token factor nodes when possible. This allows us to
207 /// get simple disambiguation between loads without worrying about alias
208 /// analysis.
209 std::vector<SDOperand> PendingLoads;
210
Chris Lattner7a60d912005-01-07 07:47:53 +0000211public:
212 // TLI - This is information that describes the available target features we
213 // need for lowering. This indicates when operations are unavailable,
214 // implemented with a libcall, etc.
215 TargetLowering &TLI;
216 SelectionDAG &DAG;
217 const TargetData &TD;
218
219 /// FuncInfo - Information about the function as a whole.
220 ///
221 FunctionLoweringInfo &FuncInfo;
222
223 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000224 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000225 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
226 FuncInfo(funcinfo) {
227 }
228
Chris Lattner4108bb02005-01-17 19:43:36 +0000229 /// getRoot - Return the current virtual root of the Selection DAG.
230 ///
231 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000232 if (PendingLoads.empty())
233 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000234
Chris Lattner4d9651c2005-01-17 22:19:26 +0000235 if (PendingLoads.size() == 1) {
236 SDOperand Root = PendingLoads[0];
237 DAG.setRoot(Root);
238 PendingLoads.clear();
239 return Root;
240 }
241
242 // Otherwise, we have to make a token factor node.
243 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
244 PendingLoads.clear();
245 DAG.setRoot(Root);
246 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000247 }
248
Chris Lattner7a60d912005-01-07 07:47:53 +0000249 void visit(Instruction &I) { visit(I.getOpcode(), I); }
250
251 void visit(unsigned Opcode, User &I) {
252 switch (Opcode) {
253 default: assert(0 && "Unknown instruction type encountered!");
254 abort();
255 // Build the switch statement using the Instruction.def file.
256#define HANDLE_INST(NUM, OPCODE, CLASS) \
257 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
258#include "llvm/Instruction.def"
259 }
260 }
261
262 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
263
264
265 SDOperand getIntPtrConstant(uint64_t Val) {
266 return DAG.getConstant(Val, TLI.getPointerTy());
267 }
268
269 SDOperand getValue(const Value *V) {
270 SDOperand &N = NodeMap[V];
271 if (N.Val) return N;
272
273 MVT::ValueType VT = TLI.getValueType(V->getType());
274 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
275 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
276 visit(CE->getOpcode(), *CE);
277 assert(N.Val && "visit didn't populate the ValueMap!");
278 return N;
279 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
280 return N = DAG.getGlobalAddress(GV, VT);
281 } else if (isa<ConstantPointerNull>(C)) {
282 return N = DAG.getConstant(0, TLI.getPointerTy());
283 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000284 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000285 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
286 return N = DAG.getConstantFP(CFP->getValue(), VT);
287 } else {
288 // Canonicalize all constant ints to be unsigned.
289 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
290 }
291
292 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
293 std::map<const AllocaInst*, int>::iterator SI =
294 FuncInfo.StaticAllocaMap.find(AI);
295 if (SI != FuncInfo.StaticAllocaMap.end())
296 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
297 }
298
299 std::map<const Value*, unsigned>::const_iterator VMI =
300 FuncInfo.ValueMap.find(V);
301 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000302
Chris Lattner33182322005-08-16 21:55:35 +0000303 unsigned InReg = VMI->second;
304
305 // If this type is not legal, make it so now.
306 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
307
308 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
309 if (DestVT < VT) {
310 // Source must be expanded. This input value is actually coming from the
311 // register pair VMI->second and VMI->second+1.
312 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
313 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
314 } else {
315 if (DestVT > VT) { // Promotion case
316 if (MVT::isFloatingPoint(VT))
317 N = DAG.getNode(ISD::FP_ROUND, VT, N);
318 else
319 N = DAG.getNode(ISD::TRUNCATE, VT, N);
320 }
321 }
322
323 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000324 }
325
326 const SDOperand &setValue(const Value *V, SDOperand NewN) {
327 SDOperand &N = NodeMap[V];
328 assert(N.Val == 0 && "Already set a value for this node!");
329 return N = NewN;
330 }
331
332 // Terminator instructions.
333 void visitRet(ReturnInst &I);
334 void visitBr(BranchInst &I);
335 void visitUnreachable(UnreachableInst &I) { /* noop */ }
336
337 // These all get lowered before this pass.
338 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
339 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
340 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
341
342 //
Chris Lattner7f9e0782005-08-22 17:28:31 +0000343 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000344 void visitAdd(User &I) {
345 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
346 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000347 void visitSub(User &I);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000348 void visitMul(User &I) {
349 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
350 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000351 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000352 unsigned Opc;
353 const Type *Ty = I.getType();
354 if (Ty->isFloatingPoint())
355 Opc = ISD::FDIV;
356 else if (Ty->isUnsigned())
357 Opc = ISD::UDIV;
358 else
359 Opc = ISD::SDIV;
360 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000361 }
362 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000363 unsigned Opc;
364 const Type *Ty = I.getType();
365 if (Ty->isFloatingPoint())
366 Opc = ISD::FREM;
367 else if (Ty->isUnsigned())
368 Opc = ISD::UREM;
369 else
370 Opc = ISD::SREM;
371 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000372 }
373 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
374 void visitOr (User &I) { visitBinary(I, ISD::OR); }
375 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner7f9e0782005-08-22 17:28:31 +0000376 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000377 void visitShr(User &I) {
Chris Lattner7f9e0782005-08-22 17:28:31 +0000378 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner7a60d912005-01-07 07:47:53 +0000379 }
380
381 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
382 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
383 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
384 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
385 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
386 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
387 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
388
389 void visitGetElementPtr(User &I);
390 void visitCast(User &I);
391 void visitSelect(User &I);
392 //
393
394 void visitMalloc(MallocInst &I);
395 void visitFree(FreeInst &I);
396 void visitAlloca(AllocaInst &I);
397 void visitLoad(LoadInst &I);
398 void visitStore(StoreInst &I);
399 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
400 void visitCall(CallInst &I);
401
Chris Lattner7a60d912005-01-07 07:47:53 +0000402 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000403 void visitVAArg(VAArgInst &I);
404 void visitVAEnd(CallInst &I);
405 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000406 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407
Chris Lattner875def92005-01-11 05:56:49 +0000408 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000409
410 void visitUserOp1(Instruction &I) {
411 assert(0 && "UserOp1 should not exist at instruction selection time!");
412 abort();
413 }
414 void visitUserOp2(Instruction &I) {
415 assert(0 && "UserOp2 should not exist at instruction selection time!");
416 abort();
417 }
418};
419} // end namespace llvm
420
421void SelectionDAGLowering::visitRet(ReturnInst &I) {
422 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000423 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000424 return;
425 }
426
427 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000428 MVT::ValueType TmpVT;
429
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 switch (Op1.getValueType()) {
431 default: assert(0 && "Unknown value type!");
432 case MVT::i1:
433 case MVT::i8:
434 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000435 case MVT::i32:
436 // If this is a machine where 32-bits is legal or expanded, promote to
437 // 32-bits, otherwise, promote to 64-bits.
438 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
439 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000441 TmpVT = MVT::i32;
442
443 // Extend integer types to result type.
444 if (I.getOperand(0)->getType()->isSigned())
445 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
446 else
447 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 break;
449 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 case MVT::i64:
451 case MVT::f64:
452 break; // No extension needed!
453 }
454
Chris Lattner4108bb02005-01-17 19:43:36 +0000455 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000456}
457
458void SelectionDAGLowering::visitBr(BranchInst &I) {
459 // Update machine-CFG edges.
460 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000461
462 // Figure out which block is immediately after the current one.
463 MachineBasicBlock *NextBlock = 0;
464 MachineFunction::iterator BBI = CurMBB;
465 if (++BBI != CurMBB->getParent()->end())
466 NextBlock = BBI;
467
468 if (I.isUnconditional()) {
469 // If this is not a fall-through branch, emit the branch.
470 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000471 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000472 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 } else {
474 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000475
476 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000477 if (Succ1MBB == NextBlock) {
478 // If the condition is false, fall through. This means we should branch
479 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000480 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000481 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000482 } else if (Succ0MBB == NextBlock) {
483 // If the condition is true, fall through. This means we should branch if
484 // the condition is false to Succ #1. Invert the condition first.
485 SDOperand True = DAG.getConstant(1, Cond.getValueType());
486 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000487 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000488 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000490 std::vector<SDOperand> Ops;
491 Ops.push_back(getRoot());
492 Ops.push_back(Cond);
493 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
494 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
495 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000496 }
497 }
498}
499
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000500void SelectionDAGLowering::visitSub(User &I) {
501 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000502 if (I.getType()->isFloatingPoint()) {
503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
504 if (CFP->isExactlyValue(-0.0)) {
505 SDOperand Op2 = getValue(I.getOperand(1));
506 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
507 return;
508 }
509 visitBinary(I, ISD::FSUB);
510 } else {
511 visitBinary(I, ISD::SUB);
512 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000513}
514
Chris Lattner7f9e0782005-08-22 17:28:31 +0000515void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 SDOperand Op1 = getValue(I.getOperand(0));
517 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000518
Chris Lattner7f9e0782005-08-22 17:28:31 +0000519 if (isShift)
Chris Lattnera66403d2005-09-02 00:19:37 +0000520 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner96c26752005-01-19 22:31:21 +0000521
Chris Lattner7a60d912005-01-07 07:47:53 +0000522 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
523}
524
525void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
526 ISD::CondCode UnsignedOpcode) {
527 SDOperand Op1 = getValue(I.getOperand(0));
528 SDOperand Op2 = getValue(I.getOperand(1));
529 ISD::CondCode Opcode = SignedOpcode;
530 if (I.getOperand(0)->getType()->isUnsigned())
531 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000532 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000533}
534
535void SelectionDAGLowering::visitSelect(User &I) {
536 SDOperand Cond = getValue(I.getOperand(0));
537 SDOperand TrueVal = getValue(I.getOperand(1));
538 SDOperand FalseVal = getValue(I.getOperand(2));
539 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
540 TrueVal, FalseVal));
541}
542
543void SelectionDAGLowering::visitCast(User &I) {
544 SDOperand N = getValue(I.getOperand(0));
545 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
546 MVT::ValueType DestTy = TLI.getValueType(I.getType());
547
548 if (N.getValueType() == DestTy) {
549 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000550 } else if (DestTy == MVT::i1) {
551 // Cast to bool is a comparison against zero, not truncation to zero.
552 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
553 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000554 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000555 } else if (isInteger(SrcTy)) {
556 if (isInteger(DestTy)) { // Int -> Int cast
557 if (DestTy < SrcTy) // Truncating cast?
558 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
559 else if (I.getOperand(0)->getType()->isSigned())
560 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
561 else
562 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
563 } else { // Int -> FP cast
564 if (I.getOperand(0)->getType()->isSigned())
565 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
566 else
567 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
568 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000569 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000570 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
571 if (isFloatingPoint(DestTy)) { // FP -> FP cast
572 if (DestTy < SrcTy) // Rounding cast?
573 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
574 else
575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
576 } else { // FP -> Int cast.
577 if (I.getType()->isSigned())
578 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
579 else
580 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
581 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000582 }
583}
584
585void SelectionDAGLowering::visitGetElementPtr(User &I) {
586 SDOperand N = getValue(I.getOperand(0));
587 const Type *Ty = I.getOperand(0)->getType();
588 const Type *UIntPtrTy = TD.getIntPtrType();
589
590 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
591 OI != E; ++OI) {
592 Value *Idx = *OI;
593 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
594 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
595 if (Field) {
596 // N = N + Offset
597 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
598 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000599 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000600 }
601 Ty = StTy->getElementType(Field);
602 } else {
603 Ty = cast<SequentialType>(Ty)->getElementType();
604 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
605 // N = N + Idx * ElementSize;
606 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000607 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
608
609 // If the index is smaller or larger than intptr_t, truncate or extend
610 // it.
611 if (IdxN.getValueType() < Scale.getValueType()) {
612 if (Idx->getType()->isSigned())
613 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
614 else
615 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
616 } else if (IdxN.getValueType() > Scale.getValueType())
617 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
618
619 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner7a60d912005-01-07 07:47:53 +0000620 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
621 }
622 }
623 }
624 setValue(&I, N);
625}
626
627void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
628 // If this is a fixed sized alloca in the entry block of the function,
629 // allocate it statically on the stack.
630 if (FuncInfo.StaticAllocaMap.count(&I))
631 return; // getValue will auto-populate this.
632
633 const Type *Ty = I.getAllocatedType();
634 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
635 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
636
637 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000638 MVT::ValueType IntPtr = TLI.getPointerTy();
639 if (IntPtr < AllocSize.getValueType())
640 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
641 else if (IntPtr > AllocSize.getValueType())
642 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000643
Chris Lattnereccb73d2005-01-22 23:04:37 +0000644 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000645 getIntPtrConstant(TySize));
646
647 // Handle alignment. If the requested alignment is less than or equal to the
648 // stack alignment, ignore it and round the size of the allocation up to the
649 // stack alignment size. If the size is greater than the stack alignment, we
650 // note this in the DYNAMIC_STACKALLOC node.
651 unsigned StackAlign =
652 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
653 if (Align <= StackAlign) {
654 Align = 0;
655 // Add SA-1 to the size.
656 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
657 getIntPtrConstant(StackAlign-1));
658 // Mask out the low bits for alignment purposes.
659 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
660 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
661 }
662
Chris Lattner96c262e2005-05-14 07:29:57 +0000663 std::vector<MVT::ValueType> VTs;
664 VTs.push_back(AllocSize.getValueType());
665 VTs.push_back(MVT::Other);
666 std::vector<SDOperand> Ops;
667 Ops.push_back(getRoot());
668 Ops.push_back(AllocSize);
669 Ops.push_back(getIntPtrConstant(Align));
670 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000671 DAG.setRoot(setValue(&I, DSA).getValue(1));
672
673 // Inform the Frame Information that we have just allocated a variable-sized
674 // object.
675 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
676}
677
678
679void SelectionDAGLowering::visitLoad(LoadInst &I) {
680 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000681
Chris Lattner4d9651c2005-01-17 22:19:26 +0000682 SDOperand Root;
683 if (I.isVolatile())
684 Root = getRoot();
685 else {
686 // Do not serialize non-volatile loads against each other.
687 Root = DAG.getRoot();
688 }
689
Chris Lattnerf5675a02005-05-09 04:08:33 +0000690 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000691 DAG.getSrcValue(I.getOperand(0)));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000692 setValue(&I, L);
693
694 if (I.isVolatile())
695 DAG.setRoot(L.getValue(1));
696 else
697 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000698}
699
700
701void SelectionDAGLowering::visitStore(StoreInst &I) {
702 Value *SrcV = I.getOperand(0);
703 SDOperand Src = getValue(SrcV);
704 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000705 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000706 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000707}
708
709void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000710 const char *RenameFn = 0;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000711 SDOperand Tmp;
Chris Lattner7a60d912005-01-07 07:47:53 +0000712 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000713 if (F->isExternal())
714 switch (F->getIntrinsicID()) {
715 case 0: // Not an LLVM intrinsic.
716 if (F->getName() == "fabs" || F->getName() == "fabsf") {
717 if (I.getNumOperands() == 2 && // Basic sanity checks.
718 I.getOperand(1)->getType()->isFloatingPoint() &&
719 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000720 Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000721 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
722 return;
723 }
724 }
Chris Lattner80026402005-04-30 04:43:14 +0000725 else if (F->getName() == "sin" || F->getName() == "sinf") {
726 if (I.getNumOperands() == 2 && // Basic sanity checks.
727 I.getOperand(1)->getType()->isFloatingPoint() &&
728 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000729 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000730 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
731 return;
732 }
733 }
734 else if (F->getName() == "cos" || F->getName() == "cosf") {
735 if (I.getNumOperands() == 2 && // Basic sanity checks.
736 I.getOperand(1)->getType()->isFloatingPoint() &&
737 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000738 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000739 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
740 return;
741 }
742 }
Chris Lattner0c140002005-04-02 05:26:53 +0000743 break;
744 case Intrinsic::vastart: visitVAStart(I); return;
745 case Intrinsic::vaend: visitVAEnd(I); return;
746 case Intrinsic::vacopy: visitVACopy(I); return;
747 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
748 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000749
Chris Lattner0fd8f9f2005-09-27 22:15:53 +0000750 case Intrinsic::setjmp:
751 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
752 break;
753 case Intrinsic::longjmp:
754 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
755 break;
Chris Lattner0c140002005-04-02 05:26:53 +0000756 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
757 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
758 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukman835702a2005-04-21 22:36:52 +0000759
Chris Lattner20eaeae2005-05-09 20:22:36 +0000760 case Intrinsic::readport:
Chris Lattnere4f71d02005-05-14 13:56:55 +0000761 case Intrinsic::readio: {
762 std::vector<MVT::ValueType> VTs;
763 VTs.push_back(TLI.getValueType(I.getType()));
764 VTs.push_back(MVT::Other);
765 std::vector<SDOperand> Ops;
766 Ops.push_back(getRoot());
767 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattner20eaeae2005-05-09 20:22:36 +0000768 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattnere4f71d02005-05-14 13:56:55 +0000769 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000770
Chris Lattner20eaeae2005-05-09 20:22:36 +0000771 setValue(&I, Tmp);
772 DAG.setRoot(Tmp.getValue(1));
773 return;
Chris Lattnere4f71d02005-05-14 13:56:55 +0000774 }
Chris Lattner20eaeae2005-05-09 20:22:36 +0000775 case Intrinsic::writeport:
776 case Intrinsic::writeio:
777 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
778 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
779 getRoot(), getValue(I.getOperand(1)),
780 getValue(I.getOperand(2))));
781 return;
Chris Lattner78761562005-05-05 17:55:17 +0000782 case Intrinsic::dbg_stoppoint:
783 case Intrinsic::dbg_region_start:
784 case Intrinsic::dbg_region_end:
785 case Intrinsic::dbg_func_start:
786 case Intrinsic::dbg_declare:
787 if (I.getType() != Type::VoidTy)
788 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
789 return;
790
Chris Lattner0c140002005-04-02 05:26:53 +0000791 case Intrinsic::isunordered:
Chris Lattnerd47675e2005-08-09 20:20:18 +0000792 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
793 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattner0c140002005-04-02 05:26:53 +0000794 return;
Chris Lattner80026402005-04-30 04:43:14 +0000795
796 case Intrinsic::sqrt:
797 setValue(&I, DAG.getNode(ISD::FSQRT,
798 getValue(I.getOperand(1)).getValueType(),
799 getValue(I.getOperand(1))));
800 return;
801
Chris Lattner20eaeae2005-05-09 20:22:36 +0000802 case Intrinsic::pcmarker:
803 Tmp = getValue(I.getOperand(1));
804 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattner0c140002005-04-02 05:26:53 +0000805 return;
Andrew Lenharth5e177822005-05-03 17:19:30 +0000806 case Intrinsic::cttz:
807 setValue(&I, DAG.getNode(ISD::CTTZ,
808 getValue(I.getOperand(1)).getValueType(),
809 getValue(I.getOperand(1))));
810 return;
811 case Intrinsic::ctlz:
812 setValue(&I, DAG.getNode(ISD::CTLZ,
813 getValue(I.getOperand(1)).getValueType(),
814 getValue(I.getOperand(1))));
815 return;
816 case Intrinsic::ctpop:
817 setValue(&I, DAG.getNode(ISD::CTPOP,
818 getValue(I.getOperand(1)).getValueType(),
819 getValue(I.getOperand(1))));
820 return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000821 default:
822 std::cerr << I;
823 assert(0 && "This intrinsic is not implemented yet!");
824 return;
Chris Lattner0c140002005-04-02 05:26:53 +0000825 }
Misha Brukman835702a2005-04-21 22:36:52 +0000826
Chris Lattner18d2b342005-01-08 22:48:57 +0000827 SDOperand Callee;
828 if (!RenameFn)
829 Callee = getValue(I.getOperand(0));
830 else
831 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000832 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukman835702a2005-04-21 22:36:52 +0000833
Chris Lattner7a60d912005-01-07 07:47:53 +0000834 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
835 Value *Arg = I.getOperand(i);
836 SDOperand ArgNode = getValue(Arg);
837 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
838 }
Misha Brukman835702a2005-04-21 22:36:52 +0000839
Nate Begemanf6565252005-03-26 01:29:23 +0000840 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
841 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000842
Chris Lattner1f45cd72005-01-08 19:26:18 +0000843 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000844 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000845 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000846 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000847 setValue(&I, Result.first);
848 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000849}
850
851void SelectionDAGLowering::visitMalloc(MallocInst &I) {
852 SDOperand Src = getValue(I.getOperand(0));
853
854 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000855
856 if (IntPtr < Src.getValueType())
857 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
858 else if (IntPtr > Src.getValueType())
859 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000860
861 // Scale the source by the type size.
862 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
863 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
864 Src, getIntPtrConstant(ElementSize));
865
866 std::vector<std::pair<SDOperand, const Type*> > Args;
867 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000868
869 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000870 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000871 DAG.getExternalSymbol("malloc", IntPtr),
872 Args, DAG);
873 setValue(&I, Result.first); // Pointers always fit in registers
874 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000875}
876
877void SelectionDAGLowering::visitFree(FreeInst &I) {
878 std::vector<std::pair<SDOperand, const Type*> > Args;
879 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
880 TLI.getTargetData().getIntPtrType()));
881 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000882 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000883 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000884 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
885 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000886}
887
Chris Lattner13d7c252005-08-26 20:54:47 +0000888// InsertAtEndOfBasicBlock - This method should be implemented by targets that
889// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
890// instructions are special in various ways, which require special support to
891// insert. The specified MachineInstr is created but not inserted into any
892// basic blocks, and the scheduler passes ownership of it to this method.
893MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
894 MachineBasicBlock *MBB) {
895 std::cerr << "If a target marks an instruction with "
896 "'usesCustomDAGSchedInserter', it must implement "
897 "TargetLowering::InsertAtEndOfBasicBlock!\n";
898 abort();
899 return 0;
900}
901
Chris Lattnerf5473e42005-07-05 19:57:53 +0000902SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
903 SDOperand VAListP, Value *VAListV,
904 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000905 // We have no sane default behavior, just emit a useful error message and bail
906 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000907 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000908 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +0000909 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +0000910}
911
Chris Lattnerf5473e42005-07-05 19:57:53 +0000912SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +0000913 SelectionDAG &DAG) {
914 // Default to a noop.
915 return Chain;
916}
917
Chris Lattnerf5473e42005-07-05 19:57:53 +0000918SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
919 SDOperand SrcP, Value *SrcV,
920 SDOperand DestP, Value *DestV,
921 SelectionDAG &DAG) {
922 // Default to copying the input list.
923 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
924 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +0000925 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000926 Val, DestP, DAG.getSrcValue(DestV));
927 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +0000928}
929
930std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +0000931TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
932 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000933 // We have no sane default behavior, just emit a useful error message and bail
934 // out.
935 std::cerr << "Variable arguments handling not implemented on this target!\n";
936 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000937 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000938}
939
940
941void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000942 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
943 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +0000944}
945
946void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
947 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +0000948 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000949 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000950 setValue(&I, Result.first);
951 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000952}
953
954void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000955 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000956 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000957}
958
959void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000960 SDOperand Result =
961 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
962 getValue(I.getOperand(1)), I.getOperand(1), DAG);
963 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +0000964}
965
Chris Lattner58cfd792005-01-09 00:00:49 +0000966
967// It is always conservatively correct for llvm.returnaddress and
968// llvm.frameaddress to return 0.
969std::pair<SDOperand, SDOperand>
970TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
971 unsigned Depth, SelectionDAG &DAG) {
972 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000973}
974
Chris Lattner29dcc712005-05-14 05:50:48 +0000975SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +0000976 assert(0 && "LowerOperation not implemented for this target!");
977 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000978 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000979}
980
Chris Lattner58cfd792005-01-09 00:00:49 +0000981void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
982 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
983 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000984 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000985 setValue(&I, Result.first);
986 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000987}
988
Chris Lattner875def92005-01-11 05:56:49 +0000989void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
990 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +0000991 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +0000992 Ops.push_back(getValue(I.getOperand(1)));
993 Ops.push_back(getValue(I.getOperand(2)));
994 Ops.push_back(getValue(I.getOperand(3)));
995 Ops.push_back(getValue(I.getOperand(4)));
996 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000997}
998
Chris Lattner875def92005-01-11 05:56:49 +0000999//===----------------------------------------------------------------------===//
1000// SelectionDAGISel code
1001//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001002
1003unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1004 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1005}
1006
Chris Lattnerc9950c12005-08-17 06:37:43 +00001007void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001008 // FIXME: we only modify the CFG to split critical edges. This
1009 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001010}
Chris Lattner7a60d912005-01-07 07:47:53 +00001011
1012
1013bool SelectionDAGISel::runOnFunction(Function &Fn) {
1014 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1015 RegMap = MF.getSSARegMap();
1016 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1017
Chris Lattnerc9950c12005-08-17 06:37:43 +00001018 // First pass, split all critical edges for PHI nodes with incoming values
1019 // that are constants, this way the load of the constant into a vreg will not
1020 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001021 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1022 PHINode *PN;
1023 for (BasicBlock::iterator BBI = BB->begin();
1024 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1026 if (isa<Constant>(PN->getIncomingValue(i)))
1027 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1028 }
Chris Lattnerc9950c12005-08-17 06:37:43 +00001029
Chris Lattner7a60d912005-01-07 07:47:53 +00001030 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1031
1032 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1033 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001034
Chris Lattner7a60d912005-01-07 07:47:53 +00001035 return true;
1036}
1037
1038
Chris Lattner718b5c22005-01-13 17:59:43 +00001039SDOperand SelectionDAGISel::
1040CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001041 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001042 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001043 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001044 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001045
1046 // If this type is not legal, we must make sure to not create an invalid
1047 // register use.
1048 MVT::ValueType SrcVT = Op.getValueType();
1049 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1050 SelectionDAG &DAG = SDL.DAG;
1051 if (SrcVT == DestVT) {
1052 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1053 } else if (SrcVT < DestVT) {
1054 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001055 if (MVT::isFloatingPoint(SrcVT))
1056 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1057 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001058 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001059 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1060 } else {
1061 // The src value is expanded into multiple registers.
1062 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1063 Op, DAG.getConstant(0, MVT::i32));
1064 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1065 Op, DAG.getConstant(1, MVT::i32));
1066 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1067 return DAG.getCopyToReg(Op, Reg+1, Hi);
1068 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001069}
1070
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001071/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1072/// single basic block, return that block. Otherwise, return a null pointer.
1073static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1074 if (A->use_empty()) return 0;
1075 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1076 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1077 ++UI)
1078 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1079 return 0; // Disagreement among the users?
Chris Lattner0c56a542005-02-17 19:40:32 +00001080
1081 // Okay, there is a single BB user. Only permit this optimization if this is
1082 // the entry block, otherwise, we might sink argument loads into loops and
1083 // stuff. Later, when we have global instruction selection, this won't be an
1084 // issue clearly.
1085 if (BB == BB->getParent()->begin())
1086 return BB;
1087 return 0;
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001088}
1089
Chris Lattner16f64df2005-01-17 17:15:02 +00001090void SelectionDAGISel::
1091LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1092 std::vector<SDOperand> &UnorderedChains) {
1093 // If this is the entry block, emit arguments.
1094 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001095 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner16f64df2005-01-17 17:15:02 +00001096
1097 if (BB == &F.front()) {
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001098 SDOperand OldRoot = SDL.DAG.getRoot();
1099
Chris Lattner16f64df2005-01-17 17:15:02 +00001100 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1101
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001102 // If there were side effects accessing the argument list, do not do
1103 // anything special.
1104 if (OldRoot != SDL.DAG.getRoot()) {
1105 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +00001106 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1107 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001108 if (!AI->use_empty()) {
1109 SDL.setValue(AI, Args[a]);
Chris Lattnere7a29982005-08-26 22:49:59 +00001110
Chris Lattnera66403d2005-09-02 00:19:37 +00001111 SDOperand Copy =
1112 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1113 UnorderedChains.push_back(Copy);
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001114 }
1115 } else {
1116 // Otherwise, if any argument is only accessed in a single basic block,
1117 // emit that argument only to that basic block.
1118 unsigned a = 0;
Chris Lattner5ca31d92005-03-30 01:10:47 +00001119 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1120 AI != E; ++AI,++a)
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001121 if (!AI->use_empty()) {
1122 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1123 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1124 std::make_pair(AI, a)));
1125 } else {
1126 SDL.setValue(AI, Args[a]);
Misha Brukman835702a2005-04-21 22:36:52 +00001127 SDOperand Copy =
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001128 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1129 UnorderedChains.push_back(Copy);
1130 }
1131 }
1132 }
Chris Lattnerd0b0ecc2005-05-13 07:33:32 +00001133
Chris Lattnerd4382f02005-09-13 19:30:54 +00001134 // Next, if the function has live ins that need to be copied into vregs,
1135 // emit the copies now, into the top of the block.
1136 MachineFunction &MF = SDL.DAG.getMachineFunction();
1137 if (MF.livein_begin() != MF.livein_end()) {
1138 SSARegMap *RegMap = MF.getSSARegMap();
1139 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1140 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1141 E = MF.livein_end(); LI != E; ++LI)
1142 if (LI->second)
1143 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1144 LI->first, RegMap->getRegClass(LI->second));
1145 }
1146
1147 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattnerd0b0ecc2005-05-13 07:33:32 +00001148 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001149 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001150
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001151 // See if there are any block-local arguments that need to be emitted in this
1152 // block.
1153
1154 if (!FuncInfo.BlockLocalArguments.empty()) {
1155 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1156 FuncInfo.BlockLocalArguments.lower_bound(BB);
1157 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1158 // Lower the arguments into this block.
1159 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukman835702a2005-04-21 22:36:52 +00001160
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001161 // Set up the value mapping for the local arguments.
1162 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1163 ++BLAI)
1164 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukman835702a2005-04-21 22:36:52 +00001165
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001166 // Any dead arguments will just be ignored here.
1167 }
Chris Lattner16f64df2005-01-17 17:15:02 +00001168 }
1169}
1170
1171
Chris Lattner7a60d912005-01-07 07:47:53 +00001172void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1173 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1174 FunctionLoweringInfo &FuncInfo) {
1175 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001176
1177 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001178
Chris Lattner16f64df2005-01-17 17:15:02 +00001179 // Lower any arguments needed in this block.
1180 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001181
1182 BB = FuncInfo.MBBMap[LLVMBB];
1183 SDL.setCurrentBasicBlock(BB);
1184
1185 // Lower all of the non-terminator instructions.
1186 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1187 I != E; ++I)
1188 SDL.visit(*I);
1189
1190 // Ensure that all instructions which are used outside of their defining
1191 // blocks are available as virtual registers.
1192 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001193 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001194 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001195 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001196 UnorderedChains.push_back(
1197 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001198 }
1199
1200 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1201 // ensure constants are generated when needed. Remember the virtual registers
1202 // that need to be added to the Machine PHI nodes as input. We cannot just
1203 // directly add them, because expansion might result in multiple MBB's for one
1204 // BB. As such, the start of the BB might correspond to a different MBB than
1205 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001206 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001207
1208 // Emit constants only once even if used by multiple PHI nodes.
1209 std::map<Constant*, unsigned> ConstantsOut;
1210
1211 // Check successor nodes PHI nodes that expect a constant to be available from
1212 // this block.
1213 TerminatorInst *TI = LLVMBB->getTerminator();
1214 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1215 BasicBlock *SuccBB = TI->getSuccessor(succ);
1216 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1217 PHINode *PN;
1218
1219 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1220 // nodes and Machine PHI nodes, but the incoming operands have not been
1221 // emitted yet.
1222 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001223 (PN = dyn_cast<PHINode>(I)); ++I)
1224 if (!PN->use_empty()) {
1225 unsigned Reg;
1226 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1227 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1228 unsigned &RegOut = ConstantsOut[C];
1229 if (RegOut == 0) {
1230 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001231 UnorderedChains.push_back(
1232 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001233 }
1234 Reg = RegOut;
1235 } else {
1236 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001237 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001238 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001239 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1240 "Didn't codegen value into a register!??");
1241 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001242 UnorderedChains.push_back(
1243 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001244 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001245 }
Misha Brukman835702a2005-04-21 22:36:52 +00001246
Chris Lattner8ea875f2005-01-07 21:34:19 +00001247 // Remember that this register needs to added to the machine PHI node as
1248 // the input for this MBB.
1249 unsigned NumElements =
1250 TLI.getNumElements(TLI.getValueType(PN->getType()));
1251 for (unsigned i = 0, e = NumElements; i != e; ++i)
1252 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001253 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001254 }
1255 ConstantsOut.clear();
1256
Chris Lattner718b5c22005-01-13 17:59:43 +00001257 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001258 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001259 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001260 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1261 }
1262
Chris Lattner7a60d912005-01-07 07:47:53 +00001263 // Lower the terminator after the copies are emitted.
1264 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001265
1266 // Make sure the root of the DAG is up-to-date.
1267 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001268}
1269
1270void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1271 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001272 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001273 CurDAG = &DAG;
1274 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1275
1276 // First step, lower LLVM code to some DAG. This DAG may use operations and
1277 // types that are not supported by the target.
1278 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1279
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001280 // Run the DAG combiner in pre-legalize mode.
1281 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001282
Chris Lattner7a60d912005-01-07 07:47:53 +00001283 DEBUG(std::cerr << "Lowered selection DAG:\n");
1284 DEBUG(DAG.dump());
1285
1286 // Second step, hack on the DAG until it only uses operations and types that
1287 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001288 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001289
1290 DEBUG(std::cerr << "Legalized selection DAG:\n");
1291 DEBUG(DAG.dump());
1292
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001293 // Run the DAG combiner in post-legalize mode.
1294 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001295
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001296 if (ViewDAGs) DAG.viewGraph();
1297
Chris Lattner5ca31d92005-03-30 01:10:47 +00001298 // Third, instruction select all of the operations to machine code, adding the
1299 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001300 InstructionSelectBasicBlock(DAG);
1301
Chris Lattner7a60d912005-01-07 07:47:53 +00001302 DEBUG(std::cerr << "Selected machine code:\n");
1303 DEBUG(BB->dump());
1304
Chris Lattner5ca31d92005-03-30 01:10:47 +00001305 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001306 // PHI nodes in successors.
1307 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1308 MachineInstr *PHI = PHINodesToUpdate[i].first;
1309 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1310 "This is not a machine PHI node that we are updating!");
1311 PHI->addRegOperand(PHINodesToUpdate[i].second);
1312 PHI->addMachineBasicBlockOperand(BB);
1313 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001314
1315 // Finally, add the CFG edges from the last selected MBB to the successor
1316 // MBBs.
1317 TerminatorInst *TI = LLVMBB->getTerminator();
1318 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1319 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1320 BB->addSuccessor(Succ0MBB);
1321 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001322}