blob: b7dd97c62a7fa7a51021f68a54835d3e41d60c77 [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"
Chris Lattner435b4022005-11-29 06:21:05 +000020#include "llvm/GlobalVariable.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/Instructions.h"
22#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000023#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000024#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/SelectionDAG.h"
29#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000030#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000037#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000038#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000039#include "llvm/Support/Debug.h"
40#include <map>
41#include <iostream>
42using namespace llvm;
43
Chris Lattner975f5c92005-09-01 18:44:10 +000044#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000045static cl::opt<bool>
46ViewDAGs("view-isel-dags", cl::Hidden,
47 cl::desc("Pop up a window to show isel dags as they are selected"));
48#else
Chris Lattnerb6cde172005-09-02 07:09:28 +000049static const bool ViewDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000050#endif
51
Chris Lattner7a60d912005-01-07 07:47:53 +000052namespace llvm {
53 //===--------------------------------------------------------------------===//
54 /// FunctionLoweringInfo - This contains information that is global to a
55 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +000056 class FunctionLoweringInfo {
57 public:
Chris Lattner7a60d912005-01-07 07:47:53 +000058 TargetLowering &TLI;
59 Function &Fn;
60 MachineFunction &MF;
61 SSARegMap *RegMap;
62
63 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
64
65 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
66 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
67
68 /// ValueMap - Since we emit code for the function a basic block at a time,
69 /// we must remember which virtual registers hold the values for
70 /// cross-basic-block values.
71 std::map<const Value*, unsigned> ValueMap;
72
73 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
74 /// the entry block. This allows the allocas to be efficiently referenced
75 /// anywhere in the function.
76 std::map<const AllocaInst*, int> StaticAllocaMap;
77
78 unsigned MakeReg(MVT::ValueType VT) {
79 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
80 }
Misha Brukman835702a2005-04-21 22:36:52 +000081
Chris Lattner7a60d912005-01-07 07:47:53 +000082 unsigned CreateRegForValue(const Value *V) {
83 MVT::ValueType VT = TLI.getValueType(V->getType());
84 // The common case is that we will only create one register for this
85 // value. If we have that case, create and return the virtual register.
86 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +000087 if (NV == 1) {
88 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +000089 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +000090 }
Misha Brukman835702a2005-04-21 22:36:52 +000091
Chris Lattner7a60d912005-01-07 07:47:53 +000092 // If this value is represented with multiple target registers, make sure
93 // to create enough consequtive registers of the right (smaller) type.
94 unsigned NT = VT-1; // Find the type to use.
95 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
96 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +000097
Chris Lattner7a60d912005-01-07 07:47:53 +000098 unsigned R = MakeReg((MVT::ValueType)NT);
99 for (unsigned i = 1; i != NV; ++i)
100 MakeReg((MVT::ValueType)NT);
101 return R;
102 }
Misha Brukman835702a2005-04-21 22:36:52 +0000103
Chris Lattner7a60d912005-01-07 07:47:53 +0000104 unsigned InitializeRegForValue(const Value *V) {
105 unsigned &R = ValueMap[V];
106 assert(R == 0 && "Already initialized this value register!");
107 return R = CreateRegForValue(V);
108 }
109 };
110}
111
112/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
113/// PHI nodes or outside of the basic block that defines it.
114static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
115 if (isa<PHINode>(I)) return true;
116 BasicBlock *BB = I->getParent();
117 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
118 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
119 return true;
120 return false;
121}
122
Chris Lattner6871b232005-10-30 19:42:35 +0000123/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
124/// entry block, return true.
125static bool isOnlyUsedInEntryBlock(Argument *A) {
126 BasicBlock *Entry = A->getParent()->begin();
127 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
128 if (cast<Instruction>(*UI)->getParent() != Entry)
129 return false; // Use not in entry block.
130 return true;
131}
132
Chris Lattner7a60d912005-01-07 07:47:53 +0000133FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000134 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000135 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
136
Chris Lattner6871b232005-10-30 19:42:35 +0000137 // Create a vreg for each argument register that is not dead and is used
138 // outside of the entry block for the function.
139 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
140 AI != E; ++AI)
141 if (!isOnlyUsedInEntryBlock(AI))
142 InitializeRegForValue(AI);
143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144 // Initialize the mapping of values to registers. This is only set up for
145 // instruction values that are used outside of the block that defines
146 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000147 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000148 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
149 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
150 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
151 const Type *Ty = AI->getAllocatedType();
152 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000153 unsigned Align =
154 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
155 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000156
157 // If the alignment of the value is smaller than the size of the value,
158 // and if the size of the value is particularly small (<= 8 bytes),
159 // round up to the size of the value for potentially better performance.
160 //
161 // FIXME: This could be made better with a preferred alignment hook in
162 // TargetData. It serves primarily to 8-byte align doubles for X86.
163 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000164 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000165 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000166 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000167 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000168 }
169
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000170 for (; BB != EB; ++BB)
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000172 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
173 if (!isa<AllocaInst>(I) ||
174 !StaticAllocaMap.count(cast<AllocaInst>(I)))
175 InitializeRegForValue(I);
176
177 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
178 // also creates the initial PHI MachineInstrs, though none of the input
179 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000180 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000181 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
182 MBBMap[BB] = MBB;
183 MF.getBasicBlockList().push_back(MBB);
184
185 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
186 // appropriate.
187 PHINode *PN;
188 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000189 (PN = dyn_cast<PHINode>(I)); ++I)
190 if (!PN->use_empty()) {
191 unsigned NumElements =
192 TLI.getNumElements(TLI.getValueType(PN->getType()));
193 unsigned PHIReg = ValueMap[PN];
194 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
195 for (unsigned i = 0; i != NumElements; ++i)
196 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
197 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000198 }
199}
200
201
202
203//===----------------------------------------------------------------------===//
204/// SelectionDAGLowering - This is the common target-independent lowering
205/// implementation that is parameterized by a TargetLowering object.
206/// Also, targets can overload any lowering method.
207///
208namespace llvm {
209class SelectionDAGLowering {
210 MachineBasicBlock *CurMBB;
211
212 std::map<const Value*, SDOperand> NodeMap;
213
Chris Lattner4d9651c2005-01-17 22:19:26 +0000214 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
215 /// them up and then emit token factor nodes when possible. This allows us to
216 /// get simple disambiguation between loads without worrying about alias
217 /// analysis.
218 std::vector<SDOperand> PendingLoads;
219
Chris Lattner7a60d912005-01-07 07:47:53 +0000220public:
221 // TLI - This is information that describes the available target features we
222 // need for lowering. This indicates when operations are unavailable,
223 // implemented with a libcall, etc.
224 TargetLowering &TLI;
225 SelectionDAG &DAG;
226 const TargetData &TD;
227
228 /// FuncInfo - Information about the function as a whole.
229 ///
230 FunctionLoweringInfo &FuncInfo;
231
232 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000233 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000234 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
235 FuncInfo(funcinfo) {
236 }
237
Chris Lattner4108bb02005-01-17 19:43:36 +0000238 /// getRoot - Return the current virtual root of the Selection DAG.
239 ///
240 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000241 if (PendingLoads.empty())
242 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000243
Chris Lattner4d9651c2005-01-17 22:19:26 +0000244 if (PendingLoads.size() == 1) {
245 SDOperand Root = PendingLoads[0];
246 DAG.setRoot(Root);
247 PendingLoads.clear();
248 return Root;
249 }
250
251 // Otherwise, we have to make a token factor node.
252 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
253 PendingLoads.clear();
254 DAG.setRoot(Root);
255 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000256 }
257
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 void visit(Instruction &I) { visit(I.getOpcode(), I); }
259
260 void visit(unsigned Opcode, User &I) {
261 switch (Opcode) {
262 default: assert(0 && "Unknown instruction type encountered!");
263 abort();
264 // Build the switch statement using the Instruction.def file.
265#define HANDLE_INST(NUM, OPCODE, CLASS) \
266 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
267#include "llvm/Instruction.def"
268 }
269 }
270
271 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
272
273
274 SDOperand getIntPtrConstant(uint64_t Val) {
275 return DAG.getConstant(Val, TLI.getPointerTy());
276 }
277
278 SDOperand getValue(const Value *V) {
279 SDOperand &N = NodeMap[V];
280 if (N.Val) return N;
281
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000282 const Type *VTy = V->getType();
283 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000284 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
286 visit(CE->getOpcode(), *CE);
287 assert(N.Val && "visit didn't populate the ValueMap!");
288 return N;
289 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
290 return N = DAG.getGlobalAddress(GV, VT);
291 } else if (isa<ConstantPointerNull>(C)) {
292 return N = DAG.getConstant(0, TLI.getPointerTy());
293 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000294 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000295 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
296 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000297 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
298 unsigned NumElements = PTy->getNumElements();
299 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
300 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
301
302 // Now that we know the number and type of the elements, push a
303 // Constant or ConstantFP node onto the ops list for each element of
304 // the packed constant.
305 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000306 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
307 if (MVT::isFloatingPoint(PVT)) {
308 for (unsigned i = 0; i != NumElements; ++i) {
309 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
310 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
311 }
312 } else {
313 for (unsigned i = 0; i != NumElements; ++i) {
314 const ConstantIntegral *El =
315 cast<ConstantIntegral>(CP->getOperand(i));
316 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
317 }
318 }
319 } else {
320 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
321 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000322 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000323 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000324 else
Chris Lattner803a5752005-12-21 02:43:26 +0000325 Op = DAG.getConstant(0, PVT);
326 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000327 }
Chris Lattner803a5752005-12-21 02:43:26 +0000328
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000329 // Handle the case where we have a 1-element vector, in which
330 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000331 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000332 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000333 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
334 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
335 } else {
336 // If the packed type isn't legal, then create a ConstantVec node with
337 // generic Vector type instead.
338 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
339 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000340 } else {
341 // Canonicalize all constant ints to be unsigned.
342 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
343 }
344
345 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
346 std::map<const AllocaInst*, int>::iterator SI =
347 FuncInfo.StaticAllocaMap.find(AI);
348 if (SI != FuncInfo.StaticAllocaMap.end())
349 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
350 }
351
352 std::map<const Value*, unsigned>::const_iterator VMI =
353 FuncInfo.ValueMap.find(V);
354 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000355
Chris Lattner33182322005-08-16 21:55:35 +0000356 unsigned InReg = VMI->second;
357
358 // If this type is not legal, make it so now.
359 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
360
361 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
362 if (DestVT < VT) {
363 // Source must be expanded. This input value is actually coming from the
364 // register pair VMI->second and VMI->second+1.
365 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
366 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
367 } else {
368 if (DestVT > VT) { // Promotion case
369 if (MVT::isFloatingPoint(VT))
370 N = DAG.getNode(ISD::FP_ROUND, VT, N);
371 else
372 N = DAG.getNode(ISD::TRUNCATE, VT, N);
373 }
374 }
375
376 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000377 }
378
379 const SDOperand &setValue(const Value *V, SDOperand NewN) {
380 SDOperand &N = NodeMap[V];
381 assert(N.Val == 0 && "Already set a value for this node!");
382 return N = NewN;
383 }
384
385 // Terminator instructions.
386 void visitRet(ReturnInst &I);
387 void visitBr(BranchInst &I);
388 void visitUnreachable(UnreachableInst &I) { /* noop */ }
389
390 // These all get lowered before this pass.
391 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
392 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
393 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
394
395 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000396 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000397 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000398 void visitAdd(User &I) {
399 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000400 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000401 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000402 void visitMul(User &I) {
403 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000404 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000405 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000406 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000407 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000408 }
409 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000410 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000411 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000412 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000413 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
414 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
415 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000416 void visitShl(User &I) { visitShift(I, ISD::SHL); }
417 void visitShr(User &I) {
418 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000419 }
420
421 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
422 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
423 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
424 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
425 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
426 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
427 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
428
429 void visitGetElementPtr(User &I);
430 void visitCast(User &I);
431 void visitSelect(User &I);
432 //
433
434 void visitMalloc(MallocInst &I);
435 void visitFree(FreeInst &I);
436 void visitAlloca(AllocaInst &I);
437 void visitLoad(LoadInst &I);
438 void visitStore(StoreInst &I);
439 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
440 void visitCall(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000441 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000442
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000444 void visitVAArg(VAArgInst &I);
445 void visitVAEnd(CallInst &I);
446 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000447 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000448
Chris Lattner875def92005-01-11 05:56:49 +0000449 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000450
451 void visitUserOp1(Instruction &I) {
452 assert(0 && "UserOp1 should not exist at instruction selection time!");
453 abort();
454 }
455 void visitUserOp2(Instruction &I) {
456 assert(0 && "UserOp2 should not exist at instruction selection time!");
457 abort();
458 }
459};
460} // end namespace llvm
461
462void SelectionDAGLowering::visitRet(ReturnInst &I) {
463 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000464 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000465 return;
466 }
467
468 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000469 MVT::ValueType TmpVT;
470
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 switch (Op1.getValueType()) {
472 default: assert(0 && "Unknown value type!");
473 case MVT::i1:
474 case MVT::i8:
475 case MVT::i16:
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000476 case MVT::i32:
477 // If this is a machine where 32-bits is legal or expanded, promote to
478 // 32-bits, otherwise, promote to 64-bits.
479 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
480 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner7a60d912005-01-07 07:47:53 +0000481 else
Chris Lattnerdb45f7d2005-03-29 19:09:56 +0000482 TmpVT = MVT::i32;
483
484 // Extend integer types to result type.
485 if (I.getOperand(0)->getType()->isSigned())
486 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
487 else
488 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 break;
490 case MVT::f32:
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 case MVT::i64:
492 case MVT::f64:
493 break; // No extension needed!
494 }
Nate Begeman78afac22005-10-18 23:23:37 +0000495 // Allow targets to lower this further to meet ABI requirements
496 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +0000497}
498
499void SelectionDAGLowering::visitBr(BranchInst &I) {
500 // Update machine-CFG edges.
501 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000502
503 // Figure out which block is immediately after the current one.
504 MachineBasicBlock *NextBlock = 0;
505 MachineFunction::iterator BBI = CurMBB;
506 if (++BBI != CurMBB->getParent()->end())
507 NextBlock = BBI;
508
509 if (I.isUnconditional()) {
510 // If this is not a fall-through branch, emit the branch.
511 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000512 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000513 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000514 } else {
515 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000516
517 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000518 if (Succ1MBB == NextBlock) {
519 // If the condition is false, fall through. This means we should branch
520 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000521 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000522 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000523 } else if (Succ0MBB == NextBlock) {
524 // If the condition is true, fall through. This means we should branch if
525 // the condition is false to Succ #1. Invert the condition first.
526 SDOperand True = DAG.getConstant(1, Cond.getValueType());
527 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000528 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000529 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000530 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000531 std::vector<SDOperand> Ops;
532 Ops.push_back(getRoot());
533 Ops.push_back(Cond);
534 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
535 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
536 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000537 }
538 }
539}
540
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000541void SelectionDAGLowering::visitSub(User &I) {
542 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000543 if (I.getType()->isFloatingPoint()) {
544 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
545 if (CFP->isExactlyValue(-0.0)) {
546 SDOperand Op2 = getValue(I.getOperand(1));
547 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
548 return;
549 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000550 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000551 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000552}
553
Nate Begemanb2e089c2005-11-19 00:36:38 +0000554void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
555 unsigned VecOp) {
556 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000557 SDOperand Op1 = getValue(I.getOperand(0));
558 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000559
Chris Lattner19baba62005-11-19 18:40:42 +0000560 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000561 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
562 } else if (Ty->isFloatingPoint()) {
563 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
564 } else {
565 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000566 unsigned NumElements = PTy->getNumElements();
567 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000568 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000569
570 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000571 // the Legalize pass does not have to deal with them. Similarly, if the
572 // abstract vector is going to turn into one that the target natively
573 // supports, generate that type now so that Legalize doesn't have to deal
574 // with that either. These steps ensure that Legalize only has to handle
575 // vector types in its Expand case.
576 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000577 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000578 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000579 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
580 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000581 } else {
582 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
583 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000584 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000585 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000586 }
Nate Begeman127321b2005-11-18 07:42:56 +0000587}
Chris Lattner96c26752005-01-19 22:31:21 +0000588
Nate Begeman127321b2005-11-18 07:42:56 +0000589void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
590 SDOperand Op1 = getValue(I.getOperand(0));
591 SDOperand Op2 = getValue(I.getOperand(1));
592
593 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
594
Chris Lattner7a60d912005-01-07 07:47:53 +0000595 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
596}
597
598void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
599 ISD::CondCode UnsignedOpcode) {
600 SDOperand Op1 = getValue(I.getOperand(0));
601 SDOperand Op2 = getValue(I.getOperand(1));
602 ISD::CondCode Opcode = SignedOpcode;
603 if (I.getOperand(0)->getType()->isUnsigned())
604 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000605 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000606}
607
608void SelectionDAGLowering::visitSelect(User &I) {
609 SDOperand Cond = getValue(I.getOperand(0));
610 SDOperand TrueVal = getValue(I.getOperand(1));
611 SDOperand FalseVal = getValue(I.getOperand(2));
612 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
613 TrueVal, FalseVal));
614}
615
616void SelectionDAGLowering::visitCast(User &I) {
617 SDOperand N = getValue(I.getOperand(0));
618 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
619 MVT::ValueType DestTy = TLI.getValueType(I.getType());
620
621 if (N.getValueType() == DestTy) {
622 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000623 } else if (DestTy == MVT::i1) {
624 // Cast to bool is a comparison against zero, not truncation to zero.
625 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
626 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000627 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000628 } else if (isInteger(SrcTy)) {
629 if (isInteger(DestTy)) { // Int -> Int cast
630 if (DestTy < SrcTy) // Truncating cast?
631 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
632 else if (I.getOperand(0)->getType()->isSigned())
633 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
634 else
635 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
636 } else { // Int -> FP cast
637 if (I.getOperand(0)->getType()->isSigned())
638 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
639 else
640 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
641 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000642 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000643 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
644 if (isFloatingPoint(DestTy)) { // FP -> FP cast
645 if (DestTy < SrcTy) // Rounding cast?
646 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
647 else
648 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
649 } else { // FP -> Int cast.
650 if (I.getType()->isSigned())
651 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
652 else
653 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
654 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000655 }
656}
657
658void SelectionDAGLowering::visitGetElementPtr(User &I) {
659 SDOperand N = getValue(I.getOperand(0));
660 const Type *Ty = I.getOperand(0)->getType();
661 const Type *UIntPtrTy = TD.getIntPtrType();
662
663 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
664 OI != E; ++OI) {
665 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000666 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000667 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
668 if (Field) {
669 // N = N + Offset
670 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
671 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000672 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000673 }
674 Ty = StTy->getElementType(Field);
675 } else {
676 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000677
Chris Lattner43535a12005-11-09 04:45:33 +0000678 // If this is a constant subscript, handle it quickly.
679 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
680 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000681
Chris Lattner43535a12005-11-09 04:45:33 +0000682 uint64_t Offs;
683 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
684 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
685 else
686 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
687 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
688 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000689 }
Chris Lattner43535a12005-11-09 04:45:33 +0000690
691 // N = N + Idx * ElementSize;
692 uint64_t ElementSize = TD.getTypeSize(Ty);
693 SDOperand IdxN = getValue(Idx);
694
695 // If the index is smaller or larger than intptr_t, truncate or extend
696 // it.
697 if (IdxN.getValueType() < N.getValueType()) {
698 if (Idx->getType()->isSigned())
699 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
700 else
701 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
702 } else if (IdxN.getValueType() > N.getValueType())
703 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
704
705 // If this is a multiply by a power of two, turn it into a shl
706 // immediately. This is a very common case.
707 if (isPowerOf2_64(ElementSize)) {
708 unsigned Amt = Log2_64(ElementSize);
709 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000710 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000711 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
712 continue;
713 }
714
715 SDOperand Scale = getIntPtrConstant(ElementSize);
716 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
717 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000718 }
719 }
720 setValue(&I, N);
721}
722
723void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
724 // If this is a fixed sized alloca in the entry block of the function,
725 // allocate it statically on the stack.
726 if (FuncInfo.StaticAllocaMap.count(&I))
727 return; // getValue will auto-populate this.
728
729 const Type *Ty = I.getAllocatedType();
730 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000731 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
732 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000733
734 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000735 MVT::ValueType IntPtr = TLI.getPointerTy();
736 if (IntPtr < AllocSize.getValueType())
737 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
738 else if (IntPtr > AllocSize.getValueType())
739 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000740
Chris Lattnereccb73d2005-01-22 23:04:37 +0000741 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000742 getIntPtrConstant(TySize));
743
744 // Handle alignment. If the requested alignment is less than or equal to the
745 // stack alignment, ignore it and round the size of the allocation up to the
746 // stack alignment size. If the size is greater than the stack alignment, we
747 // note this in the DYNAMIC_STACKALLOC node.
748 unsigned StackAlign =
749 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
750 if (Align <= StackAlign) {
751 Align = 0;
752 // Add SA-1 to the size.
753 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
754 getIntPtrConstant(StackAlign-1));
755 // Mask out the low bits for alignment purposes.
756 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
757 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
758 }
759
Chris Lattner96c262e2005-05-14 07:29:57 +0000760 std::vector<MVT::ValueType> VTs;
761 VTs.push_back(AllocSize.getValueType());
762 VTs.push_back(MVT::Other);
763 std::vector<SDOperand> Ops;
764 Ops.push_back(getRoot());
765 Ops.push_back(AllocSize);
766 Ops.push_back(getIntPtrConstant(Align));
767 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000768 DAG.setRoot(setValue(&I, DSA).getValue(1));
769
770 // Inform the Frame Information that we have just allocated a variable-sized
771 // object.
772 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
773}
774
Chris Lattner435b4022005-11-29 06:21:05 +0000775/// getStringValue - Turn an LLVM constant pointer that eventually points to a
776/// global into a string value. Return an empty string if we can't do it.
777///
778static std::string getStringValue(Value *V, unsigned Offset = 0) {
779 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
780 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
781 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
782 if (Init->isString()) {
783 std::string Result = Init->getAsString();
784 if (Offset < Result.size()) {
785 // If we are pointing INTO The string, erase the beginning...
786 Result.erase(Result.begin(), Result.begin()+Offset);
787
788 // Take off the null terminator, and any string fragments after it.
789 std::string::size_type NullPos = Result.find_first_of((char)0);
790 if (NullPos != std::string::npos)
791 Result.erase(Result.begin()+NullPos, Result.end());
792 return Result;
793 }
794 }
795 }
796 } else if (Constant *C = dyn_cast<Constant>(V)) {
797 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
798 return getStringValue(GV, Offset);
799 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
800 if (CE->getOpcode() == Instruction::GetElementPtr) {
801 // Turn a gep into the specified offset.
802 if (CE->getNumOperands() == 3 &&
803 cast<Constant>(CE->getOperand(1))->isNullValue() &&
804 isa<ConstantInt>(CE->getOperand(2))) {
805 return getStringValue(CE->getOperand(0),
806 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
807 }
808 }
809 }
810 }
811 return "";
812}
Chris Lattner7a60d912005-01-07 07:47:53 +0000813
814void SelectionDAGLowering::visitLoad(LoadInst &I) {
815 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000816
Chris Lattner4d9651c2005-01-17 22:19:26 +0000817 SDOperand Root;
818 if (I.isVolatile())
819 Root = getRoot();
820 else {
821 // Do not serialize non-volatile loads against each other.
822 Root = DAG.getRoot();
823 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000824
825 const Type *Ty = I.getType();
826 SDOperand L;
827
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000828 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000829 unsigned NumElements = PTy->getNumElements();
830 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000831 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000832
833 // Immediately scalarize packed types containing only one element, so that
834 // the Legalize pass does not have to deal with them.
835 if (NumElements == 1) {
836 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000837 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
838 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000839 } else {
840 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
841 DAG.getSrcValue(I.getOperand(0)));
842 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000843 } else {
844 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
845 DAG.getSrcValue(I.getOperand(0)));
846 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000847 setValue(&I, L);
848
849 if (I.isVolatile())
850 DAG.setRoot(L.getValue(1));
851 else
852 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000853}
854
855
856void SelectionDAGLowering::visitStore(StoreInst &I) {
857 Value *SrcV = I.getOperand(0);
858 SDOperand Src = getValue(SrcV);
859 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000860 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000861 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000862}
863
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000864/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
865/// we want to emit this as a call to a named external function, return the name
866/// otherwise lower it and return null.
867const char *
868SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
869 switch (Intrinsic) {
870 case Intrinsic::vastart: visitVAStart(I); return 0;
871 case Intrinsic::vaend: visitVAEnd(I); return 0;
872 case Intrinsic::vacopy: visitVACopy(I); return 0;
873 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
874 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
875 case Intrinsic::setjmp:
876 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
877 break;
878 case Intrinsic::longjmp:
879 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
880 break;
881 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
882 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
883 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
884
885 case Intrinsic::readport:
886 case Intrinsic::readio: {
887 std::vector<MVT::ValueType> VTs;
888 VTs.push_back(TLI.getValueType(I.getType()));
889 VTs.push_back(MVT::Other);
890 std::vector<SDOperand> Ops;
891 Ops.push_back(getRoot());
892 Ops.push_back(getValue(I.getOperand(1)));
893 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
894 ISD::READPORT : ISD::READIO, VTs, Ops);
895
896 setValue(&I, Tmp);
897 DAG.setRoot(Tmp.getValue(1));
898 return 0;
899 }
900 case Intrinsic::writeport:
901 case Intrinsic::writeio:
902 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
903 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
904 getRoot(), getValue(I.getOperand(1)),
905 getValue(I.getOperand(2))));
906 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000907
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000908 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000909 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
910 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000911
912 std::string fname = "<unknown>";
913 std::vector<SDOperand> Ops;
914
Chris Lattner435b4022005-11-29 06:21:05 +0000915 // Input Chain
916 Ops.push_back(getRoot());
917
918 // line number
919 Ops.push_back(getValue(I.getOperand(2)));
920
921 // column
922 Ops.push_back(getValue(I.getOperand(3)));
923
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000924 // filename/working dir
925 // Pull the filename out of the the compilation unit.
926 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
927 if (cunit && cunit->hasInitializer()) {
928 if (ConstantStruct *CS =
929 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
930 if (CS->getNumOperands() > 0) {
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000931 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskey7c462762005-12-16 22:45:29 +0000932 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000933 }
934 }
935 }
936
937 if (Ops.size() == 5) // Found filename/workingdir.
938 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner8782b782005-12-03 18:50:48 +0000939 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000940 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000941 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000942 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000943 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
944 return "llvm_dbg_region_start";
945 if (I.getType() != Type::VoidTy)
946 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
947 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000948 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000949 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
950 return "llvm_dbg_region_end";
951 if (I.getType() != Type::VoidTy)
952 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
953 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000954 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000955 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
956 return "llvm_dbg_subprogram";
957 if (I.getType() != Type::VoidTy)
958 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
959 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000960 case Intrinsic::dbg_declare:
961 if (I.getType() != Type::VoidTy)
962 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
963 return 0;
964
965 case Intrinsic::isunordered:
966 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
967 getValue(I.getOperand(2)), ISD::SETUO));
968 return 0;
969
970 case Intrinsic::sqrt:
971 setValue(&I, DAG.getNode(ISD::FSQRT,
972 getValue(I.getOperand(1)).getValueType(),
973 getValue(I.getOperand(1))));
974 return 0;
975 case Intrinsic::pcmarker: {
976 SDOperand Tmp = getValue(I.getOperand(1));
977 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
978 return 0;
979 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000980 case Intrinsic::readcyclecounter: {
981 std::vector<MVT::ValueType> VTs;
982 VTs.push_back(MVT::i64);
983 VTs.push_back(MVT::Other);
984 std::vector<SDOperand> Ops;
985 Ops.push_back(getRoot());
986 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
987 setValue(&I, Tmp);
988 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +0000989 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +0000990 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000991 case Intrinsic::cttz:
992 setValue(&I, DAG.getNode(ISD::CTTZ,
993 getValue(I.getOperand(1)).getValueType(),
994 getValue(I.getOperand(1))));
995 return 0;
996 case Intrinsic::ctlz:
997 setValue(&I, DAG.getNode(ISD::CTLZ,
998 getValue(I.getOperand(1)).getValueType(),
999 getValue(I.getOperand(1))));
1000 return 0;
1001 case Intrinsic::ctpop:
1002 setValue(&I, DAG.getNode(ISD::CTPOP,
1003 getValue(I.getOperand(1)).getValueType(),
1004 getValue(I.getOperand(1))));
1005 return 0;
Chris Lattner9e8b6332005-12-12 22:51:16 +00001006 case Intrinsic::prefetch:
1007 // FIXME: Currently discarding prefetches.
1008 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001009 default:
1010 std::cerr << I;
1011 assert(0 && "This intrinsic is not implemented yet!");
1012 return 0;
1013 }
1014}
1015
1016
Chris Lattner7a60d912005-01-07 07:47:53 +00001017void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001018 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001019 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001020 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001021 if (unsigned IID = F->getIntrinsicID()) {
1022 RenameFn = visitIntrinsicCall(I, IID);
1023 if (!RenameFn)
1024 return;
1025 } else { // Not an LLVM intrinsic.
1026 const std::string &Name = F->getName();
1027 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001028 if (I.getNumOperands() == 2 && // Basic sanity checks.
1029 I.getOperand(1)->getType()->isFloatingPoint() &&
1030 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001031 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001032 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1033 return;
1034 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001035 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001036 if (I.getNumOperands() == 2 && // Basic sanity checks.
1037 I.getOperand(1)->getType()->isFloatingPoint() &&
1038 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001039 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001040 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1041 return;
1042 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001043 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001044 if (I.getNumOperands() == 2 && // Basic sanity checks.
1045 I.getOperand(1)->getType()->isFloatingPoint() &&
1046 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001047 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001048 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1049 return;
1050 }
1051 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001052 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001053 }
Misha Brukman835702a2005-04-21 22:36:52 +00001054
Chris Lattner18d2b342005-01-08 22:48:57 +00001055 SDOperand Callee;
1056 if (!RenameFn)
1057 Callee = getValue(I.getOperand(0));
1058 else
1059 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001060 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001061 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001062 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1063 Value *Arg = I.getOperand(i);
1064 SDOperand ArgNode = getValue(Arg);
1065 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1066 }
Misha Brukman835702a2005-04-21 22:36:52 +00001067
Nate Begemanf6565252005-03-26 01:29:23 +00001068 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1069 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001070
Chris Lattner1f45cd72005-01-08 19:26:18 +00001071 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001072 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001073 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001074 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001075 setValue(&I, Result.first);
1076 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001077}
1078
1079void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1080 SDOperand Src = getValue(I.getOperand(0));
1081
1082 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001083
1084 if (IntPtr < Src.getValueType())
1085 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1086 else if (IntPtr > Src.getValueType())
1087 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001088
1089 // Scale the source by the type size.
1090 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1091 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1092 Src, getIntPtrConstant(ElementSize));
1093
1094 std::vector<std::pair<SDOperand, const Type*> > Args;
1095 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001096
1097 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001098 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001099 DAG.getExternalSymbol("malloc", IntPtr),
1100 Args, DAG);
1101 setValue(&I, Result.first); // Pointers always fit in registers
1102 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001103}
1104
1105void SelectionDAGLowering::visitFree(FreeInst &I) {
1106 std::vector<std::pair<SDOperand, const Type*> > Args;
1107 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1108 TLI.getTargetData().getIntPtrType()));
1109 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001110 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001111 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001112 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1113 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001114}
1115
Chris Lattner13d7c252005-08-26 20:54:47 +00001116// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1117// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1118// instructions are special in various ways, which require special support to
1119// insert. The specified MachineInstr is created but not inserted into any
1120// basic blocks, and the scheduler passes ownership of it to this method.
1121MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1122 MachineBasicBlock *MBB) {
1123 std::cerr << "If a target marks an instruction with "
1124 "'usesCustomDAGSchedInserter', it must implement "
1125 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1126 abort();
1127 return 0;
1128}
1129
Nate Begeman78afac22005-10-18 23:23:37 +00001130SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1131 SelectionDAG &DAG) {
1132 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1133}
1134
Chris Lattnerf5473e42005-07-05 19:57:53 +00001135SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1136 SDOperand VAListP, Value *VAListV,
1137 SelectionDAG &DAG) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001138 // We have no sane default behavior, just emit a useful error message and bail
1139 // out.
Chris Lattner58cfd792005-01-09 00:00:49 +00001140 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00001141 abort();
Chris Lattnerf5473e42005-07-05 19:57:53 +00001142 return SDOperand();
Chris Lattner7a60d912005-01-07 07:47:53 +00001143}
1144
Chris Lattnerf5473e42005-07-05 19:57:53 +00001145SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner58cfd792005-01-09 00:00:49 +00001146 SelectionDAG &DAG) {
1147 // Default to a noop.
1148 return Chain;
1149}
1150
Chris Lattnerf5473e42005-07-05 19:57:53 +00001151SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1152 SDOperand SrcP, Value *SrcV,
1153 SDOperand DestP, Value *DestV,
1154 SelectionDAG &DAG) {
1155 // Default to copying the input list.
1156 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1157 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth25314522005-06-22 21:04:42 +00001158 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001159 Val, DestP, DAG.getSrcValue(DestV));
1160 return Result;
Chris Lattner58cfd792005-01-09 00:00:49 +00001161}
1162
1163std::pair<SDOperand,SDOperand>
Chris Lattnerf5473e42005-07-05 19:57:53 +00001164TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1165 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner58cfd792005-01-09 00:00:49 +00001166 // We have no sane default behavior, just emit a useful error message and bail
1167 // out.
1168 std::cerr << "Variable arguments handling not implemented on this target!\n";
1169 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001170 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner58cfd792005-01-09 00:00:49 +00001171}
1172
1173
1174void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001175 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1176 I.getOperand(1), DAG));
Chris Lattner58cfd792005-01-09 00:00:49 +00001177}
1178
1179void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1180 std::pair<SDOperand,SDOperand> Result =
Chris Lattnerf5473e42005-07-05 19:57:53 +00001181 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth9144ec42005-06-18 18:34:52 +00001182 I.getType(), DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001183 setValue(&I, Result.first);
1184 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001185}
1186
1187void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001188 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnerf5473e42005-07-05 19:57:53 +00001189 I.getOperand(1), DAG));
Chris Lattner7a60d912005-01-07 07:47:53 +00001190}
1191
1192void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnerf5473e42005-07-05 19:57:53 +00001193 SDOperand Result =
1194 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1195 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1196 DAG.setRoot(Result);
Chris Lattner7a60d912005-01-07 07:47:53 +00001197}
1198
Chris Lattner58cfd792005-01-09 00:00:49 +00001199
1200// It is always conservatively correct for llvm.returnaddress and
1201// llvm.frameaddress to return 0.
1202std::pair<SDOperand, SDOperand>
1203TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1204 unsigned Depth, SelectionDAG &DAG) {
1205 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001206}
1207
Chris Lattner29dcc712005-05-14 05:50:48 +00001208SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001209 assert(0 && "LowerOperation not implemented for this target!");
1210 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001211 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001212}
1213
Chris Lattner58cfd792005-01-09 00:00:49 +00001214void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1215 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1216 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001217 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001218 setValue(&I, Result.first);
1219 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001220}
1221
Chris Lattner875def92005-01-11 05:56:49 +00001222void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer3fd1b4c2005-11-30 05:21:10 +00001223#if 0
1224 // If the size of the cpy/move/set is constant (known)
1225 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1226 uint64_t size = op3->getValue();
1227 switch (Op) {
1228 case ISD::MEMSET:
1229 if (size <= TLI.getMaxStoresPerMemSet()) {
1230 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1231 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1232 uint64_t align = op4.getValue();
1233 while (size > align) {
1234 size -=align;
1235 }
1236 Value *SrcV = I.getOperand(0);
1237 SDOperand Src = getValue(SrcV);
1238 SDOperand Ptr = getValue(I.getOperand(1));
1239 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1240 DAG.getSrcValue(I.getOperand(1))));
1241 }
1242 break;
1243 }
1244 break; // don't do this optimization, use a normal memset
1245 case ISD::MEMMOVE:
1246 case ISD::MEMCPY:
1247 break; // FIXME: not implemented yet
1248 }
1249 }
1250#endif
1251
1252 // Non-optimized version
Chris Lattner875def92005-01-11 05:56:49 +00001253 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001254 Ops.push_back(getRoot());
Chris Lattner875def92005-01-11 05:56:49 +00001255 Ops.push_back(getValue(I.getOperand(1)));
1256 Ops.push_back(getValue(I.getOperand(2)));
1257 Ops.push_back(getValue(I.getOperand(3)));
1258 Ops.push_back(getValue(I.getOperand(4)));
1259 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001260}
1261
Chris Lattner875def92005-01-11 05:56:49 +00001262//===----------------------------------------------------------------------===//
1263// SelectionDAGISel code
1264//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001265
1266unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1267 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1268}
1269
Chris Lattnerc9950c12005-08-17 06:37:43 +00001270void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001271 // FIXME: we only modify the CFG to split critical edges. This
1272 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001273}
Chris Lattner7a60d912005-01-07 07:47:53 +00001274
Chris Lattner35397782005-12-05 07:10:48 +00001275
1276/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1277/// casting to the type of GEPI.
1278static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1279 Value *Ptr, Value *PtrOffset) {
1280 if (V) return V; // Already computed.
1281
1282 BasicBlock::iterator InsertPt;
1283 if (BB == GEPI->getParent()) {
1284 // If insert into the GEP's block, insert right after the GEP.
1285 InsertPt = GEPI;
1286 ++InsertPt;
1287 } else {
1288 // Otherwise, insert at the top of BB, after any PHI nodes
1289 InsertPt = BB->begin();
1290 while (isa<PHINode>(InsertPt)) ++InsertPt;
1291 }
1292
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001293 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1294 // BB so that there is only one value live across basic blocks (the cast
1295 // operand).
1296 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1297 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1298 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1299
Chris Lattner35397782005-12-05 07:10:48 +00001300 // Add the offset, cast it to the right type.
1301 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1302 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1303 return V = Ptr;
1304}
1305
1306
1307/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1308/// selection, we want to be a bit careful about some things. In particular, if
1309/// we have a GEP instruction that is used in a different block than it is
1310/// defined, the addressing expression of the GEP cannot be folded into loads or
1311/// stores that use it. In this case, decompose the GEP and move constant
1312/// indices into blocks that use it.
1313static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1314 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00001315 // If this GEP is only used inside the block it is defined in, there is no
1316 // need to rewrite it.
1317 bool isUsedOutsideDefBB = false;
1318 BasicBlock *DefBB = GEPI->getParent();
1319 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1320 UI != E; ++UI) {
1321 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1322 isUsedOutsideDefBB = true;
1323 break;
1324 }
1325 }
1326 if (!isUsedOutsideDefBB) return;
1327
1328 // If this GEP has no non-zero constant indices, there is nothing we can do,
1329 // ignore it.
1330 bool hasConstantIndex = false;
1331 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1332 E = GEPI->op_end(); OI != E; ++OI) {
1333 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1334 if (CI->getRawValue()) {
1335 hasConstantIndex = true;
1336 break;
1337 }
1338 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00001339 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1340 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00001341
1342 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1343 // constant offset (which we now know is non-zero) and deal with it later.
1344 uint64_t ConstantOffset = 0;
1345 const Type *UIntPtrTy = TD.getIntPtrType();
1346 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1347 const Type *Ty = GEPI->getOperand(0)->getType();
1348
1349 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1350 E = GEPI->op_end(); OI != E; ++OI) {
1351 Value *Idx = *OI;
1352 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1353 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1354 if (Field)
1355 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1356 Ty = StTy->getElementType(Field);
1357 } else {
1358 Ty = cast<SequentialType>(Ty)->getElementType();
1359
1360 // Handle constant subscripts.
1361 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1362 if (CI->getRawValue() == 0) continue;
1363
1364 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1365 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1366 else
1367 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1368 continue;
1369 }
1370
1371 // Ptr = Ptr + Idx * ElementSize;
1372
1373 // Cast Idx to UIntPtrTy if needed.
1374 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1375
1376 uint64_t ElementSize = TD.getTypeSize(Ty);
1377 // Mask off bits that should not be set.
1378 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1379 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1380
1381 // Multiply by the element size and add to the base.
1382 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1383 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1384 }
1385 }
1386
1387 // Make sure that the offset fits in uintptr_t.
1388 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1389 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1390
1391 // Okay, we have now emitted all of the variable index parts to the BB that
1392 // the GEP is defined in. Loop over all of the using instructions, inserting
1393 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001394 // instruction to use the newly computed value, making GEPI dead. When the
1395 // user is a load or store instruction address, we emit the add into the user
1396 // block, otherwise we use a canonical version right next to the gep (these
1397 // won't be foldable as addresses, so we might as well share the computation).
1398
Chris Lattner35397782005-12-05 07:10:48 +00001399 std::map<BasicBlock*,Value*> InsertedExprs;
1400 while (!GEPI->use_empty()) {
1401 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001402
1403 // If this use is not foldable into the addressing mode, use a version
1404 // emitted in the GEP block.
1405 Value *NewVal;
1406 if (!isa<LoadInst>(User) &&
1407 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1408 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1409 Ptr, PtrOffset);
1410 } else {
1411 // Otherwise, insert the code in the User's block so it can be folded into
1412 // any users in that block.
1413 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00001414 User->getParent(), GEPI,
1415 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00001416 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00001417 User->replaceUsesOfWith(GEPI, NewVal);
1418 }
Chris Lattner35397782005-12-05 07:10:48 +00001419
1420 // Finally, the GEP is dead, remove it.
1421 GEPI->eraseFromParent();
1422}
1423
Chris Lattner7a60d912005-01-07 07:47:53 +00001424bool SelectionDAGISel::runOnFunction(Function &Fn) {
1425 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1426 RegMap = MF.getSSARegMap();
1427 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1428
Chris Lattner35397782005-12-05 07:10:48 +00001429 // First, split all critical edges for PHI nodes with incoming values that are
1430 // constants, this way the load of the constant into a vreg will not be placed
1431 // into MBBs that are used some other way.
1432 //
1433 // In this pass we also look for GEP instructions that are used across basic
1434 // blocks and rewrites them to improve basic-block-at-a-time selection.
1435 //
Chris Lattner1a908c82005-08-18 17:35:14 +00001436 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1437 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00001438 BasicBlock::iterator BBI;
1439 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00001440 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1441 if (isa<Constant>(PN->getIncomingValue(i)))
1442 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00001443
1444 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1445 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1446 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00001447 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001448
Chris Lattner7a60d912005-01-07 07:47:53 +00001449 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1450
1451 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1452 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00001453
Chris Lattner7a60d912005-01-07 07:47:53 +00001454 return true;
1455}
1456
1457
Chris Lattner718b5c22005-01-13 17:59:43 +00001458SDOperand SelectionDAGISel::
1459CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00001460 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00001461 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00001462 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00001463 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00001464
1465 // If this type is not legal, we must make sure to not create an invalid
1466 // register use.
1467 MVT::ValueType SrcVT = Op.getValueType();
1468 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1469 SelectionDAG &DAG = SDL.DAG;
1470 if (SrcVT == DestVT) {
1471 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1472 } else if (SrcVT < DestVT) {
1473 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00001474 if (MVT::isFloatingPoint(SrcVT))
1475 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1476 else
Chris Lattnera66403d2005-09-02 00:19:37 +00001477 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00001478 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1479 } else {
1480 // The src value is expanded into multiple registers.
1481 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1482 Op, DAG.getConstant(0, MVT::i32));
1483 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1484 Op, DAG.getConstant(1, MVT::i32));
1485 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1486 return DAG.getCopyToReg(Op, Reg+1, Hi);
1487 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001488}
1489
Chris Lattner16f64df2005-01-17 17:15:02 +00001490void SelectionDAGISel::
1491LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1492 std::vector<SDOperand> &UnorderedChains) {
1493 // If this is the entry block, emit arguments.
1494 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001495 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00001496 SDOperand OldRoot = SDL.DAG.getRoot();
1497 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00001498
Chris Lattner6871b232005-10-30 19:42:35 +00001499 unsigned a = 0;
1500 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1501 AI != E; ++AI, ++a)
1502 if (!AI->use_empty()) {
1503 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00001504
Chris Lattner6871b232005-10-30 19:42:35 +00001505 // If this argument is live outside of the entry block, insert a copy from
1506 // whereever we got it to the vreg that other BB's will reference it as.
1507 if (FuncInfo.ValueMap.count(AI)) {
1508 SDOperand Copy =
1509 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1510 UnorderedChains.push_back(Copy);
1511 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00001512 }
Chris Lattner6871b232005-10-30 19:42:35 +00001513
1514 // Next, if the function has live ins that need to be copied into vregs,
1515 // emit the copies now, into the top of the block.
1516 MachineFunction &MF = SDL.DAG.getMachineFunction();
1517 if (MF.livein_begin() != MF.livein_end()) {
1518 SSARegMap *RegMap = MF.getSSARegMap();
1519 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1520 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1521 E = MF.livein_end(); LI != E; ++LI)
1522 if (LI->second)
1523 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1524 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00001525 }
Chris Lattner6871b232005-10-30 19:42:35 +00001526
1527 // Finally, if the target has anything special to do, allow it to do so.
1528 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00001529}
1530
1531
Chris Lattner7a60d912005-01-07 07:47:53 +00001532void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1533 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1534 FunctionLoweringInfo &FuncInfo) {
1535 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00001536
1537 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00001538
Chris Lattner6871b232005-10-30 19:42:35 +00001539 // Lower any arguments needed in this block if this is the entry block.
1540 if (LLVMBB == &LLVMBB->getParent()->front())
1541 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00001542
1543 BB = FuncInfo.MBBMap[LLVMBB];
1544 SDL.setCurrentBasicBlock(BB);
1545
1546 // Lower all of the non-terminator instructions.
1547 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1548 I != E; ++I)
1549 SDL.visit(*I);
1550
1551 // Ensure that all instructions which are used outside of their defining
1552 // blocks are available as virtual registers.
1553 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00001554 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00001555 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00001556 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00001557 UnorderedChains.push_back(
1558 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00001559 }
1560
1561 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1562 // ensure constants are generated when needed. Remember the virtual registers
1563 // that need to be added to the Machine PHI nodes as input. We cannot just
1564 // directly add them, because expansion might result in multiple MBB's for one
1565 // BB. As such, the start of the BB might correspond to a different MBB than
1566 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00001567 //
Chris Lattner7a60d912005-01-07 07:47:53 +00001568
1569 // Emit constants only once even if used by multiple PHI nodes.
1570 std::map<Constant*, unsigned> ConstantsOut;
1571
1572 // Check successor nodes PHI nodes that expect a constant to be available from
1573 // this block.
1574 TerminatorInst *TI = LLVMBB->getTerminator();
1575 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1576 BasicBlock *SuccBB = TI->getSuccessor(succ);
1577 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1578 PHINode *PN;
1579
1580 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1581 // nodes and Machine PHI nodes, but the incoming operands have not been
1582 // emitted yet.
1583 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00001584 (PN = dyn_cast<PHINode>(I)); ++I)
1585 if (!PN->use_empty()) {
1586 unsigned Reg;
1587 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1588 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1589 unsigned &RegOut = ConstantsOut[C];
1590 if (RegOut == 0) {
1591 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00001592 UnorderedChains.push_back(
1593 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00001594 }
1595 Reg = RegOut;
1596 } else {
1597 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00001598 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00001599 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00001600 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1601 "Didn't codegen value into a register!??");
1602 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00001603 UnorderedChains.push_back(
1604 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00001605 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001606 }
Misha Brukman835702a2005-04-21 22:36:52 +00001607
Chris Lattner8ea875f2005-01-07 21:34:19 +00001608 // Remember that this register needs to added to the machine PHI node as
1609 // the input for this MBB.
1610 unsigned NumElements =
1611 TLI.getNumElements(TLI.getValueType(PN->getType()));
1612 for (unsigned i = 0, e = NumElements; i != e; ++i)
1613 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00001614 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001615 }
1616 ConstantsOut.clear();
1617
Chris Lattner718b5c22005-01-13 17:59:43 +00001618 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00001619 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00001620 SDOperand Root = SDL.getRoot();
1621 if (Root.getOpcode() != ISD::EntryToken) {
1622 unsigned i = 0, e = UnorderedChains.size();
1623 for (; i != e; ++i) {
1624 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1625 if (UnorderedChains[i].Val->getOperand(0) == Root)
1626 break; // Don't add the root if we already indirectly depend on it.
1627 }
1628
1629 if (i == e)
1630 UnorderedChains.push_back(Root);
1631 }
Chris Lattner718b5c22005-01-13 17:59:43 +00001632 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1633 }
1634
Chris Lattner7a60d912005-01-07 07:47:53 +00001635 // Lower the terminator after the copies are emitted.
1636 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00001637
1638 // Make sure the root of the DAG is up-to-date.
1639 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00001640}
1641
1642void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1643 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00001644 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00001645 CurDAG = &DAG;
1646 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1647
1648 // First step, lower LLVM code to some DAG. This DAG may use operations and
1649 // types that are not supported by the target.
1650 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1651
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001652 // Run the DAG combiner in pre-legalize mode.
1653 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00001654
Chris Lattner7a60d912005-01-07 07:47:53 +00001655 DEBUG(std::cerr << "Lowered selection DAG:\n");
1656 DEBUG(DAG.dump());
1657
1658 // Second step, hack on the DAG until it only uses operations and types that
1659 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00001660 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00001661
1662 DEBUG(std::cerr << "Legalized selection DAG:\n");
1663 DEBUG(DAG.dump());
1664
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00001665 // Run the DAG combiner in post-legalize mode.
1666 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00001667
Chris Lattner6bd8fd02005-10-05 06:09:10 +00001668 if (ViewDAGs) DAG.viewGraph();
1669
Chris Lattner5ca31d92005-03-30 01:10:47 +00001670 // Third, instruction select all of the operations to machine code, adding the
1671 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00001672 InstructionSelectBasicBlock(DAG);
1673
Chris Lattner7a60d912005-01-07 07:47:53 +00001674 DEBUG(std::cerr << "Selected machine code:\n");
1675 DEBUG(BB->dump());
1676
Chris Lattner5ca31d92005-03-30 01:10:47 +00001677 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00001678 // PHI nodes in successors.
1679 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1680 MachineInstr *PHI = PHINodesToUpdate[i].first;
1681 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1682 "This is not a machine PHI node that we are updating!");
1683 PHI->addRegOperand(PHINodesToUpdate[i].second);
1684 PHI->addMachineBasicBlockOperand(BB);
1685 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00001686
1687 // Finally, add the CFG edges from the last selected MBB to the successor
1688 // MBBs.
1689 TerminatorInst *TI = LLVMBB->getTerminator();
1690 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1691 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1692 BB->addSuccessor(Succ0MBB);
1693 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001694}