blob: 26421c148f80ca9b68f6d323eb0d1b6e30c624b3 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000016#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/SelectionDAG.h"
26#include "llvm/CodeGen/SSARegMap.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetFrameInfo.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetLowering.h"
31#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000033#include "llvm/Support/CommandLine.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/Support/Debug.h"
35#include <map>
36#include <iostream>
37using namespace llvm;
38
Nate Begeman2300f552005-09-07 00:15:36 +000039// Temporary command line code to enable use of the dag combiner as a beta
40// option.
41namespace llvm {
42 bool CombinerEnabled;
43}
44namespace {
45 cl::opt<bool, true>
46 CombineDAG("enable-dag-combiner", cl::Hidden,
47 cl::desc("Run the DAG combiner before and after Legalize"),
48 cl::location(CombinerEnabled),
49 cl::init(false));
50}
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
53ViewDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55#else
Chris Lattnera639a432005-09-02 07:09:28 +000056static const bool ViewDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#endif
58
Nate Begeman2300f552005-09-07 00:15:36 +000059
Chris Lattner1c08c712005-01-07 07:47:53 +000060namespace llvm {
61 //===--------------------------------------------------------------------===//
62 /// FunctionLoweringInfo - This contains information that is global to a
63 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000064 class FunctionLoweringInfo {
65 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000066 TargetLowering &TLI;
67 Function &Fn;
68 MachineFunction &MF;
69 SSARegMap *RegMap;
70
71 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
72
73 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
74 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
75
76 /// ValueMap - Since we emit code for the function a basic block at a time,
77 /// we must remember which virtual registers hold the values for
78 /// cross-basic-block values.
79 std::map<const Value*, unsigned> ValueMap;
80
81 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
82 /// the entry block. This allows the allocas to be efficiently referenced
83 /// anywhere in the function.
84 std::map<const AllocaInst*, int> StaticAllocaMap;
85
Chris Lattner0afa8e32005-01-17 17:55:19 +000086 /// BlockLocalArguments - If any arguments are only used in a single basic
87 /// block, and if the target can access the arguments without side-effects,
88 /// avoid emitting CopyToReg nodes for those arguments. This map keeps
89 /// track of which arguments are local to each BB.
90 std::multimap<BasicBlock*, std::pair<Argument*,
91 unsigned> > BlockLocalArguments;
92
93
Chris Lattner1c08c712005-01-07 07:47:53 +000094 unsigned MakeReg(MVT::ValueType VT) {
95 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
96 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000097
Chris Lattner1c08c712005-01-07 07:47:53 +000098 unsigned CreateRegForValue(const Value *V) {
99 MVT::ValueType VT = TLI.getValueType(V->getType());
100 // The common case is that we will only create one register for this
101 // value. If we have that case, create and return the virtual register.
102 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000103 if (NV == 1) {
104 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000105 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000106 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000107
Chris Lattner1c08c712005-01-07 07:47:53 +0000108 // If this value is represented with multiple target registers, make sure
109 // to create enough consequtive registers of the right (smaller) type.
110 unsigned NT = VT-1; // Find the type to use.
111 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
112 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000113
Chris Lattner1c08c712005-01-07 07:47:53 +0000114 unsigned R = MakeReg((MVT::ValueType)NT);
115 for (unsigned i = 1; i != NV; ++i)
116 MakeReg((MVT::ValueType)NT);
117 return R;
118 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000119
Chris Lattner1c08c712005-01-07 07:47:53 +0000120 unsigned InitializeRegForValue(const Value *V) {
121 unsigned &R = ValueMap[V];
122 assert(R == 0 && "Already initialized this value register!");
123 return R = CreateRegForValue(V);
124 }
125 };
126}
127
128/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
129/// PHI nodes or outside of the basic block that defines it.
130static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
131 if (isa<PHINode>(I)) return true;
132 BasicBlock *BB = I->getParent();
133 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
134 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
135 return true;
136 return false;
137}
138
139FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000140 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000141 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
142
143 // Initialize the mapping of values to registers. This is only set up for
144 // instruction values that are used outside of the block that defines
145 // them.
Chris Lattner16ce0df2005-05-11 18:57:06 +0000146 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
147 AI != E; ++AI)
Chris Lattner1c08c712005-01-07 07:47:53 +0000148 InitializeRegForValue(AI);
149
150 Function::iterator BB = Fn.begin(), E = Fn.end();
151 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
152 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
153 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
154 const Type *Ty = AI->getAllocatedType();
155 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
156 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
Chris Lattnera8217e32005-05-13 23:14:17 +0000157
158 // If the alignment of the value is smaller than the size of the value,
159 // and if the size of the value is particularly small (<= 8 bytes),
160 // round up to the size of the value for potentially better performance.
161 //
162 // FIXME: This could be made better with a preferred alignment hook in
163 // TargetData. It serves primarily to 8-byte align doubles for X86.
164 if (Align < TySize && TySize <= 8) Align = TySize;
165
Chris Lattnerfd88f642005-09-02 18:41:28 +0000166 if (CUI->getValue()) // Don't produce zero sized stack objects
167 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner1c08c712005-01-07 07:47:53 +0000168 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000169 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000170 }
171
172 for (; BB != E; ++BB)
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000173 for (BasicBlock::iterator I = BB->begin(), e = BB->end(); I != e; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
175 if (!isa<AllocaInst>(I) ||
176 !StaticAllocaMap.count(cast<AllocaInst>(I)))
177 InitializeRegForValue(I);
178
179 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
180 // also creates the initial PHI MachineInstrs, though none of the input
181 // operands are populated.
182 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
183 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
184 MBBMap[BB] = MBB;
185 MF.getBasicBlockList().push_back(MBB);
186
187 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
188 // appropriate.
189 PHINode *PN;
190 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000191 (PN = dyn_cast<PHINode>(I)); ++I)
192 if (!PN->use_empty()) {
193 unsigned NumElements =
194 TLI.getNumElements(TLI.getValueType(PN->getType()));
195 unsigned PHIReg = ValueMap[PN];
196 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
197 for (unsigned i = 0; i != NumElements; ++i)
198 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
199 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000200 }
201}
202
203
204
205//===----------------------------------------------------------------------===//
206/// SelectionDAGLowering - This is the common target-independent lowering
207/// implementation that is parameterized by a TargetLowering object.
208/// Also, targets can overload any lowering method.
209///
210namespace llvm {
211class SelectionDAGLowering {
212 MachineBasicBlock *CurMBB;
213
214 std::map<const Value*, SDOperand> NodeMap;
215
Chris Lattnerd3948112005-01-17 22:19:26 +0000216 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
217 /// them up and then emit token factor nodes when possible. This allows us to
218 /// get simple disambiguation between loads without worrying about alias
219 /// analysis.
220 std::vector<SDOperand> PendingLoads;
221
Chris Lattner1c08c712005-01-07 07:47:53 +0000222public:
223 // TLI - This is information that describes the available target features we
224 // need for lowering. This indicates when operations are unavailable,
225 // implemented with a libcall, etc.
226 TargetLowering &TLI;
227 SelectionDAG &DAG;
228 const TargetData &TD;
229
230 /// FuncInfo - Information about the function as a whole.
231 ///
232 FunctionLoweringInfo &FuncInfo;
233
234 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000235 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000236 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
237 FuncInfo(funcinfo) {
238 }
239
Chris Lattnera651cf62005-01-17 19:43:36 +0000240 /// getRoot - Return the current virtual root of the Selection DAG.
241 ///
242 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000243 if (PendingLoads.empty())
244 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000245
Chris Lattnerd3948112005-01-17 22:19:26 +0000246 if (PendingLoads.size() == 1) {
247 SDOperand Root = PendingLoads[0];
248 DAG.setRoot(Root);
249 PendingLoads.clear();
250 return Root;
251 }
252
253 // Otherwise, we have to make a token factor node.
254 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
255 PendingLoads.clear();
256 DAG.setRoot(Root);
257 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000258 }
259
Chris Lattner1c08c712005-01-07 07:47:53 +0000260 void visit(Instruction &I) { visit(I.getOpcode(), I); }
261
262 void visit(unsigned Opcode, User &I) {
263 switch (Opcode) {
264 default: assert(0 && "Unknown instruction type encountered!");
265 abort();
266 // Build the switch statement using the Instruction.def file.
267#define HANDLE_INST(NUM, OPCODE, CLASS) \
268 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
269#include "llvm/Instruction.def"
270 }
271 }
272
273 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
274
275
276 SDOperand getIntPtrConstant(uint64_t Val) {
277 return DAG.getConstant(Val, TLI.getPointerTy());
278 }
279
280 SDOperand getValue(const Value *V) {
281 SDOperand &N = NodeMap[V];
282 if (N.Val) return N;
283
284 MVT::ValueType VT = TLI.getValueType(V->getType());
285 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
287 visit(CE->getOpcode(), *CE);
288 assert(N.Val && "visit didn't populate the ValueMap!");
289 return N;
290 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
291 return N = DAG.getGlobalAddress(GV, VT);
292 } else if (isa<ConstantPointerNull>(C)) {
293 return N = DAG.getConstant(0, TLI.getPointerTy());
294 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000295 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
297 return N = DAG.getConstantFP(CFP->getValue(), VT);
298 } else {
299 // Canonicalize all constant ints to be unsigned.
300 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
301 }
302
303 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
304 std::map<const AllocaInst*, int>::iterator SI =
305 FuncInfo.StaticAllocaMap.find(AI);
306 if (SI != FuncInfo.StaticAllocaMap.end())
307 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
308 }
309
310 std::map<const Value*, unsigned>::const_iterator VMI =
311 FuncInfo.ValueMap.find(V);
312 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000313
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000314 unsigned InReg = VMI->second;
315
316 // If this type is not legal, make it so now.
317 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
318
319 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
320 if (DestVT < VT) {
321 // Source must be expanded. This input value is actually coming from the
322 // register pair VMI->second and VMI->second+1.
323 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
324 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
325 } else {
326 if (DestVT > VT) { // Promotion case
327 if (MVT::isFloatingPoint(VT))
328 N = DAG.getNode(ISD::FP_ROUND, VT, N);
329 else
330 N = DAG.getNode(ISD::TRUNCATE, VT, N);
331 }
332 }
333
334 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000335 }
336
337 const SDOperand &setValue(const Value *V, SDOperand NewN) {
338 SDOperand &N = NodeMap[V];
339 assert(N.Val == 0 && "Already set a value for this node!");
340 return N = NewN;
341 }
342
343 // Terminator instructions.
344 void visitRet(ReturnInst &I);
345 void visitBr(BranchInst &I);
346 void visitUnreachable(UnreachableInst &I) { /* noop */ }
347
348 // These all get lowered before this pass.
349 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
350 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
351 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
352
353 //
Chris Lattner8f034052005-08-22 17:28:31 +0000354 void visitBinary(User &I, unsigned Opcode, bool isShift = false);
Chris Lattner1c08c712005-01-07 07:47:53 +0000355 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000356 void visitSub(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000357 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
358 void visitDiv(User &I) {
359 visitBinary(I, I.getType()->isUnsigned() ? ISD::UDIV : ISD::SDIV);
360 }
361 void visitRem(User &I) {
362 visitBinary(I, I.getType()->isUnsigned() ? ISD::UREM : ISD::SREM);
363 }
364 void visitAnd(User &I) { visitBinary(I, ISD::AND); }
365 void visitOr (User &I) { visitBinary(I, ISD::OR); }
366 void visitXor(User &I) { visitBinary(I, ISD::XOR); }
Chris Lattner8f034052005-08-22 17:28:31 +0000367 void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000368 void visitShr(User &I) {
Chris Lattner8f034052005-08-22 17:28:31 +0000369 visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 }
371
372 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
373 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
374 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
375 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
376 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
377 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
378 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
379
380 void visitGetElementPtr(User &I);
381 void visitCast(User &I);
382 void visitSelect(User &I);
383 //
384
385 void visitMalloc(MallocInst &I);
386 void visitFree(FreeInst &I);
387 void visitAlloca(AllocaInst &I);
388 void visitLoad(LoadInst &I);
389 void visitStore(StoreInst &I);
390 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
391 void visitCall(CallInst &I);
392
Chris Lattner1c08c712005-01-07 07:47:53 +0000393 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000394 void visitVAArg(VAArgInst &I);
395 void visitVAEnd(CallInst &I);
396 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000397 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000398
Chris Lattner7041ee32005-01-11 05:56:49 +0000399 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000400
401 void visitUserOp1(Instruction &I) {
402 assert(0 && "UserOp1 should not exist at instruction selection time!");
403 abort();
404 }
405 void visitUserOp2(Instruction &I) {
406 assert(0 && "UserOp2 should not exist at instruction selection time!");
407 abort();
408 }
409};
410} // end namespace llvm
411
412void SelectionDAGLowering::visitRet(ReturnInst &I) {
413 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000414 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000415 return;
416 }
417
418 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000419 MVT::ValueType TmpVT;
420
Chris Lattner1c08c712005-01-07 07:47:53 +0000421 switch (Op1.getValueType()) {
422 default: assert(0 && "Unknown value type!");
423 case MVT::i1:
424 case MVT::i8:
425 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000426 case MVT::i32:
427 // If this is a machine where 32-bits is legal or expanded, promote to
428 // 32-bits, otherwise, promote to 64-bits.
429 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
430 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000431 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000432 TmpVT = MVT::i32;
433
434 // Extend integer types to result type.
435 if (I.getOperand(0)->getType()->isSigned())
436 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
437 else
438 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000439 break;
440 case MVT::f32:
Chris Lattner1c08c712005-01-07 07:47:53 +0000441 case MVT::i64:
442 case MVT::f64:
443 break; // No extension needed!
444 }
445
Chris Lattnera651cf62005-01-17 19:43:36 +0000446 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot(), Op1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000447}
448
449void SelectionDAGLowering::visitBr(BranchInst &I) {
450 // Update machine-CFG edges.
451 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000452
453 // Figure out which block is immediately after the current one.
454 MachineBasicBlock *NextBlock = 0;
455 MachineFunction::iterator BBI = CurMBB;
456 if (++BBI != CurMBB->getParent()->end())
457 NextBlock = BBI;
458
459 if (I.isUnconditional()) {
460 // If this is not a fall-through branch, emit the branch.
461 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000462 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000463 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000464 } else {
465 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000466
467 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000468 if (Succ1MBB == NextBlock) {
469 // If the condition is false, fall through. This means we should branch
470 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000471 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000472 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000473 } else if (Succ0MBB == NextBlock) {
474 // If the condition is true, fall through. This means we should branch if
475 // the condition is false to Succ #1. Invert the condition first.
476 SDOperand True = DAG.getConstant(1, Cond.getValueType());
477 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000478 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000479 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000480 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000481 std::vector<SDOperand> Ops;
482 Ops.push_back(getRoot());
483 Ops.push_back(Cond);
484 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
485 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
486 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000487 }
488 }
489}
490
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000491void SelectionDAGLowering::visitSub(User &I) {
492 // -0.0 - X --> fneg
493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
494 if (CFP->isExactlyValue(-0.0)) {
495 SDOperand Op2 = getValue(I.getOperand(1));
496 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
497 return;
498 }
499
500 visitBinary(I, ISD::SUB);
501}
502
Chris Lattner8f034052005-08-22 17:28:31 +0000503void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000504 SDOperand Op1 = getValue(I.getOperand(0));
505 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000506
Chris Lattner8f034052005-08-22 17:28:31 +0000507 if (isShift)
Chris Lattnerfab08872005-09-02 00:19:37 +0000508 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Chris Lattner2c49f272005-01-19 22:31:21 +0000509
Chris Lattner1c08c712005-01-07 07:47:53 +0000510 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
511}
512
513void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
514 ISD::CondCode UnsignedOpcode) {
515 SDOperand Op1 = getValue(I.getOperand(0));
516 SDOperand Op2 = getValue(I.getOperand(1));
517 ISD::CondCode Opcode = SignedOpcode;
518 if (I.getOperand(0)->getType()->isUnsigned())
519 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000520 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000521}
522
523void SelectionDAGLowering::visitSelect(User &I) {
524 SDOperand Cond = getValue(I.getOperand(0));
525 SDOperand TrueVal = getValue(I.getOperand(1));
526 SDOperand FalseVal = getValue(I.getOperand(2));
527 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
528 TrueVal, FalseVal));
529}
530
531void SelectionDAGLowering::visitCast(User &I) {
532 SDOperand N = getValue(I.getOperand(0));
533 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
534 MVT::ValueType DestTy = TLI.getValueType(I.getType());
535
536 if (N.getValueType() == DestTy) {
537 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000538 } else if (DestTy == MVT::i1) {
539 // Cast to bool is a comparison against zero, not truncation to zero.
540 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
541 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000542 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000543 } else if (isInteger(SrcTy)) {
544 if (isInteger(DestTy)) { // Int -> Int cast
545 if (DestTy < SrcTy) // Truncating cast?
546 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
547 else if (I.getOperand(0)->getType()->isSigned())
548 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
549 else
550 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
551 } else { // Int -> FP cast
552 if (I.getOperand(0)->getType()->isSigned())
553 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
554 else
555 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
556 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000557 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000558 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
559 if (isFloatingPoint(DestTy)) { // FP -> FP cast
560 if (DestTy < SrcTy) // Rounding cast?
561 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
562 else
563 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
564 } else { // FP -> Int cast.
565 if (I.getType()->isSigned())
566 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
567 else
568 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
569 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 }
571}
572
573void SelectionDAGLowering::visitGetElementPtr(User &I) {
574 SDOperand N = getValue(I.getOperand(0));
575 const Type *Ty = I.getOperand(0)->getType();
576 const Type *UIntPtrTy = TD.getIntPtrType();
577
578 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
579 OI != E; ++OI) {
580 Value *Idx = *OI;
581 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
582 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
583 if (Field) {
584 // N = N + Offset
585 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
586 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000587 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000588 }
589 Ty = StTy->getElementType(Field);
590 } else {
591 Ty = cast<SequentialType>(Ty)->getElementType();
592 if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
593 // N = N + Idx * ElementSize;
594 uint64_t ElementSize = TD.getTypeSize(Ty);
Chris Lattner7cc47772005-01-07 21:56:57 +0000595 SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
596
597 // If the index is smaller or larger than intptr_t, truncate or extend
598 // it.
599 if (IdxN.getValueType() < Scale.getValueType()) {
600 if (Idx->getType()->isSigned())
601 IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
602 else
603 IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
604 } else if (IdxN.getValueType() > Scale.getValueType())
605 IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
606
607 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
Chris Lattner1c08c712005-01-07 07:47:53 +0000608 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
609 }
610 }
611 }
612 setValue(&I, N);
613}
614
615void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
616 // If this is a fixed sized alloca in the entry block of the function,
617 // allocate it statically on the stack.
618 if (FuncInfo.StaticAllocaMap.count(&I))
619 return; // getValue will auto-populate this.
620
621 const Type *Ty = I.getAllocatedType();
622 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
623 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
624
625 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000626 MVT::ValueType IntPtr = TLI.getPointerTy();
627 if (IntPtr < AllocSize.getValueType())
628 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
629 else if (IntPtr > AllocSize.getValueType())
630 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000631
Chris Lattner68cd65e2005-01-22 23:04:37 +0000632 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000633 getIntPtrConstant(TySize));
634
635 // Handle alignment. If the requested alignment is less than or equal to the
636 // stack alignment, ignore it and round the size of the allocation up to the
637 // stack alignment size. If the size is greater than the stack alignment, we
638 // note this in the DYNAMIC_STACKALLOC node.
639 unsigned StackAlign =
640 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
641 if (Align <= StackAlign) {
642 Align = 0;
643 // Add SA-1 to the size.
644 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
645 getIntPtrConstant(StackAlign-1));
646 // Mask out the low bits for alignment purposes.
647 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
648 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
649 }
650
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000651 std::vector<MVT::ValueType> VTs;
652 VTs.push_back(AllocSize.getValueType());
653 VTs.push_back(MVT::Other);
654 std::vector<SDOperand> Ops;
655 Ops.push_back(getRoot());
656 Ops.push_back(AllocSize);
657 Ops.push_back(getIntPtrConstant(Align));
658 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000659 DAG.setRoot(setValue(&I, DSA).getValue(1));
660
661 // Inform the Frame Information that we have just allocated a variable-sized
662 // object.
663 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
664}
665
666
667void SelectionDAGLowering::visitLoad(LoadInst &I) {
668 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000669
Chris Lattnerd3948112005-01-17 22:19:26 +0000670 SDOperand Root;
671 if (I.isVolatile())
672 Root = getRoot();
673 else {
674 // Do not serialize non-volatile loads against each other.
675 Root = DAG.getRoot();
676 }
677
Chris Lattner369e6db2005-05-09 04:08:33 +0000678 SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000679 DAG.getSrcValue(I.getOperand(0)));
Chris Lattnerd3948112005-01-17 22:19:26 +0000680 setValue(&I, L);
681
682 if (I.isVolatile())
683 DAG.setRoot(L.getValue(1));
684 else
685 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000686}
687
688
689void SelectionDAGLowering::visitStore(StoreInst &I) {
690 Value *SrcV = I.getOperand(0);
691 SDOperand Src = getValue(SrcV);
692 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000693 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000694 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000695}
696
697void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +0000698 const char *RenameFn = 0;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000699 SDOperand Tmp;
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 if (Function *F = I.getCalledFunction())
Chris Lattnerc0f18152005-04-02 05:26:53 +0000701 if (F->isExternal())
702 switch (F->getIntrinsicID()) {
703 case 0: // Not an LLVM intrinsic.
704 if (F->getName() == "fabs" || F->getName() == "fabsf") {
705 if (I.getNumOperands() == 2 && // Basic sanity checks.
706 I.getOperand(1)->getType()->isFloatingPoint() &&
707 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000708 Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000709 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
710 return;
711 }
712 }
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000713 else if (F->getName() == "sin" || F->getName() == "sinf") {
714 if (I.getNumOperands() == 2 && // Basic sanity checks.
715 I.getOperand(1)->getType()->isFloatingPoint() &&
716 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000717 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000718 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
719 return;
720 }
721 }
722 else if (F->getName() == "cos" || F->getName() == "cosf") {
723 if (I.getNumOperands() == 2 && // Basic sanity checks.
724 I.getOperand(1)->getType()->isFloatingPoint() &&
725 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000726 Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000727 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
728 return;
729 }
730 }
Chris Lattnerc0f18152005-04-02 05:26:53 +0000731 break;
732 case Intrinsic::vastart: visitVAStart(I); return;
733 case Intrinsic::vaend: visitVAEnd(I); return;
734 case Intrinsic::vacopy: visitVACopy(I); return;
735 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
736 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000737
Chris Lattnerc0f18152005-04-02 05:26:53 +0000738 case Intrinsic::setjmp: RenameFn = "setjmp"; break;
739 case Intrinsic::longjmp: RenameFn = "longjmp"; break;
740 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return;
741 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return;
742 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000743
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000744 case Intrinsic::readport:
Chris Lattner1ca85d52005-05-14 13:56:55 +0000745 case Intrinsic::readio: {
746 std::vector<MVT::ValueType> VTs;
747 VTs.push_back(TLI.getValueType(I.getType()));
748 VTs.push_back(MVT::Other);
749 std::vector<SDOperand> Ops;
750 Ops.push_back(getRoot());
751 Ops.push_back(getValue(I.getOperand(1)));
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000752 Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
Chris Lattner1ca85d52005-05-14 13:56:55 +0000753 ISD::READPORT : ISD::READIO, VTs, Ops);
Jeff Cohen00b168892005-07-27 06:12:32 +0000754
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000755 setValue(&I, Tmp);
756 DAG.setRoot(Tmp.getValue(1));
757 return;
Chris Lattner1ca85d52005-05-14 13:56:55 +0000758 }
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000759 case Intrinsic::writeport:
760 case Intrinsic::writeio:
761 DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
762 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
763 getRoot(), getValue(I.getOperand(1)),
764 getValue(I.getOperand(2))));
765 return;
Chris Lattner7ea0ade2005-05-05 17:55:17 +0000766 case Intrinsic::dbg_stoppoint:
767 case Intrinsic::dbg_region_start:
768 case Intrinsic::dbg_region_end:
769 case Intrinsic::dbg_func_start:
770 case Intrinsic::dbg_declare:
771 if (I.getType() != Type::VoidTy)
772 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
773 return;
774
Chris Lattnerc0f18152005-04-02 05:26:53 +0000775 case Intrinsic::isunordered:
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000776 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
777 getValue(I.getOperand(2)), ISD::SETUO));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000778 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +0000779
780 case Intrinsic::sqrt:
781 setValue(&I, DAG.getNode(ISD::FSQRT,
782 getValue(I.getOperand(1)).getValueType(),
783 getValue(I.getOperand(1))));
784 return;
785
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000786 case Intrinsic::pcmarker:
787 Tmp = getValue(I.getOperand(1));
788 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
Chris Lattnerc0f18152005-04-02 05:26:53 +0000789 return;
Andrew Lenharth691ef2b2005-05-03 17:19:30 +0000790 case Intrinsic::cttz:
791 setValue(&I, DAG.getNode(ISD::CTTZ,
792 getValue(I.getOperand(1)).getValueType(),
793 getValue(I.getOperand(1))));
794 return;
795 case Intrinsic::ctlz:
796 setValue(&I, DAG.getNode(ISD::CTLZ,
797 getValue(I.getOperand(1)).getValueType(),
798 getValue(I.getOperand(1))));
799 return;
800 case Intrinsic::ctpop:
801 setValue(&I, DAG.getNode(ISD::CTPOP,
802 getValue(I.getOperand(1)).getValueType(),
803 getValue(I.getOperand(1))));
804 return;
Chris Lattnerd0f6c1f2005-05-09 20:22:36 +0000805 default:
806 std::cerr << I;
807 assert(0 && "This intrinsic is not implemented yet!");
808 return;
Chris Lattnerc0f18152005-04-02 05:26:53 +0000809 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000810
Chris Lattner64e14b12005-01-08 22:48:57 +0000811 SDOperand Callee;
812 if (!RenameFn)
813 Callee = getValue(I.getOperand(0));
814 else
815 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +0000816 std::vector<std::pair<SDOperand, const Type*> > Args;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000817
Chris Lattner1c08c712005-01-07 07:47:53 +0000818 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
819 Value *Arg = I.getOperand(i);
820 SDOperand ArgNode = getValue(Arg);
821 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
822 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000823
Nate Begeman8e21e712005-03-26 01:29:23 +0000824 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
825 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000826
Chris Lattnercf5734d2005-01-08 19:26:18 +0000827 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +0000828 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +0000829 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +0000830 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +0000831 setValue(&I, Result.first);
832 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000833}
834
835void SelectionDAGLowering::visitMalloc(MallocInst &I) {
836 SDOperand Src = getValue(I.getOperand(0));
837
838 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +0000839
840 if (IntPtr < Src.getValueType())
841 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
842 else if (IntPtr > Src.getValueType())
843 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +0000844
845 // Scale the source by the type size.
846 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
847 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
848 Src, getIntPtrConstant(ElementSize));
849
850 std::vector<std::pair<SDOperand, const Type*> > Args;
851 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +0000852
853 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000854 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000855 DAG.getExternalSymbol("malloc", IntPtr),
856 Args, DAG);
857 setValue(&I, Result.first); // Pointers always fit in registers
858 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000859}
860
861void SelectionDAGLowering::visitFree(FreeInst &I) {
862 std::vector<std::pair<SDOperand, const Type*> > Args;
863 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
864 TLI.getTargetData().getIntPtrType()));
865 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +0000866 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +0000867 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +0000868 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
869 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000870}
871
Chris Lattner025c39b2005-08-26 20:54:47 +0000872// InsertAtEndOfBasicBlock - This method should be implemented by targets that
873// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
874// instructions are special in various ways, which require special support to
875// insert. The specified MachineInstr is created but not inserted into any
876// basic blocks, and the scheduler passes ownership of it to this method.
877MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
878 MachineBasicBlock *MBB) {
879 std::cerr << "If a target marks an instruction with "
880 "'usesCustomDAGSchedInserter', it must implement "
881 "TargetLowering::InsertAtEndOfBasicBlock!\n";
882 abort();
883 return 0;
884}
885
Chris Lattnere64e72b2005-07-05 19:57:53 +0000886SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
887 SDOperand VAListP, Value *VAListV,
888 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000889 // We have no sane default behavior, just emit a useful error message and bail
890 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +0000891 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +0000892 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +0000893 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +0000894}
895
Chris Lattnere64e72b2005-07-05 19:57:53 +0000896SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +0000897 SelectionDAG &DAG) {
898 // Default to a noop.
899 return Chain;
900}
901
Chris Lattnere64e72b2005-07-05 19:57:53 +0000902SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
903 SDOperand SrcP, Value *SrcV,
904 SDOperand DestP, Value *DestV,
905 SelectionDAG &DAG) {
906 // Default to copying the input list.
907 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
908 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +0000909 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +0000910 Val, DestP, DAG.getSrcValue(DestV));
911 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +0000912}
913
914std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +0000915TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
916 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +0000917 // We have no sane default behavior, just emit a useful error message and bail
918 // out.
919 std::cerr << "Variable arguments handling not implemented on this target!\n";
920 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000921 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +0000922}
923
924
925void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +0000926 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
927 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +0000928}
929
930void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
931 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +0000932 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +0000933 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000934 setValue(&I, Result.first);
935 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000936}
937
938void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +0000939 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +0000940 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000941}
942
943void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +0000944 SDOperand Result =
945 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
946 getValue(I.getOperand(1)), I.getOperand(1), DAG);
947 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +0000948}
949
Chris Lattner39ae3622005-01-09 00:00:49 +0000950
951// It is always conservatively correct for llvm.returnaddress and
952// llvm.frameaddress to return 0.
953std::pair<SDOperand, SDOperand>
954TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
955 unsigned Depth, SelectionDAG &DAG) {
956 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +0000957}
958
Chris Lattner50381b62005-05-14 05:50:48 +0000959SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +0000960 assert(0 && "LowerOperation not implemented for this target!");
961 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +0000962 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +0000963}
964
Chris Lattner39ae3622005-01-09 00:00:49 +0000965void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
966 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
967 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +0000968 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +0000969 setValue(&I, Result.first);
970 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +0000971}
972
Chris Lattner7041ee32005-01-11 05:56:49 +0000973void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
974 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +0000975 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +0000976 Ops.push_back(getValue(I.getOperand(1)));
977 Ops.push_back(getValue(I.getOperand(2)));
978 Ops.push_back(getValue(I.getOperand(3)));
979 Ops.push_back(getValue(I.getOperand(4)));
980 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000981}
982
Chris Lattner7041ee32005-01-11 05:56:49 +0000983//===----------------------------------------------------------------------===//
984// SelectionDAGISel code
985//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000986
987unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
988 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
989}
990
Chris Lattner495a0b52005-08-17 06:37:43 +0000991void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +0000992 // FIXME: we only modify the CFG to split critical edges. This
993 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +0000994}
Chris Lattner1c08c712005-01-07 07:47:53 +0000995
996
997bool SelectionDAGISel::runOnFunction(Function &Fn) {
998 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
999 RegMap = MF.getSSARegMap();
1000 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1001
Chris Lattner495a0b52005-08-17 06:37:43 +00001002 // First pass, split all critical edges for PHI nodes with incoming values
1003 // that are constants, this way the load of the constant into a vreg will not
1004 // be placed into MBBs that are used some other way.
Chris Lattner36b708f2005-08-18 17:35:14 +00001005 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1006 PHINode *PN;
1007 for (BasicBlock::iterator BBI = BB->begin();
1008 (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1009 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1010 if (isa<Constant>(PN->getIncomingValue(i)))
1011 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1012 }
Chris Lattner495a0b52005-08-17 06:37:43 +00001013
Chris Lattner1c08c712005-01-07 07:47:53 +00001014 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1015
1016 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1017 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001018
Chris Lattner1c08c712005-01-07 07:47:53 +00001019 return true;
1020}
1021
1022
Chris Lattnerddb870b2005-01-13 17:59:43 +00001023SDOperand SelectionDAGISel::
1024CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001025 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001026 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001027 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001028 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001029
1030 // If this type is not legal, we must make sure to not create an invalid
1031 // register use.
1032 MVT::ValueType SrcVT = Op.getValueType();
1033 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1034 SelectionDAG &DAG = SDL.DAG;
1035 if (SrcVT == DestVT) {
1036 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1037 } else if (SrcVT < DestVT) {
1038 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001039 if (MVT::isFloatingPoint(SrcVT))
1040 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1041 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001042 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001043 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1044 } else {
1045 // The src value is expanded into multiple registers.
1046 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1047 Op, DAG.getConstant(0, MVT::i32));
1048 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1049 Op, DAG.getConstant(1, MVT::i32));
1050 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1051 return DAG.getCopyToReg(Op, Reg+1, Hi);
1052 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001053}
1054
Chris Lattner0afa8e32005-01-17 17:55:19 +00001055/// IsOnlyUsedInOneBasicBlock - If the specified argument is only used in a
1056/// single basic block, return that block. Otherwise, return a null pointer.
1057static BasicBlock *IsOnlyUsedInOneBasicBlock(Argument *A) {
1058 if (A->use_empty()) return 0;
1059 BasicBlock *BB = cast<Instruction>(A->use_back())->getParent();
1060 for (Argument::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E;
1061 ++UI)
1062 if (isa<PHINode>(*UI) || cast<Instruction>(*UI)->getParent() != BB)
1063 return 0; // Disagreement among the users?
Chris Lattneraa781b32005-02-17 19:40:32 +00001064
1065 // Okay, there is a single BB user. Only permit this optimization if this is
1066 // the entry block, otherwise, we might sink argument loads into loops and
1067 // stuff. Later, when we have global instruction selection, this won't be an
1068 // issue clearly.
1069 if (BB == BB->getParent()->begin())
1070 return BB;
1071 return 0;
Chris Lattner0afa8e32005-01-17 17:55:19 +00001072}
1073
Chris Lattner068a81e2005-01-17 17:15:02 +00001074void SelectionDAGISel::
1075LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1076 std::vector<SDOperand> &UnorderedChains) {
1077 // If this is the entry block, emit arguments.
1078 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001079 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner068a81e2005-01-17 17:15:02 +00001080
1081 if (BB == &F.front()) {
Chris Lattner0afa8e32005-01-17 17:55:19 +00001082 SDOperand OldRoot = SDL.DAG.getRoot();
1083
Chris Lattner068a81e2005-01-17 17:15:02 +00001084 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1085
Chris Lattner0afa8e32005-01-17 17:55:19 +00001086 // If there were side effects accessing the argument list, do not do
1087 // anything special.
1088 if (OldRoot != SDL.DAG.getRoot()) {
1089 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1091 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001092 if (!AI->use_empty()) {
1093 SDL.setValue(AI, Args[a]);
Chris Lattner9d3a4832005-08-26 22:49:59 +00001094
Chris Lattnerfab08872005-09-02 00:19:37 +00001095 SDOperand Copy =
1096 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1097 UnorderedChains.push_back(Copy);
Chris Lattner0afa8e32005-01-17 17:55:19 +00001098 }
1099 } else {
1100 // Otherwise, if any argument is only accessed in a single basic block,
1101 // emit that argument only to that basic block.
1102 unsigned a = 0;
Chris Lattnera33ef482005-03-30 01:10:47 +00001103 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1104 AI != E; ++AI,++a)
Chris Lattner0afa8e32005-01-17 17:55:19 +00001105 if (!AI->use_empty()) {
1106 if (BasicBlock *BBU = IsOnlyUsedInOneBasicBlock(AI)) {
1107 FuncInfo.BlockLocalArguments.insert(std::make_pair(BBU,
1108 std::make_pair(AI, a)));
1109 } else {
1110 SDL.setValue(AI, Args[a]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001111 SDOperand Copy =
Chris Lattner0afa8e32005-01-17 17:55:19 +00001112 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1113 UnorderedChains.push_back(Copy);
1114 }
1115 }
1116 }
Chris Lattner405ef9e2005-05-13 07:33:32 +00001117
1118 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner0afa8e32005-01-17 17:55:19 +00001119 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001120
Chris Lattner0afa8e32005-01-17 17:55:19 +00001121 // See if there are any block-local arguments that need to be emitted in this
1122 // block.
1123
1124 if (!FuncInfo.BlockLocalArguments.empty()) {
1125 std::multimap<BasicBlock*, std::pair<Argument*, unsigned> >::iterator BLAI =
1126 FuncInfo.BlockLocalArguments.lower_bound(BB);
1127 if (BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB) {
1128 // Lower the arguments into this block.
1129 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001130
Chris Lattner0afa8e32005-01-17 17:55:19 +00001131 // Set up the value mapping for the local arguments.
1132 for (; BLAI != FuncInfo.BlockLocalArguments.end() && BLAI->first == BB;
1133 ++BLAI)
1134 SDL.setValue(BLAI->second.first, Args[BLAI->second.second]);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001135
Chris Lattner0afa8e32005-01-17 17:55:19 +00001136 // Any dead arguments will just be ignored here.
1137 }
Chris Lattner068a81e2005-01-17 17:15:02 +00001138 }
1139}
1140
1141
Chris Lattner1c08c712005-01-07 07:47:53 +00001142void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1143 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1144 FunctionLoweringInfo &FuncInfo) {
1145 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001146
1147 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001148
Chris Lattner068a81e2005-01-17 17:15:02 +00001149 // Lower any arguments needed in this block.
1150 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001151
1152 BB = FuncInfo.MBBMap[LLVMBB];
1153 SDL.setCurrentBasicBlock(BB);
1154
1155 // Lower all of the non-terminator instructions.
1156 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1157 I != E; ++I)
1158 SDL.visit(*I);
1159
1160 // Ensure that all instructions which are used outside of their defining
1161 // blocks are available as virtual registers.
1162 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001163 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001164 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001165 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001166 UnorderedChains.push_back(
1167 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001168 }
1169
1170 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1171 // ensure constants are generated when needed. Remember the virtual registers
1172 // that need to be added to the Machine PHI nodes as input. We cannot just
1173 // directly add them, because expansion might result in multiple MBB's for one
1174 // BB. As such, the start of the BB might correspond to a different MBB than
1175 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001176 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001177
1178 // Emit constants only once even if used by multiple PHI nodes.
1179 std::map<Constant*, unsigned> ConstantsOut;
1180
1181 // Check successor nodes PHI nodes that expect a constant to be available from
1182 // this block.
1183 TerminatorInst *TI = LLVMBB->getTerminator();
1184 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1185 BasicBlock *SuccBB = TI->getSuccessor(succ);
1186 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1187 PHINode *PN;
1188
1189 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1190 // nodes and Machine PHI nodes, but the incoming operands have not been
1191 // emitted yet.
1192 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001193 (PN = dyn_cast<PHINode>(I)); ++I)
1194 if (!PN->use_empty()) {
1195 unsigned Reg;
1196 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1197 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1198 unsigned &RegOut = ConstantsOut[C];
1199 if (RegOut == 0) {
1200 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001201 UnorderedChains.push_back(
1202 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001203 }
1204 Reg = RegOut;
1205 } else {
1206 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001207 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001208 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001209 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1210 "Didn't codegen value into a register!??");
1211 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001212 UnorderedChains.push_back(
1213 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001214 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001215 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001216
Chris Lattnerf44fd882005-01-07 21:34:19 +00001217 // Remember that this register needs to added to the machine PHI node as
1218 // the input for this MBB.
1219 unsigned NumElements =
1220 TLI.getNumElements(TLI.getValueType(PN->getType()));
1221 for (unsigned i = 0, e = NumElements; i != e; ++i)
1222 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001223 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001224 }
1225 ConstantsOut.clear();
1226
Chris Lattnerddb870b2005-01-13 17:59:43 +00001227 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001228 if (!UnorderedChains.empty()) {
Chris Lattnerd3948112005-01-17 22:19:26 +00001229 UnorderedChains.push_back(SDL.getRoot());
Chris Lattnerddb870b2005-01-13 17:59:43 +00001230 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1231 }
1232
Chris Lattner1c08c712005-01-07 07:47:53 +00001233 // Lower the terminator after the copies are emitted.
1234 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001235
1236 // Make sure the root of the DAG is up-to-date.
1237 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001238}
1239
1240void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1241 FunctionLoweringInfo &FuncInfo) {
Chris Lattnerac9dc082005-01-23 04:36:26 +00001242 SelectionDAG DAG(TLI, MF);
Chris Lattner1c08c712005-01-07 07:47:53 +00001243 CurDAG = &DAG;
1244 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1245
1246 // First step, lower LLVM code to some DAG. This DAG may use operations and
1247 // types that are not supported by the target.
1248 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1249
Nate Begeman2300f552005-09-07 00:15:36 +00001250 // Run the DAG combiner in pre-legalize mode, if we are told to do so
1251 if (CombinerEnabled) DAG.Combine(false);
1252
Chris Lattner1c08c712005-01-07 07:47:53 +00001253 DEBUG(std::cerr << "Lowered selection DAG:\n");
1254 DEBUG(DAG.dump());
1255
1256 // Second step, hack on the DAG until it only uses operations and types that
1257 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001258 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001259
1260 DEBUG(std::cerr << "Legalized selection DAG:\n");
1261 DEBUG(DAG.dump());
1262
Chris Lattner82cfa5d2005-08-24 00:34:29 +00001263 if (ViewDAGs) DAG.viewGraph();
1264
Nate Begeman2300f552005-09-07 00:15:36 +00001265 // Run the DAG combiner in post-legalize mode, if we are told to do so
1266 if (CombinerEnabled) DAG.Combine(true);
1267
Chris Lattnera33ef482005-03-30 01:10:47 +00001268 // Third, instruction select all of the operations to machine code, adding the
1269 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001270 InstructionSelectBasicBlock(DAG);
1271
Chris Lattner1c08c712005-01-07 07:47:53 +00001272 DEBUG(std::cerr << "Selected machine code:\n");
1273 DEBUG(BB->dump());
1274
Chris Lattnera33ef482005-03-30 01:10:47 +00001275 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001276 // PHI nodes in successors.
1277 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1278 MachineInstr *PHI = PHINodesToUpdate[i].first;
1279 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1280 "This is not a machine PHI node that we are updating!");
1281 PHI->addRegOperand(PHINodesToUpdate[i].second);
1282 PHI->addMachineBasicBlockOperand(BB);
1283 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001284
1285 // Finally, add the CFG edges from the last selected MBB to the successor
1286 // MBBs.
1287 TerminatorInst *TI = LLVMBB->getTerminator();
1288 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1289 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1290 BB->addSuccessor(Succ0MBB);
1291 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001292}