blob: 3b5ef32e3c34f856566a8167ad24cb09e63a5ece [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
75 unsigned MakeReg(MVT::ValueType VT) {
76 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
77 }
Misha Brukman835702a2005-04-21 22:36:52 +000078
Chris Lattner7a60d912005-01-07 07:47:53 +000079 unsigned CreateRegForValue(const Value *V) {
80 MVT::ValueType VT = TLI.getValueType(V->getType());
81 // The common case is that we will only create one register for this
82 // value. If we have that case, create and return the virtual register.
83 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000084 if (NV == 1) {
85 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000086 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000087 }
Misha Brukman835702a2005-04-21 22:36:52 +000088
Chris Lattner7a60d912005-01-07 07:47:53 +000089 // If this value is represented with multiple target registers, make sure
90 // to create enough consequtive registers of the right (smaller) type.
91 unsigned NT = VT-1; // Find the type to use.
92 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
93 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000094
Chris Lattner7a60d912005-01-07 07:47:53 +000095 unsigned R = MakeReg((MVT::ValueType)NT);
96 for (unsigned i = 1; i != NV; ++i)
97 MakeReg((MVT::ValueType)NT);
98 return R;
99 }
Misha Brukman835702a2005-04-21 22:36:52 +0000100
Chris Lattner7a60d912005-01-07 07:47:53 +0000101 unsigned InitializeRegForValue(const Value *V) {
102 unsigned &R = ValueMap[V];
103 assert(R == 0 && "Already initialized this value register!");
104 return R = CreateRegForValue(V);
105 }
106 };
107}
108
109/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
110/// PHI nodes or outside of the basic block that defines it.
111static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
112 if (isa<PHINode>(I)) return true;
113 BasicBlock *BB = I->getParent();
114 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
115 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
116 return true;
117 return false;
118}
119
Chris Lattner6871b232005-10-30 19:42:35 +0000120/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
121/// entry block, return true.
122static bool isOnlyUsedInEntryBlock(Argument *A) {
123 BasicBlock *Entry = A->getParent()->begin();
124 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
125 if (cast<Instruction>(*UI)->getParent() != Entry)
126 return false; // Use not in entry block.
127 return true;
128}
129
Chris Lattner7a60d912005-01-07 07:47:53 +0000130FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000131 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000132 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
133
Chris Lattner6871b232005-10-30 19:42:35 +0000134 // Create a vreg for each argument register that is not dead and is used
135 // outside of the entry block for the function.
136 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137 AI != E; ++AI)
138 if (!isOnlyUsedInEntryBlock(AI))
139 InitializeRegForValue(AI);
140
Chris Lattner7a60d912005-01-07 07:47:53 +0000141 // Initialize the mapping of values to registers. This is only set up for
142 // instruction values that are used outside of the block that defines
143 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000144 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000145 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
146 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
147 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
148 const Type *Ty = AI->getAllocatedType();
149 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
150 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
Chris Lattnercbefe722005-05-13 23:14:17 +0000151
152 // If the alignment of the value is smaller than the size of the value,
153 // and if the size of the value is particularly small (<= 8 bytes),
154 // round up to the size of the value for potentially better performance.
155 //
156 // FIXME: This could be made better with a preferred alignment hook in
157 // TargetData. It serves primarily to 8-byte align doubles for X86.
158 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000159 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000160 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000163 }
164
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000165 for (; BB != EB; ++BB)
166 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000167 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
168 if (!isa<AllocaInst>(I) ||
169 !StaticAllocaMap.count(cast<AllocaInst>(I)))
170 InitializeRegForValue(I);
171
172 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
173 // also creates the initial PHI MachineInstrs, though none of the input
174 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000175 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000176 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
177 MBBMap[BB] = MBB;
178 MF.getBasicBlockList().push_back(MBB);
179
180 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
181 // appropriate.
182 PHINode *PN;
183 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000184 (PN = dyn_cast<PHINode>(I)); ++I)
185 if (!PN->use_empty()) {
186 unsigned NumElements =
187 TLI.getNumElements(TLI.getValueType(PN->getType()));
188 unsigned PHIReg = ValueMap[PN];
189 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
190 for (unsigned i = 0; i != NumElements; ++i)
191 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
192 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 }
194}
195
196
197
198//===----------------------------------------------------------------------===//
199/// SelectionDAGLowering - This is the common target-independent lowering
200/// implementation that is parameterized by a TargetLowering object.
201/// Also, targets can overload any lowering method.
202///
203namespace llvm {
204class SelectionDAGLowering {
205 MachineBasicBlock *CurMBB;
206
207 std::map<const Value*, SDOperand> NodeMap;
208
Chris Lattner4d9651c2005-01-17 22:19:26 +0000209 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
210 /// them up and then emit token factor nodes when possible. This allows us to
211 /// get simple disambiguation between loads without worrying about alias
212 /// analysis.
213 std::vector<SDOperand> PendingLoads;
214
Chris Lattner7a60d912005-01-07 07:47:53 +0000215public:
216 // TLI - This is information that describes the available target features we
217 // need for lowering. This indicates when operations are unavailable,
218 // implemented with a libcall, etc.
219 TargetLowering &TLI;
220 SelectionDAG &DAG;
221 const TargetData &TD;
222
223 /// FuncInfo - Information about the function as a whole.
224 ///
225 FunctionLoweringInfo &FuncInfo;
226
227 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000228 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000229 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
230 FuncInfo(funcinfo) {
231 }
232
Chris Lattner4108bb02005-01-17 19:43:36 +0000233 /// getRoot - Return the current virtual root of the Selection DAG.
234 ///
235 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000236 if (PendingLoads.empty())
237 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000238
Chris Lattner4d9651c2005-01-17 22:19:26 +0000239 if (PendingLoads.size() == 1) {
240 SDOperand Root = PendingLoads[0];
241 DAG.setRoot(Root);
242 PendingLoads.clear();
243 return Root;
244 }
245
246 // Otherwise, we have to make a token factor node.
247 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
248 PendingLoads.clear();
249 DAG.setRoot(Root);
250 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000251 }
252
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 void visit(Instruction &I) { visit(I.getOpcode(), I); }
254
255 void visit(unsigned Opcode, User &I) {
256 switch (Opcode) {
257 default: assert(0 && "Unknown instruction type encountered!");
258 abort();
259 // Build the switch statement using the Instruction.def file.
260#define HANDLE_INST(NUM, OPCODE, CLASS) \
261 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
262#include "llvm/Instruction.def"
263 }
264 }
265
266 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
267
268
269 SDOperand getIntPtrConstant(uint64_t Val) {
270 return DAG.getConstant(Val, TLI.getPointerTy());
271 }
272
273 SDOperand getValue(const Value *V) {
274 SDOperand &N = NodeMap[V];
275 if (N.Val) return N;
276
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
279 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
280 visit(CE->getOpcode(), *CE);
281 assert(N.Val && "visit didn't populate the ValueMap!");
282 return N;
283 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
284 return N = DAG.getGlobalAddress(GV, VT);
285 } else if (isa<ConstantPointerNull>(C)) {
286 return N = DAG.getConstant(0, TLI.getPointerTy());
287 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000288 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000289 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
290 return N = DAG.getConstantFP(CFP->getValue(), VT);
291 } else {
292 // Canonicalize all constant ints to be unsigned.
293 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
294 }
295
296 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
297 std::map<const AllocaInst*, int>::iterator SI =
298 FuncInfo.StaticAllocaMap.find(AI);
299 if (SI != FuncInfo.StaticAllocaMap.end())
300 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
301 }
302
303 std::map<const Value*, unsigned>::const_iterator VMI =
304 FuncInfo.ValueMap.find(V);
305 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000306
Chris Lattner33182322005-08-16 21:55:35 +0000307 unsigned InReg = VMI->second;
308
309 // If this type is not legal, make it so now.
310 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
311
312 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
313 if (DestVT < VT) {
314 // Source must be expanded. This input value is actually coming from the
315 // register pair VMI->second and VMI->second+1.
316 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
317 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
318 } else {
319 if (DestVT > VT) { // Promotion case
320 if (MVT::isFloatingPoint(VT))
321 N = DAG.getNode(ISD::FP_ROUND, VT, N);
322 else
323 N = DAG.getNode(ISD::TRUNCATE, VT, N);
324 }
325 }
326
327 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000328 }
329
330 const SDOperand &setValue(const Value *V, SDOperand NewN) {
331 SDOperand &N = NodeMap[V];
332 assert(N.Val == 0 && "Already set a value for this node!");
333 return N = NewN;
334 }
335
336 // Terminator instructions.
337 void visitRet(ReturnInst &I);
338 void visitBr(BranchInst &I);
339 void visitUnreachable(UnreachableInst &I) { /* noop */ }
340
341 // These all get lowered before this pass.
342 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
343 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
344 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
345
346 //
Chris Lattner7f9e0782005-08-22 17:28:31 +0000347 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000348 void visitAdd(User &I) {
349 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
350 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000351 void visitSub(User &I);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000352 void visitMul(User &I) {
353 visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
354 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000355 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000356 unsigned Opc;
357 const Type *Ty = I.getType();
358 if (Ty->isFloatingPoint())
359 Opc = ISD::FDIV;
360 else if (Ty->isUnsigned())
361 Opc = ISD::UDIV;
362 else
363 Opc = ISD::SDIV;
364 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000365 }
366 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000367 unsigned Opc;
368 const Type *Ty = I.getType();
369 if (Ty->isFloatingPoint())
370 Opc = ISD::FREM;
371 else if (Ty->isUnsigned())
372 Opc = ISD::UREM;
373 else
374 Opc = ISD::SREM;
375 visitBinary(I, Opc);
Chris Lattner7a60d912005-01-07 07:47:53 +0000376 }
377 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
378 void visitOr (User &I) { visitBinary(I, ISD::OR); }
379 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner7f9e0782005-08-22 17:28:31 +0000380 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000381 void visitShr(User &I) {
Chris Lattner7f9e0782005-08-22 17:28:31 +0000382 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner7a60d912005-01-07 07:47:53 +0000383 }
384
385 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
386 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
387 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
388 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
389 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
390 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
391 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
392
393 void visitGetElementPtr(User &I);
394 void visitCast(User &I);
395 void visitSelect(User &I);
396 //
397
398 void visitMalloc(MallocInst &I);
399 void visitFree(FreeInst &I);
400 void visitAlloca(AllocaInst &I);
401 void visitLoad(LoadInst &I);
402 void visitStore(StoreInst &I);
403 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
404 void visitCall(CallInst &I);
405
Chris Lattner7a60d912005-01-07 07:47:53 +0000406 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000407 void visitVAArg(VAArgInst &I);
408 void visitVAEnd(CallInst &I);
409 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000410 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000411
Chris Lattner875def92005-01-11 05:56:49 +0000412 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000413
414 void visitUserOp1(Instruction &I) {
415 assert(0 && "UserOp1 should not exist at instruction selection time!");
416 abort();
417 }
418 void visitUserOp2(Instruction &I) {
419 assert(0 && "UserOp2 should not exist at instruction selection time!");
420 abort();
421 }
422};
423} // end namespace llvm
424
425void SelectionDAGLowering::visitRet(ReturnInst &I) {
426 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000427 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 return;
429 }
430
431 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000432 MVT::ValueType TmpVT;
433
Chris Lattner7a60d912005-01-07 07:47:53 +0000434 switch (Op1.getValueType()) {
435 default: assert(0 && "Unknown value type!");
436 case MVT::i1:
437 case MVT::i8:
438 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000439 case MVT::i32:
440 // If this is a machine where 32-bits is legal or expanded, promote to
441 // 32-bits, otherwise, promote to 64-bits.
442 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
443 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000444 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000445 TmpVT = MVT::i32;
446
447 // Extend integer types to result type.
448 if (I.getOperand(0)->getType()->isSigned())
449 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
450 else
451 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000452 break;
453 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000454 case MVT::i64:
455 case MVT::f64:
456 break; // No extension needed!
457 }
Nate Begeman78afac22005-10-18 23:23:37 +0000458 // Allow targets to lower this further to meet ABI requirements
459 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000460}
461
462void SelectionDAGLowering::visitBr(BranchInst &I) {
463 // Update machine-CFG edges.
464 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000465
466 // Figure out which block is immediately after the current one.
467 MachineBasicBlock *NextBlock = 0;
468 MachineFunction::iterator BBI = CurMBB;
469 if (++BBI != CurMBB->getParent()->end())
470 NextBlock = BBI;
471
472 if (I.isUnconditional()) {
473 // If this is not a fall-through branch, emit the branch.
474 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000475 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000476 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000477 } else {
478 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000479
480 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000481 if (Succ1MBB == NextBlock) {
482 // If the condition is false, fall through. This means we should branch
483 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000484 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000485 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000486 } else if (Succ0MBB == NextBlock) {
487 // If the condition is true, fall through. This means we should branch if
488 // the condition is false to Succ #1. Invert the condition first.
489 SDOperand True = DAG.getConstant(1, Cond.getValueType());
490 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000491 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000492 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000494 std::vector<SDOperand> Ops;
495 Ops.push_back(getRoot());
496 Ops.push_back(Cond);
497 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
498 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
499 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
501 }
502}
503
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000504void SelectionDAGLowering::visitSub(User &I) {
505 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000506 if (I.getType()->isFloatingPoint()) {
507 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
508 if (CFP->isExactlyValue(-0.0)) {
509 SDOperand Op2 = getValue(I.getOperand(1));
510 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
511 return;
512 }
513 visitBinary(I, ISD::FSUB);
514 } else {
515 visitBinary(I, ISD::SUB);
516 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000517}
518
Chris Lattner7f9e0782005-08-22 17:28:31 +0000519void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 SDOperand Op1 = getValue(I.getOperand(0));
521 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000522
Chris Lattner7f9e0782005-08-22 17:28:31 +0000523 if (isShift)
Chris Lattnera66403d2005-09-02 00:19:37 +0000524 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner96c26752005-01-19 22:31:21 +0000525
Chris Lattner7a60d912005-01-07 07:47:53 +0000526 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
527}
528
529void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
530 ISD::CondCode UnsignedOpcode) {
531 SDOperand Op1 = getValue(I.getOperand(0));
532 SDOperand Op2 = getValue(I.getOperand(1));
533 ISD::CondCode Opcode = SignedOpcode;
534 if (I.getOperand(0)->getType()->isUnsigned())
535 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000536 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000537}
538
539void SelectionDAGLowering::visitSelect(User &I) {
540 SDOperand Cond = getValue(I.getOperand(0));
541 SDOperand TrueVal = getValue(I.getOperand(1));
542 SDOperand FalseVal = getValue(I.getOperand(2));
543 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
544 TrueVal, FalseVal));
545}
546
547void SelectionDAGLowering::visitCast(User &I) {
548 SDOperand N = getValue(I.getOperand(0));
549 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
550 MVT::ValueType DestTy = TLI.getValueType(I.getType());
551
552 if (N.getValueType() == DestTy) {
553 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000554 } else if (DestTy == MVT::i1) {
555 // Cast to bool is a comparison against zero, not truncation to zero.
556 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
557 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000558 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000559 } else if (isInteger(SrcTy)) {
560 if (isInteger(DestTy)) { // Int -> Int cast
561 if (DestTy < SrcTy) // Truncating cast?
562 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
563 else if (I.getOperand(0)->getType()->isSigned())
564 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
565 else
566 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
567 } else { // Int -> FP cast
568 if (I.getOperand(0)->getType()->isSigned())
569 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
570 else
571 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
572 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000573 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000574 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
575 if (isFloatingPoint(DestTy)) { // FP -> FP cast
576 if (DestTy < SrcTy) // Rounding cast?
577 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
578 else
579 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
580 } else { // FP -> Int cast.
581 if (I.getType()->isSigned())
582 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
583 else
584 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
585 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000586 }
587}
588
589void SelectionDAGLowering::visitGetElementPtr(User &I) {
590 SDOperand N = getValue(I.getOperand(0));
591 const Type *Ty = I.getOperand(0)->getType();
592 const Type *UIntPtrTy = TD.getIntPtrType();
593
594 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
595 OI != E; ++OI) {
596 Value *Idx = *OI;
597 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
598 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
599 if (Field) {
600 // N = N + Offset
601 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
602 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000603 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000604 }
605 Ty = StTy->getElementType(Field);
606 } else {
607 Ty = cast<SequentialType>(Ty)->getElementType();
608 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
609 // N = N + Idx * ElementSize;
610 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner19a83992005-01-07 21:56:57 +0000611 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
612
613 // If the index is smaller or larger than intptr_t, truncate or extend
614 // it.
615 if (IdxN.getValueType() < Scale.getValueType()) {
616 if (Idx->getType()->isSigned())
617 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
618 else
619 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
620 } else if (IdxN.getValueType() > Scale.getValueType())
621 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
622
623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner7a60d912005-01-07 07:47:53 +0000624 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
625 }
626 }
627 }
628 setValue(&I, N);
629}
630
631void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
632 // If this is a fixed sized alloca in the entry block of the function,
633 // allocate it statically on the stack.
634 if (FuncInfo.StaticAllocaMap.count(&I))
635 return; // getValue will auto-populate this.
636
637 const Type *Ty = I.getAllocatedType();
638 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
639 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
640
641 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000642 MVT::ValueType IntPtr = TLI.getPointerTy();
643 if (IntPtr < AllocSize.getValueType())
644 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
645 else if (IntPtr > AllocSize.getValueType())
646 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000647
Chris Lattnereccb73d2005-01-22 23:04:37 +0000648 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000649 getIntPtrConstant(TySize));
650
651 // Handle alignment. If the requested alignment is less than or equal to the
652 // stack alignment, ignore it and round the size of the allocation up to the
653 // stack alignment size. If the size is greater than the stack alignment, we
654 // note this in the DYNAMIC_STACKALLOC node.
655 unsigned StackAlign =
656 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
657 if (Align <= StackAlign) {
658 Align = 0;
659 // Add SA-1 to the size.
660 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
661 getIntPtrConstant(StackAlign-1));
662 // Mask out the low bits for alignment purposes.
663 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
664 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
665 }
666
Chris Lattner96c262e2005-05-14 07:29:57 +0000667 std::vector<MVT::ValueType> VTs;
668 VTs.push_back(AllocSize.getValueType());
669 VTs.push_back(MVT::Other);
670 std::vector<SDOperand> Ops;
671 Ops.push_back(getRoot());
672 Ops.push_back(AllocSize);
673 Ops.push_back(getIntPtrConstant(Align));
674 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000675 DAG.setRoot(setValue(&I, DSA).getValue(1));
676
677 // Inform the Frame Information that we have just allocated a variable-sized
678 // object.
679 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
680}
681
682
683void SelectionDAGLowering::visitLoad(LoadInst &I) {
684 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000685
Chris Lattner4d9651c2005-01-17 22:19:26 +0000686 SDOperand Root;
687 if (I.isVolatile())
688 Root = getRoot();
689 else {
690 // Do not serialize non-volatile loads against each other.
691 Root = DAG.getRoot();
692 }
693
Chris Lattnerf5675a02005-05-09 04:08:33 +0000694 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000695 DAG.getSrcValue(I.getOperand(0)));
Chris Lattner4d9651c2005-01-17 22:19:26 +0000696 setValue(&I, L);
697
698 if (I.isVolatile())
699 DAG.setRoot(L.getValue(1));
700 else
701 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000702}
703
704
705void SelectionDAGLowering::visitStore(StoreInst &I) {
706 Value *SrcV = I.getOperand(0);
707 SDOperand Src = getValue(SrcV);
708 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000709 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000710 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000711}
712
713void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +0000714 const char *RenameFn = 0;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000715 SDOperand Tmp;
Chris Lattner7a60d912005-01-07 07:47:53 +0000716 if (Function *F = I.getCalledFunction())
Chris Lattner0c140002005-04-02 05:26:53 +0000717 if (F->isExternal())
718 switch (F->getIntrinsicID()) {
719 case 0: // Not an LLVM intrinsic.
720 if (F->getName() == "fabs" || F->getName() == "fabsf") {
721 if (I.getNumOperands() == 2 && // Basic sanity checks.
722 I.getOperand(1)->getType()->isFloatingPoint() &&
723 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000724 Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +0000725 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
726 return;
727 }
728 }
Chris Lattner80026402005-04-30 04:43:14 +0000729 else if (F->getName() == "sin" || F->getName() == "sinf") {
730 if (I.getNumOperands() == 2 && // Basic sanity checks.
731 I.getOperand(1)->getType()->isFloatingPoint() &&
732 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000733 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000734 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
735 return;
736 }
737 }
738 else if (F->getName() == "cos" || F->getName() == "cosf") {
739 if (I.getNumOperands() == 2 && // Basic sanity checks.
740 I.getOperand(1)->getType()->isFloatingPoint() &&
741 I.getType() == I.getOperand(1)->getType()) {
Chris Lattner20eaeae2005-05-09 20:22:36 +0000742 Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +0000743 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
744 return;
745 }
746 }
Chris Lattner0c140002005-04-02 05:26:53 +0000747 break;
748 case Intrinsic::vastart: visitVAStart(I); return;
749 case Intrinsic::vaend: visitVAEnd(I); return;
750 case Intrinsic::vacopy: visitVACopy(I); return;
751 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
752 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000753
Chris Lattner0fd8f9f2005-09-27 22:15:53 +0000754 case Intrinsic::setjmp:
755 RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
756 break;
757 case Intrinsic::longjmp:
758 RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
759 break;
Chris Lattner0c140002005-04-02 05:26:53 +0000760 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
761 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
762 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukman835702a2005-04-21 22:36:52 +0000763
Chris Lattner20eaeae2005-05-09 20:22:36 +0000764 case Intrinsic::readport:
Chris Lattnere4f71d02005-05-14 13:56:55 +0000765 case Intrinsic::readio: {
766 std::vector<MVT::ValueType> VTs;
767 VTs.push_back(TLI.getValueType(I.getType()));
768 VTs.push_back(MVT::Other);
769 std::vector<SDOperand> Ops;
770 Ops.push_back(getRoot());
771 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattner20eaeae2005-05-09 20:22:36 +0000772 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattnere4f71d02005-05-14 13:56:55 +0000773 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000774
Chris Lattner20eaeae2005-05-09 20:22:36 +0000775 setValue(&I, Tmp);
776 DAG.setRoot(Tmp.getValue(1));
777 return;
Chris Lattnere4f71d02005-05-14 13:56:55 +0000778 }
Chris Lattner20eaeae2005-05-09 20:22:36 +0000779 case Intrinsic::writeport:
780 case Intrinsic::writeio:
781 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
782 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
783 getRoot(), getValue(I.getOperand(1)),
784 getValue(I.getOperand(2))));
785 return;
Chris Lattner78761562005-05-05 17:55:17 +0000786 case Intrinsic::dbg_stoppoint:
787 case Intrinsic::dbg_region_start:
788 case Intrinsic::dbg_region_end:
789 case Intrinsic::dbg_func_start:
790 case Intrinsic::dbg_declare:
791 if (I.getType() != Type::VoidTy)
792 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
793 return;
794
Chris Lattner0c140002005-04-02 05:26:53 +0000795 case Intrinsic::isunordered:
Chris Lattnerd47675e2005-08-09 20:20:18 +0000796 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
797 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattner0c140002005-04-02 05:26:53 +0000798 return;
Chris Lattner80026402005-04-30 04:43:14 +0000799
800 case Intrinsic::sqrt:
801 setValue(&I, DAG.getNode(ISD::FSQRT,
802 getValue(I.getOperand(1)).getValueType(),
803 getValue(I.getOperand(1))));
804 return;
805
Chris Lattner20eaeae2005-05-09 20:22:36 +0000806 case Intrinsic::pcmarker:
807 Tmp = getValue(I.getOperand(1));
808 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattner0c140002005-04-02 05:26:53 +0000809 return;
Andrew Lenharth5e177822005-05-03 17:19:30 +0000810 case Intrinsic::cttz:
811 setValue(&I, DAG.getNode(ISD::CTTZ,
812 getValue(I.getOperand(1)).getValueType(),
813 getValue(I.getOperand(1))));
814 return;
815 case Intrinsic::ctlz:
816 setValue(&I, DAG.getNode(ISD::CTLZ,
817 getValue(I.getOperand(1)).getValueType(),
818 getValue(I.getOperand(1))));
819 return;
820 case Intrinsic::ctpop:
821 setValue(&I, DAG.getNode(ISD::CTPOP,
822 getValue(I.getOperand(1)).getValueType(),
823 getValue(I.getOperand(1))));
824 return;
Chris Lattner20eaeae2005-05-09 20:22:36 +0000825 default:
826 std::cerr << I;
827 assert(0 && "This intrinsic is not implemented yet!");
828 return;
Chris Lattner0c140002005-04-02 05:26:53 +0000829 }
Misha Brukman835702a2005-04-21 22:36:52 +0000830
Chris Lattner18d2b342005-01-08 22:48:57 +0000831 SDOperand Callee;
832 if (!RenameFn)
833 Callee = getValue(I.getOperand(0));
834 else
835 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +0000836 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukman835702a2005-04-21 22:36:52 +0000837
Chris Lattner7a60d912005-01-07 07:47:53 +0000838 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
839 Value *Arg = I.getOperand(i);
840 SDOperand ArgNode = getValue(Arg);
841 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
842 }
Misha Brukman835702a2005-04-21 22:36:52 +0000843
Nate Begemanf6565252005-03-26 01:29:23 +0000844 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
845 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +0000846
Chris Lattner1f45cd72005-01-08 19:26:18 +0000847 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +0000848 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +0000849 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +0000850 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +0000851 setValue(&I, Result.first);
852 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000853}
854
855void SelectionDAGLowering::visitMalloc(MallocInst &I) {
856 SDOperand Src = getValue(I.getOperand(0));
857
858 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +0000859
860 if (IntPtr < Src.getValueType())
861 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
862 else if (IntPtr > Src.getValueType())
863 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +0000864
865 // Scale the source by the type size.
866 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
867 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
868 Src, getIntPtrConstant(ElementSize));
869
870 std::vector<std::pair<SDOperand, const Type*> > Args;
871 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +0000872
873 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000874 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000875 DAG.getExternalSymbol("malloc", IntPtr),
876 Args, DAG);
877 setValue(&I, Result.first); // Pointers always fit in registers
878 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000879}
880
881void SelectionDAGLowering::visitFree(FreeInst &I) {
882 std::vector<std::pair<SDOperand, const Type*> > Args;
883 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
884 TLI.getTargetData().getIntPtrType()));
885 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +0000886 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +0000887 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +0000888 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
889 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000890}
891
Chris Lattner13d7c252005-08-26 20:54:47 +0000892// InsertAtEndOfBasicBlock - This method should be implemented by targets that
893// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
894// instructions are special in various ways, which require special support to
895// insert. The specified MachineInstr is created but not inserted into any
896// basic blocks, and the scheduler passes ownership of it to this method.
897MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
898 MachineBasicBlock *MBB) {
899 std::cerr << "If a target marks an instruction with "
900 "'usesCustomDAGSchedInserter', it must implement "
901 "TargetLowering::InsertAtEndOfBasicBlock!\n";
902 abort();
903 return 0;
904}
905
Nate Begeman78afac22005-10-18 23:23:37 +0000906SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
907 SelectionDAG &DAG) {
908 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
909}
910
Chris Lattnerf5473e42005-07-05 19:57:53 +0000911SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
912 SDOperand VAListP, Value *VAListV,
913 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000914 // We have no sane default behavior, just emit a useful error message and bail
915 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +0000916 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +0000917 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +0000918 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +0000919}
920
Chris Lattnerf5473e42005-07-05 19:57:53 +0000921SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +0000922 SelectionDAG &DAG) {
923 // Default to a noop.
924 return Chain;
925}
926
Chris Lattnerf5473e42005-07-05 19:57:53 +0000927SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
928 SDOperand SrcP, Value *SrcV,
929 SDOperand DestP, Value *DestV,
930 SelectionDAG &DAG) {
931 // Default to copying the input list.
932 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
933 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +0000934 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000935 Val, DestP, DAG.getSrcValue(DestV));
936 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +0000937}
938
939std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +0000940TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
941 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +0000942 // We have no sane default behavior, just emit a useful error message and bail
943 // out.
944 std::cerr << "Variable arguments handling not implemented on this target!\n";
945 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000946 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +0000947}
948
949
950void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000951 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
952 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +0000953}
954
955void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
956 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +0000957 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +0000958 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000959 setValue(&I, Result.first);
960 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000961}
962
963void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000964 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +0000965 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000966}
967
968void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +0000969 SDOperand Result =
970 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
971 getValue(I.getOperand(1)), I.getOperand(1), DAG);
972 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +0000973}
974
Chris Lattner58cfd792005-01-09 00:00:49 +0000975
976// It is always conservatively correct for llvm.returnaddress and
977// llvm.frameaddress to return 0.
978std::pair<SDOperand, SDOperand>
979TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
980 unsigned Depth, SelectionDAG &DAG) {
981 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +0000982}
983
Chris Lattner29dcc712005-05-14 05:50:48 +0000984SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +0000985 assert(0 && "LowerOperation not implemented for this target!");
986 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +0000987 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +0000988}
989
Chris Lattner58cfd792005-01-09 00:00:49 +0000990void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
991 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
992 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +0000993 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +0000994 setValue(&I, Result.first);
995 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +0000996}
997
Chris Lattner875def92005-01-11 05:56:49 +0000998void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
999 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001000 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001001 Ops.push_back(getValue(I.getOperand(1)));
1002 Ops.push_back(getValue(I.getOperand(2)));
1003 Ops.push_back(getValue(I.getOperand(3)));
1004 Ops.push_back(getValue(I.getOperand(4)));
1005 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001006}
1007
Chris Lattner875def92005-01-11 05:56:49 +00001008//===----------------------------------------------------------------------===//
1009// SelectionDAGISel code
1010//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001011
1012unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1013 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1014}
1015
Chris Lattnerc9950c12005-08-17 06:37:43 +00001016void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001017 // FIXME: we only modify the CFG to split critical edges. This
1018 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001019}
Chris Lattner7a60d912005-01-07 07:47:53 +00001020
1021
1022bool SelectionDAGISel::runOnFunction(Function &Fn) {
1023 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1024 RegMap = MF.getSSARegMap();
1025 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1026
Chris Lattnerc9950c12005-08-17 06:37:43 +00001027 // First pass, split all critical edges for PHI nodes with incoming values
1028 // that are constants, this way the load of the constant into a vreg will not
1029 // be placed into MBBs that are used some other way.
Chris Lattner1a908c82005-08-18 17:35:14 +00001030 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1031 PHINode *PN;
1032 for (BasicBlock::iterator BBI = BB->begin();
1033 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1035 if (isa<Constant>(PN->getIncomingValue(i)))
1036 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1037 }
Chris Lattnerc9950c12005-08-17 06:37:43 +00001038
Chris Lattner7a60d912005-01-07 07:47:53 +00001039 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1040
1041 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1042 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001043
Chris Lattner7a60d912005-01-07 07:47:53 +00001044 return true;
1045}
1046
1047
Chris Lattner718b5c22005-01-13 17:59:43 +00001048SDOperand SelectionDAGISel::
1049CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001050 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001051 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001052 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001053 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001054
1055 // If this type is not legal, we must make sure to not create an invalid
1056 // register use.
1057 MVT::ValueType SrcVT = Op.getValueType();
1058 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1059 SelectionDAG &DAG = SDL.DAG;
1060 if (SrcVT == DestVT) {
1061 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1062 } else if (SrcVT < DestVT) {
1063 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001064 if (MVT::isFloatingPoint(SrcVT))
1065 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1066 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001067 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001068 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1069 } else {
1070 // The src value is expanded into multiple registers.
1071 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1072 Op, DAG.getConstant(0, MVT::i32));
1073 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1074 Op, DAG.getConstant(1, MVT::i32));
1075 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1076 return DAG.getCopyToReg(Op, Reg+1, Hi);
1077 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001078}
1079
Chris Lattner16f64df2005-01-17 17:15:02 +00001080void SelectionDAGISel::
1081LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1082 std::vector<SDOperand> &UnorderedChains) {
1083 // If this is the entry block, emit arguments.
1084 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001085 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001086 SDOperand OldRoot = SDL.DAG.getRoot();
1087 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001088
Chris Lattner6871b232005-10-30 19:42:35 +00001089 unsigned a = 0;
1090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1091 AI != E; ++AI, ++a)
1092 if (!AI->use_empty()) {
1093 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001094
Chris Lattner6871b232005-10-30 19:42:35 +00001095 // If this argument is live outside of the entry block, insert a copy from
1096 // whereever we got it to the vreg that other BB's will reference it as.
1097 if (FuncInfo.ValueMap.count(AI)) {
1098 SDOperand Copy =
1099 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1100 UnorderedChains.push_back(Copy);
1101 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001102 }
Chris Lattner6871b232005-10-30 19:42:35 +00001103
1104 // Next, if the function has live ins that need to be copied into vregs,
1105 // emit the copies now, into the top of the block.
1106 MachineFunction &MF = SDL.DAG.getMachineFunction();
1107 if (MF.livein_begin() != MF.livein_end()) {
1108 SSARegMap *RegMap = MF.getSSARegMap();
1109 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1110 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1111 E = MF.livein_end(); LI != E; ++LI)
1112 if (LI->second)
1113 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1114 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001115 }
Chris Lattner6871b232005-10-30 19:42:35 +00001116
1117 // Finally, if the target has anything special to do, allow it to do so.
1118 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001119}
1120
1121
Chris Lattner7a60d912005-01-07 07:47:53 +00001122void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1123 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1124 FunctionLoweringInfo &FuncInfo) {
1125 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001126
1127 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001128
Chris Lattner6871b232005-10-30 19:42:35 +00001129 // Lower any arguments needed in this block if this is the entry block.
1130 if (LLVMBB == &LLVMBB->getParent()->front())
1131 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001132
1133 BB = FuncInfo.MBBMap[LLVMBB];
1134 SDL.setCurrentBasicBlock(BB);
1135
1136 // Lower all of the non-terminator instructions.
1137 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1138 I != E; ++I)
1139 SDL.visit(*I);
1140
1141 // Ensure that all instructions which are used outside of their defining
1142 // blocks are available as virtual registers.
1143 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001144 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001145 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001146 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001147 UnorderedChains.push_back(
1148 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001149 }
1150
1151 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1152 // ensure constants are generated when needed. Remember the virtual registers
1153 // that need to be added to the Machine PHI nodes as input. We cannot just
1154 // directly add them, because expansion might result in multiple MBB's for one
1155 // BB. As such, the start of the BB might correspond to a different MBB than
1156 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001157 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001158
1159 // Emit constants only once even if used by multiple PHI nodes.
1160 std::map<Constant*, unsigned> ConstantsOut;
1161
1162 // Check successor nodes PHI nodes that expect a constant to be available from
1163 // this block.
1164 TerminatorInst *TI = LLVMBB->getTerminator();
1165 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1166 BasicBlock *SuccBB = TI->getSuccessor(succ);
1167 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1168 PHINode *PN;
1169
1170 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1171 // nodes and Machine PHI nodes, but the incoming operands have not been
1172 // emitted yet.
1173 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001174 (PN = dyn_cast<PHINode>(I)); ++I)
1175 if (!PN->use_empty()) {
1176 unsigned Reg;
1177 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1178 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1179 unsigned &RegOut = ConstantsOut[C];
1180 if (RegOut == 0) {
1181 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001182 UnorderedChains.push_back(
1183 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001184 }
1185 Reg = RegOut;
1186 } else {
1187 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001188 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001189 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001190 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1191 "Didn't codegen value into a register!??");
1192 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001193 UnorderedChains.push_back(
1194 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001195 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001196 }
Misha Brukman835702a2005-04-21 22:36:52 +00001197
Chris Lattner8ea875f2005-01-07 21:34:19 +00001198 // Remember that this register needs to added to the machine PHI node as
1199 // the input for this MBB.
1200 unsigned NumElements =
1201 TLI.getNumElements(TLI.getValueType(PN->getType()));
1202 for (unsigned i = 0, e = NumElements; i != e; ++i)
1203 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001204 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001205 }
1206 ConstantsOut.clear();
1207
Chris Lattner718b5c22005-01-13 17:59:43 +00001208 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001209 if (!UnorderedChains.empty()) {
Chris Lattner4d9651c2005-01-17 22:19:26 +00001210 UnorderedChains.push_back(SDL.getRoot());
Chris Lattner718b5c22005-01-13 17:59:43 +00001211 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1212 }
1213
Chris Lattner7a60d912005-01-07 07:47:53 +00001214 // Lower the terminator after the copies are emitted.
1215 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001216
1217 // Make sure the root of the DAG is up-to-date.
1218 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001219}
1220
1221void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1222 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001223 SelectionDAG DAG(TLI, MF);
Chris Lattner7a60d912005-01-07 07:47:53 +00001224 CurDAG = &DAG;
1225 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1226
1227 // First step, lower LLVM code to some DAG. This DAG may use operations and
1228 // types that are not supported by the target.
1229 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1230
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001231 // Run the DAG combiner in pre-legalize mode.
1232 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001233
Chris Lattner7a60d912005-01-07 07:47:53 +00001234 DEBUG(std::cerr << "Lowered selection DAG:\n");
1235 DEBUG(DAG.dump());
1236
1237 // Second step, hack on the DAG until it only uses operations and types that
1238 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001239 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001240
1241 DEBUG(std::cerr << "Legalized selection DAG:\n");
1242 DEBUG(DAG.dump());
1243
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001244 // Run the DAG combiner in post-legalize mode.
1245 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001246
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001247 if (ViewDAGs) DAG.viewGraph();
1248
Chris Lattner5ca31d92005-03-30 01:10:47 +00001249 // Third, instruction select all of the operations to machine code, adding the
1250 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001251 InstructionSelectBasicBlock(DAG);
1252
Chris Lattner7a60d912005-01-07 07:47:53 +00001253 DEBUG(std::cerr << "Selected machine code:\n");
1254 DEBUG(BB->dump());
1255
Chris Lattner5ca31d92005-03-30 01:10:47 +00001256 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001257 // PHI nodes in successors.
1258 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1259 MachineInstr *PHI = PHINodesToUpdate[i].first;
1260 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1261 "This is not a machine PHI node that we are updating!");
1262 PHI->addRegOperand(PHINodesToUpdate[i].second);
1263 PHI->addMachineBasicBlockOperand(BB);
1264 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001265
1266 // Finally, add the CFG edges from the last selected MBB to the successor
1267 // MBBs.
1268 TerminatorInst *TI = LLVMBB->getTerminator();
1269 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1270 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1271 BB->addSuccessor(Succ0MBB);
1272 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001273}