blob: 7e20f091b22134131c5a3afa179bb9ae7e7e0293 [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"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000022#include "llvm/Instructions.h"
23#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000024#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000025#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
29#include "llvm/CodeGen/SelectionDAG.h"
30#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000031#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/Target/TargetData.h"
33#include "llvm/Target/TargetFrameInfo.h"
34#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000038#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000039#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000040#include "llvm/Support/Debug.h"
41#include <map>
42#include <iostream>
43using namespace llvm;
44
Chris Lattnerda8abb02005-09-01 18:44:10 +000045#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000046static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000047ViewISelDAGs("view-isel-dags", cl::Hidden,
48 cl::desc("Pop up a window to show isel dags as they are selected"));
49static cl::opt<bool>
50ViewSchedDAGs("view-sched-dags", cl::Hidden,
51 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000052#else
Evan Chenga9c20912006-01-21 02:32:06 +000053static const bool ViewISelDAGs = 0;
54static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000055#endif
56
Chris Lattner1c08c712005-01-07 07:47:53 +000057namespace llvm {
58 //===--------------------------------------------------------------------===//
59 /// FunctionLoweringInfo - This contains information that is global to a
60 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +000061 class FunctionLoweringInfo {
62 public:
Chris Lattner1c08c712005-01-07 07:47:53 +000063 TargetLowering &TLI;
64 Function &Fn;
65 MachineFunction &MF;
66 SSARegMap *RegMap;
67
68 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
69
70 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
71 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
72
73 /// ValueMap - Since we emit code for the function a basic block at a time,
74 /// we must remember which virtual registers hold the values for
75 /// cross-basic-block values.
76 std::map<const Value*, unsigned> ValueMap;
77
78 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
79 /// the entry block. This allows the allocas to be efficiently referenced
80 /// anywhere in the function.
81 std::map<const AllocaInst*, int> StaticAllocaMap;
82
83 unsigned MakeReg(MVT::ValueType VT) {
84 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
85 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000086
Chris Lattner1c08c712005-01-07 07:47:53 +000087 unsigned CreateRegForValue(const Value *V) {
88 MVT::ValueType VT = TLI.getValueType(V->getType());
89 // The common case is that we will only create one register for this
90 // value. If we have that case, create and return the virtual register.
91 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +000092 if (NV == 1) {
93 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +000094 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +000095 }
Misha Brukmanedf128a2005-04-21 22:36:52 +000096
Chris Lattner1c08c712005-01-07 07:47:53 +000097 // If this value is represented with multiple target registers, make sure
98 // to create enough consequtive registers of the right (smaller) type.
99 unsigned NT = VT-1; // Find the type to use.
100 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
101 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000102
Chris Lattner1c08c712005-01-07 07:47:53 +0000103 unsigned R = MakeReg((MVT::ValueType)NT);
104 for (unsigned i = 1; i != NV; ++i)
105 MakeReg((MVT::ValueType)NT);
106 return R;
107 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000108
Chris Lattner1c08c712005-01-07 07:47:53 +0000109 unsigned InitializeRegForValue(const Value *V) {
110 unsigned &R = ValueMap[V];
111 assert(R == 0 && "Already initialized this value register!");
112 return R = CreateRegForValue(V);
113 }
114 };
115}
116
117/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
118/// PHI nodes or outside of the basic block that defines it.
119static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
120 if (isa<PHINode>(I)) return true;
121 BasicBlock *BB = I->getParent();
122 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
123 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
124 return true;
125 return false;
126}
127
Chris Lattnerbf209482005-10-30 19:42:35 +0000128/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
129/// entry block, return true.
130static bool isOnlyUsedInEntryBlock(Argument *A) {
131 BasicBlock *Entry = A->getParent()->begin();
132 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
133 if (cast<Instruction>(*UI)->getParent() != Entry)
134 return false; // Use not in entry block.
135 return true;
136}
137
Chris Lattner1c08c712005-01-07 07:47:53 +0000138FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000139 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000140 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
141
Chris Lattnerbf209482005-10-30 19:42:35 +0000142 // Create a vreg for each argument register that is not dead and is used
143 // outside of the entry block for the function.
144 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
145 AI != E; ++AI)
146 if (!isOnlyUsedInEntryBlock(AI))
147 InitializeRegForValue(AI);
148
Chris Lattner1c08c712005-01-07 07:47:53 +0000149 // Initialize the mapping of values to registers. This is only set up for
150 // instruction values that are used outside of the block that defines
151 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000152 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000153 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
154 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
155 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
156 const Type *Ty = AI->getAllocatedType();
157 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000158 unsigned Align =
159 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
160 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000161
162 // If the alignment of the value is smaller than the size of the value,
163 // and if the size of the value is particularly small (<= 8 bytes),
164 // round up to the size of the value for potentially better performance.
165 //
166 // FIXME: This could be made better with a preferred alignment hook in
167 // TargetData. It serves primarily to 8-byte align doubles for X86.
168 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000169 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000170 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000171 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000172 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000173 }
174
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000175 for (; BB != EB; ++BB)
176 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000177 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
178 if (!isa<AllocaInst>(I) ||
179 !StaticAllocaMap.count(cast<AllocaInst>(I)))
180 InitializeRegForValue(I);
181
182 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
183 // also creates the initial PHI MachineInstrs, though none of the input
184 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000185 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000186 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
187 MBBMap[BB] = MBB;
188 MF.getBasicBlockList().push_back(MBB);
189
190 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
191 // appropriate.
192 PHINode *PN;
193 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000194 (PN = dyn_cast<PHINode>(I)); ++I)
195 if (!PN->use_empty()) {
196 unsigned NumElements =
197 TLI.getNumElements(TLI.getValueType(PN->getType()));
198 unsigned PHIReg = ValueMap[PN];
199 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
200 for (unsigned i = 0; i != NumElements; ++i)
201 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
202 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000203 }
204}
205
206
207
208//===----------------------------------------------------------------------===//
209/// SelectionDAGLowering - This is the common target-independent lowering
210/// implementation that is parameterized by a TargetLowering object.
211/// Also, targets can overload any lowering method.
212///
213namespace llvm {
214class SelectionDAGLowering {
215 MachineBasicBlock *CurMBB;
216
217 std::map<const Value*, SDOperand> NodeMap;
218
Chris Lattnerd3948112005-01-17 22:19:26 +0000219 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
220 /// them up and then emit token factor nodes when possible. This allows us to
221 /// get simple disambiguation between loads without worrying about alias
222 /// analysis.
223 std::vector<SDOperand> PendingLoads;
224
Chris Lattner1c08c712005-01-07 07:47:53 +0000225public:
226 // TLI - This is information that describes the available target features we
227 // need for lowering. This indicates when operations are unavailable,
228 // implemented with a libcall, etc.
229 TargetLowering &TLI;
230 SelectionDAG &DAG;
231 const TargetData &TD;
232
233 /// FuncInfo - Information about the function as a whole.
234 ///
235 FunctionLoweringInfo &FuncInfo;
236
237 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000238 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000239 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
240 FuncInfo(funcinfo) {
241 }
242
Chris Lattnera651cf62005-01-17 19:43:36 +0000243 /// getRoot - Return the current virtual root of the Selection DAG.
244 ///
245 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000246 if (PendingLoads.empty())
247 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000248
Chris Lattnerd3948112005-01-17 22:19:26 +0000249 if (PendingLoads.size() == 1) {
250 SDOperand Root = PendingLoads[0];
251 DAG.setRoot(Root);
252 PendingLoads.clear();
253 return Root;
254 }
255
256 // Otherwise, we have to make a token factor node.
257 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
258 PendingLoads.clear();
259 DAG.setRoot(Root);
260 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000261 }
262
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 void visit(Instruction &I) { visit(I.getOpcode(), I); }
264
265 void visit(unsigned Opcode, User &I) {
266 switch (Opcode) {
267 default: assert(0 && "Unknown instruction type encountered!");
268 abort();
269 // Build the switch statement using the Instruction.def file.
270#define HANDLE_INST(NUM, OPCODE, CLASS) \
271 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
272#include "llvm/Instruction.def"
273 }
274 }
275
276 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
277
278
279 SDOperand getIntPtrConstant(uint64_t Val) {
280 return DAG.getConstant(Val, TLI.getPointerTy());
281 }
282
283 SDOperand getValue(const Value *V) {
284 SDOperand &N = NodeMap[V];
285 if (N.Val) return N;
286
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000287 const Type *VTy = V->getType();
288 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000289 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
290 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
291 visit(CE->getOpcode(), *CE);
292 assert(N.Val && "visit didn't populate the ValueMap!");
293 return N;
294 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
295 return N = DAG.getGlobalAddress(GV, VT);
296 } else if (isa<ConstantPointerNull>(C)) {
297 return N = DAG.getConstant(0, TLI.getPointerTy());
298 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000299 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000300 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
301 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000302 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
303 unsigned NumElements = PTy->getNumElements();
304 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
305 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
306
307 // Now that we know the number and type of the elements, push a
308 // Constant or ConstantFP node onto the ops list for each element of
309 // the packed constant.
310 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000311 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
312 if (MVT::isFloatingPoint(PVT)) {
313 for (unsigned i = 0; i != NumElements; ++i) {
314 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
315 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
316 }
317 } else {
318 for (unsigned i = 0; i != NumElements; ++i) {
319 const ConstantIntegral *El =
320 cast<ConstantIntegral>(CP->getOperand(i));
321 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
322 }
323 }
324 } else {
325 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
326 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000327 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000328 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000329 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000330 Op = DAG.getConstant(0, PVT);
331 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000332 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000333
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000334 // Handle the case where we have a 1-element vector, in which
335 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000336 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000337 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000338 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
339 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
340 } else {
341 // If the packed type isn't legal, then create a ConstantVec node with
342 // generic Vector type instead.
343 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
344 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000345 } else {
346 // Canonicalize all constant ints to be unsigned.
347 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
348 }
349
350 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
351 std::map<const AllocaInst*, int>::iterator SI =
352 FuncInfo.StaticAllocaMap.find(AI);
353 if (SI != FuncInfo.StaticAllocaMap.end())
354 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
355 }
356
357 std::map<const Value*, unsigned>::const_iterator VMI =
358 FuncInfo.ValueMap.find(V);
359 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000360
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000361 unsigned InReg = VMI->second;
362
363 // If this type is not legal, make it so now.
364 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
365
366 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
367 if (DestVT < VT) {
368 // Source must be expanded. This input value is actually coming from the
369 // register pair VMI->second and VMI->second+1.
370 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
371 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
372 } else {
373 if (DestVT > VT) { // Promotion case
374 if (MVT::isFloatingPoint(VT))
375 N = DAG.getNode(ISD::FP_ROUND, VT, N);
376 else
377 N = DAG.getNode(ISD::TRUNCATE, VT, N);
378 }
379 }
380
381 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000382 }
383
384 const SDOperand &setValue(const Value *V, SDOperand NewN) {
385 SDOperand &N = NodeMap[V];
386 assert(N.Val == 0 && "Already set a value for this node!");
387 return N = NewN;
388 }
389
390 // Terminator instructions.
391 void visitRet(ReturnInst &I);
392 void visitBr(BranchInst &I);
393 void visitUnreachable(UnreachableInst &I) { /* noop */ }
394
395 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000396 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000397 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000398 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
399 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
400 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
401
402 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000403 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000404 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000405 void visitAdd(User &I) {
406 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000407 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000408 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000409 void visitMul(User &I) {
410 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000411 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000412 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000413 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000414 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000415 }
416 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000417 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000418 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000419 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000420 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
421 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
422 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begemane21ea612005-11-18 07:42:56 +0000423 void visitShl(User &I) { visitShift(I, ISD::SHL); }
424 void visitShr(User &I) {
425 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 }
427
428 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
429 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
430 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
431 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
432 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
433 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
434 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
435
436 void visitGetElementPtr(User &I);
437 void visitCast(User &I);
438 void visitSelect(User &I);
439 //
440
441 void visitMalloc(MallocInst &I);
442 void visitFree(FreeInst &I);
443 void visitAlloca(AllocaInst &I);
444 void visitLoad(LoadInst &I);
445 void visitStore(StoreInst &I);
446 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
447 void visitCall(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000448 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000449
Chris Lattner1c08c712005-01-07 07:47:53 +0000450 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 void visitVAArg(VAArgInst &I);
452 void visitVAEnd(CallInst &I);
453 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000454 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000455
Chris Lattner7041ee32005-01-11 05:56:49 +0000456 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000457
458 void visitUserOp1(Instruction &I) {
459 assert(0 && "UserOp1 should not exist at instruction selection time!");
460 abort();
461 }
462 void visitUserOp2(Instruction &I) {
463 assert(0 && "UserOp2 should not exist at instruction selection time!");
464 abort();
465 }
466};
467} // end namespace llvm
468
469void SelectionDAGLowering::visitRet(ReturnInst &I) {
470 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000471 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000472 return;
473 }
474
475 SDOperand Op1 = getValue(I.getOperand(0));
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000476 MVT::ValueType TmpVT;
477
Chris Lattner1c08c712005-01-07 07:47:53 +0000478 switch (Op1.getValueType()) {
479 default: assert(0 && "Unknown value type!");
480 case MVT::i1:
481 case MVT::i8:
482 case MVT::i16:
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000483 case MVT::i32:
484 // If this is a machine where 32-bits is legal or expanded, promote to
485 // 32-bits, otherwise, promote to 64-bits.
486 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
487 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 else
Chris Lattnerf51d3bd2005-03-29 19:09:56 +0000489 TmpVT = MVT::i32;
490
491 // Extend integer types to result type.
492 if (I.getOperand(0)->getType()->isSigned())
493 Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
494 else
495 Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
Chris Lattner1c08c712005-01-07 07:47:53 +0000496 break;
497 case MVT::f32:
Chris Lattner4eebb602006-01-20 18:38:32 +0000498 // If this is a machine where f32 is promoted to f64, do so now.
499 if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
500 Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
501 break;
Chris Lattner1c08c712005-01-07 07:47:53 +0000502 case MVT::i64:
503 case MVT::f64:
504 break; // No extension needed!
505 }
Nate Begeman4a959452005-10-18 23:23:37 +0000506 // Allow targets to lower this further to meet ABI requirements
507 DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +0000508}
509
510void SelectionDAGLowering::visitBr(BranchInst &I) {
511 // Update machine-CFG edges.
512 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000513
514 // Figure out which block is immediately after the current one.
515 MachineBasicBlock *NextBlock = 0;
516 MachineFunction::iterator BBI = CurMBB;
517 if (++BBI != CurMBB->getParent()->end())
518 NextBlock = BBI;
519
520 if (I.isUnconditional()) {
521 // If this is not a fall-through branch, emit the branch.
522 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000523 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000524 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000525 } else {
526 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000527
528 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000529 if (Succ1MBB == NextBlock) {
530 // If the condition is false, fall through. This means we should branch
531 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000532 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000533 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000534 } else if (Succ0MBB == NextBlock) {
535 // If the condition is true, fall through. This means we should branch if
536 // the condition is false to Succ #1. Invert the condition first.
537 SDOperand True = DAG.getConstant(1, Cond.getValueType());
538 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000539 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000540 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000541 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000542 std::vector<SDOperand> Ops;
543 Ops.push_back(getRoot());
544 Ops.push_back(Cond);
545 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
546 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
547 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000548 }
549 }
550}
551
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000552void SelectionDAGLowering::visitSub(User &I) {
553 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000554 if (I.getType()->isFloatingPoint()) {
555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
556 if (CFP->isExactlyValue(-0.0)) {
557 SDOperand Op2 = getValue(I.getOperand(1));
558 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
559 return;
560 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000561 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000562 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000563}
564
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000565void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
566 unsigned VecOp) {
567 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000568 SDOperand Op1 = getValue(I.getOperand(0));
569 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000570
Chris Lattnerb67eb912005-11-19 18:40:42 +0000571 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000572 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
573 } else if (Ty->isFloatingPoint()) {
574 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
575 } else {
576 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000577 unsigned NumElements = PTy->getNumElements();
578 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000579 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000580
581 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000582 // the Legalize pass does not have to deal with them. Similarly, if the
583 // abstract vector is going to turn into one that the target natively
584 // supports, generate that type now so that Legalize doesn't have to deal
585 // with that either. These steps ensure that Legalize only has to handle
586 // vector types in its Expand case.
587 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000588 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000589 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000590 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
591 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000592 } else {
593 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
594 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemanab48be32005-11-22 18:16:00 +0000595 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000596 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000597 }
Nate Begemane21ea612005-11-18 07:42:56 +0000598}
Chris Lattner2c49f272005-01-19 22:31:21 +0000599
Nate Begemane21ea612005-11-18 07:42:56 +0000600void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
601 SDOperand Op1 = getValue(I.getOperand(0));
602 SDOperand Op2 = getValue(I.getOperand(1));
603
604 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
605
Chris Lattner1c08c712005-01-07 07:47:53 +0000606 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
607}
608
609void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
610 ISD::CondCode UnsignedOpcode) {
611 SDOperand Op1 = getValue(I.getOperand(0));
612 SDOperand Op2 = getValue(I.getOperand(1));
613 ISD::CondCode Opcode = SignedOpcode;
614 if (I.getOperand(0)->getType()->isUnsigned())
615 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000616 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000617}
618
619void SelectionDAGLowering::visitSelect(User &I) {
620 SDOperand Cond = getValue(I.getOperand(0));
621 SDOperand TrueVal = getValue(I.getOperand(1));
622 SDOperand FalseVal = getValue(I.getOperand(2));
623 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
624 TrueVal, FalseVal));
625}
626
627void SelectionDAGLowering::visitCast(User &I) {
628 SDOperand N = getValue(I.getOperand(0));
629 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
630 MVT::ValueType DestTy = TLI.getValueType(I.getType());
631
632 if (N.getValueType() == DestTy) {
633 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000634 } else if (DestTy == MVT::i1) {
635 // Cast to bool is a comparison against zero, not truncation to zero.
636 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
637 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000638 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000639 } else if (isInteger(SrcTy)) {
640 if (isInteger(DestTy)) { // Int -> Int cast
641 if (DestTy < SrcTy) // Truncating cast?
642 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
643 else if (I.getOperand(0)->getType()->isSigned())
644 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
645 else
646 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
647 } else { // Int -> FP cast
648 if (I.getOperand(0)->getType()->isSigned())
649 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
650 else
651 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
652 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000654 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
655 if (isFloatingPoint(DestTy)) { // FP -> FP cast
656 if (DestTy < SrcTy) // Rounding cast?
657 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
658 else
659 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
660 } else { // FP -> Int cast.
661 if (I.getType()->isSigned())
662 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
663 else
664 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
665 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000666 }
667}
668
669void SelectionDAGLowering::visitGetElementPtr(User &I) {
670 SDOperand N = getValue(I.getOperand(0));
671 const Type *Ty = I.getOperand(0)->getType();
672 const Type *UIntPtrTy = TD.getIntPtrType();
673
674 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
675 OI != E; ++OI) {
676 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000677 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000678 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
679 if (Field) {
680 // N = N + Offset
681 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
682 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000683 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000684 }
685 Ty = StTy->getElementType(Field);
686 } else {
687 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000688
Chris Lattner7c0104b2005-11-09 04:45:33 +0000689 // If this is a constant subscript, handle it quickly.
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
691 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000692
Chris Lattner7c0104b2005-11-09 04:45:33 +0000693 uint64_t Offs;
694 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
695 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
696 else
697 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
698 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
699 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000701
702 // N = N + Idx * ElementSize;
703 uint64_t ElementSize = TD.getTypeSize(Ty);
704 SDOperand IdxN = getValue(Idx);
705
706 // If the index is smaller or larger than intptr_t, truncate or extend
707 // it.
708 if (IdxN.getValueType() < N.getValueType()) {
709 if (Idx->getType()->isSigned())
710 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
711 else
712 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
713 } else if (IdxN.getValueType() > N.getValueType())
714 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
715
716 // If this is a multiply by a power of two, turn it into a shl
717 // immediately. This is a very common case.
718 if (isPowerOf2_64(ElementSize)) {
719 unsigned Amt = Log2_64(ElementSize);
720 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000721 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000722 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
723 continue;
724 }
725
726 SDOperand Scale = getIntPtrConstant(ElementSize);
727 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
728 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000729 }
730 }
731 setValue(&I, N);
732}
733
734void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
735 // If this is a fixed sized alloca in the entry block of the function,
736 // allocate it statically on the stack.
737 if (FuncInfo.StaticAllocaMap.count(&I))
738 return; // getValue will auto-populate this.
739
740 const Type *Ty = I.getAllocatedType();
741 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000742 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
743 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000744
745 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000746 MVT::ValueType IntPtr = TLI.getPointerTy();
747 if (IntPtr < AllocSize.getValueType())
748 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
749 else if (IntPtr > AllocSize.getValueType())
750 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000751
Chris Lattner68cd65e2005-01-22 23:04:37 +0000752 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000753 getIntPtrConstant(TySize));
754
755 // Handle alignment. If the requested alignment is less than or equal to the
756 // stack alignment, ignore it and round the size of the allocation up to the
757 // stack alignment size. If the size is greater than the stack alignment, we
758 // note this in the DYNAMIC_STACKALLOC node.
759 unsigned StackAlign =
760 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
761 if (Align <= StackAlign) {
762 Align = 0;
763 // Add SA-1 to the size.
764 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
765 getIntPtrConstant(StackAlign-1));
766 // Mask out the low bits for alignment purposes.
767 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
768 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
769 }
770
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000771 std::vector<MVT::ValueType> VTs;
772 VTs.push_back(AllocSize.getValueType());
773 VTs.push_back(MVT::Other);
774 std::vector<SDOperand> Ops;
775 Ops.push_back(getRoot());
776 Ops.push_back(AllocSize);
777 Ops.push_back(getIntPtrConstant(Align));
778 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000779 DAG.setRoot(setValue(&I, DSA).getValue(1));
780
781 // Inform the Frame Information that we have just allocated a variable-sized
782 // object.
783 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
784}
785
Chris Lattner36ce6912005-11-29 06:21:05 +0000786/// getStringValue - Turn an LLVM constant pointer that eventually points to a
787/// global into a string value. Return an empty string if we can't do it.
788///
789static std::string getStringValue(Value *V, unsigned Offset = 0) {
790 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
791 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
792 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
793 if (Init->isString()) {
794 std::string Result = Init->getAsString();
795 if (Offset < Result.size()) {
796 // If we are pointing INTO The string, erase the beginning...
797 Result.erase(Result.begin(), Result.begin()+Offset);
798
799 // Take off the null terminator, and any string fragments after it.
800 std::string::size_type NullPos = Result.find_first_of((char)0);
801 if (NullPos != std::string::npos)
802 Result.erase(Result.begin()+NullPos, Result.end());
803 return Result;
804 }
805 }
806 }
807 } else if (Constant *C = dyn_cast<Constant>(V)) {
808 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
809 return getStringValue(GV, Offset);
810 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811 if (CE->getOpcode() == Instruction::GetElementPtr) {
812 // Turn a gep into the specified offset.
813 if (CE->getNumOperands() == 3 &&
814 cast<Constant>(CE->getOperand(1))->isNullValue() &&
815 isa<ConstantInt>(CE->getOperand(2))) {
816 return getStringValue(CE->getOperand(0),
817 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
818 }
819 }
820 }
821 }
822 return "";
823}
Chris Lattner1c08c712005-01-07 07:47:53 +0000824
825void SelectionDAGLowering::visitLoad(LoadInst &I) {
826 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000827
Chris Lattnerd3948112005-01-17 22:19:26 +0000828 SDOperand Root;
829 if (I.isVolatile())
830 Root = getRoot();
831 else {
832 // Do not serialize non-volatile loads against each other.
833 Root = DAG.getRoot();
834 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000835
836 const Type *Ty = I.getType();
837 SDOperand L;
838
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000839 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000840 unsigned NumElements = PTy->getNumElements();
841 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000842 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000843
844 // Immediately scalarize packed types containing only one element, so that
845 // the Legalize pass does not have to deal with them.
846 if (NumElements == 1) {
847 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000848 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
849 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000850 } else {
851 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
852 DAG.getSrcValue(I.getOperand(0)));
853 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000854 } else {
855 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
856 DAG.getSrcValue(I.getOperand(0)));
857 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000858 setValue(&I, L);
859
860 if (I.isVolatile())
861 DAG.setRoot(L.getValue(1));
862 else
863 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000864}
865
866
867void SelectionDAGLowering::visitStore(StoreInst &I) {
868 Value *SrcV = I.getOperand(0);
869 SDOperand Src = getValue(SrcV);
870 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000871 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000872 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000873}
874
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000875/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
876/// we want to emit this as a call to a named external function, return the name
877/// otherwise lower it and return null.
878const char *
879SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
880 switch (Intrinsic) {
881 case Intrinsic::vastart: visitVAStart(I); return 0;
882 case Intrinsic::vaend: visitVAEnd(I); return 0;
883 case Intrinsic::vacopy: visitVACopy(I); return 0;
884 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
885 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
886 case Intrinsic::setjmp:
887 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
888 break;
889 case Intrinsic::longjmp:
890 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
891 break;
892 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
893 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
894 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
895
896 case Intrinsic::readport:
897 case Intrinsic::readio: {
898 std::vector<MVT::ValueType> VTs;
899 VTs.push_back(TLI.getValueType(I.getType()));
900 VTs.push_back(MVT::Other);
901 std::vector<SDOperand> Ops;
902 Ops.push_back(getRoot());
903 Ops.push_back(getValue(I.getOperand(1)));
904 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
905 ISD::READPORT : ISD::READIO, VTs, Ops);
906
907 setValue(&I, Tmp);
908 DAG.setRoot(Tmp.getValue(1));
909 return 0;
910 }
911 case Intrinsic::writeport:
912 case Intrinsic::writeio:
913 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
914 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
915 getRoot(), getValue(I.getOperand(1)),
916 getValue(I.getOperand(2))));
917 return 0;
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000918
Chris Lattner86cb6432005-12-13 17:40:33 +0000919 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000920 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
921 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000922
923 std::string fname = "<unknown>";
924 std::vector<SDOperand> Ops;
925
Chris Lattner36ce6912005-11-29 06:21:05 +0000926 // Input Chain
927 Ops.push_back(getRoot());
928
929 // line number
930 Ops.push_back(getValue(I.getOperand(2)));
931
932 // column
933 Ops.push_back(getValue(I.getOperand(3)));
934
Chris Lattner86cb6432005-12-13 17:40:33 +0000935 // filename/working dir
936 // Pull the filename out of the the compilation unit.
937 const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
938 if (cunit && cunit->hasInitializer()) {
939 if (ConstantStruct *CS =
940 dyn_cast<ConstantStruct>(cunit->getInitializer())) {
941 if (CS->getNumOperands() > 0) {
Chris Lattner86cb6432005-12-13 17:40:33 +0000942 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
Jim Laskeyf5395ce2005-12-16 22:45:29 +0000943 Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
Chris Lattner86cb6432005-12-13 17:40:33 +0000944 }
945 }
946 }
947
948 if (Ops.size() == 5) // Found filename/workingdir.
949 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattnerd67b3a82005-12-03 18:50:48 +0000950 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000951 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +0000952 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000953 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000954 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
955 return "llvm_dbg_region_start";
956 if (I.getType() != Type::VoidTy)
957 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
958 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000959 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000960 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
961 return "llvm_dbg_region_end";
962 if (I.getType() != Type::VoidTy)
963 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
964 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000965 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000966 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
967 return "llvm_dbg_subprogram";
968 if (I.getType() != Type::VoidTy)
969 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
970 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000971 case Intrinsic::dbg_declare:
972 if (I.getType() != Type::VoidTy)
973 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
974 return 0;
975
Reid Spencer0b118202006-01-16 21:12:35 +0000976 case Intrinsic::isunordered_f32:
977 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000978 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
979 getValue(I.getOperand(2)), ISD::SETUO));
980 return 0;
981
Reid Spencer0b118202006-01-16 21:12:35 +0000982 case Intrinsic::sqrt_f32:
983 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000984 setValue(&I, DAG.getNode(ISD::FSQRT,
985 getValue(I.getOperand(1)).getValueType(),
986 getValue(I.getOperand(1))));
987 return 0;
988 case Intrinsic::pcmarker: {
989 SDOperand Tmp = getValue(I.getOperand(1));
990 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
991 return 0;
992 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +0000993 case Intrinsic::readcyclecounter: {
994 std::vector<MVT::ValueType> VTs;
995 VTs.push_back(MVT::i64);
996 VTs.push_back(MVT::Other);
997 std::vector<SDOperand> Ops;
998 Ops.push_back(getRoot());
999 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1000 setValue(&I, Tmp);
1001 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001002 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001003 }
Nate Begemand88fc032006-01-14 03:14:10 +00001004 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001005 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001006 case Intrinsic::bswap_i64:
1007 setValue(&I, DAG.getNode(ISD::BSWAP,
1008 getValue(I.getOperand(1)).getValueType(),
1009 getValue(I.getOperand(1))));
1010 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001011 case Intrinsic::cttz_i8:
1012 case Intrinsic::cttz_i16:
1013 case Intrinsic::cttz_i32:
1014 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001015 setValue(&I, DAG.getNode(ISD::CTTZ,
1016 getValue(I.getOperand(1)).getValueType(),
1017 getValue(I.getOperand(1))));
1018 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001019 case Intrinsic::ctlz_i8:
1020 case Intrinsic::ctlz_i16:
1021 case Intrinsic::ctlz_i32:
1022 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001023 setValue(&I, DAG.getNode(ISD::CTLZ,
1024 getValue(I.getOperand(1)).getValueType(),
1025 getValue(I.getOperand(1))));
1026 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001027 case Intrinsic::ctpop_i8:
1028 case Intrinsic::ctpop_i16:
1029 case Intrinsic::ctpop_i32:
1030 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001031 setValue(&I, DAG.getNode(ISD::CTPOP,
1032 getValue(I.getOperand(1)).getValueType(),
1033 getValue(I.getOperand(1))));
1034 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001035 case Intrinsic::stacksave: {
1036 std::vector<MVT::ValueType> VTs;
1037 VTs.push_back(TLI.getPointerTy());
1038 VTs.push_back(MVT::Other);
1039 std::vector<SDOperand> Ops;
1040 Ops.push_back(getRoot());
1041 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1042 setValue(&I, Tmp);
1043 DAG.setRoot(Tmp.getValue(1));
1044 return 0;
1045 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001046 case Intrinsic::stackrestore: {
1047 SDOperand Tmp = getValue(I.getOperand(1));
1048 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001049 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001050 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001051 case Intrinsic::prefetch:
1052 // FIXME: Currently discarding prefetches.
1053 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001054 default:
1055 std::cerr << I;
1056 assert(0 && "This intrinsic is not implemented yet!");
1057 return 0;
1058 }
1059}
1060
1061
Chris Lattner1c08c712005-01-07 07:47:53 +00001062void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001063 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001064 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001065 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001066 if (unsigned IID = F->getIntrinsicID()) {
1067 RenameFn = visitIntrinsicCall(I, IID);
1068 if (!RenameFn)
1069 return;
1070 } else { // Not an LLVM intrinsic.
1071 const std::string &Name = F->getName();
1072 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001073 if (I.getNumOperands() == 2 && // Basic sanity checks.
1074 I.getOperand(1)->getType()->isFloatingPoint() &&
1075 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001076 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001077 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1078 return;
1079 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001080 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001081 if (I.getNumOperands() == 2 && // Basic sanity checks.
1082 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001083 I.getType() == I.getOperand(1)->getType() &&
1084 TLI.isOperationLegal(ISD::FSIN,
1085 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001086 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001087 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1088 return;
1089 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001090 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001091 if (I.getNumOperands() == 2 && // Basic sanity checks.
1092 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattnerd12b2d72006-01-18 21:50:14 +00001093 I.getType() == I.getOperand(1)->getType() &&
1094 TLI.isOperationLegal(ISD::FCOS,
1095 TLI.getValueType(I.getOperand(1)->getType()))) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001096 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001097 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1098 return;
1099 }
1100 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001101 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001102 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001103
Chris Lattner64e14b12005-01-08 22:48:57 +00001104 SDOperand Callee;
1105 if (!RenameFn)
1106 Callee = getValue(I.getOperand(0));
1107 else
1108 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001109 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001110 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001111 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1112 Value *Arg = I.getOperand(i);
1113 SDOperand ArgNode = getValue(Arg);
1114 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1115 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001116
Nate Begeman8e21e712005-03-26 01:29:23 +00001117 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1118 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001119
Chris Lattnercf5734d2005-01-08 19:26:18 +00001120 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001121 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001122 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001123 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001124 setValue(&I, Result.first);
1125 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001126}
1127
1128void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1129 SDOperand Src = getValue(I.getOperand(0));
1130
1131 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001132
1133 if (IntPtr < Src.getValueType())
1134 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1135 else if (IntPtr > Src.getValueType())
1136 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001137
1138 // Scale the source by the type size.
1139 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1140 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1141 Src, getIntPtrConstant(ElementSize));
1142
1143 std::vector<std::pair<SDOperand, const Type*> > Args;
1144 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001145
1146 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001147 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001148 DAG.getExternalSymbol("malloc", IntPtr),
1149 Args, DAG);
1150 setValue(&I, Result.first); // Pointers always fit in registers
1151 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001152}
1153
1154void SelectionDAGLowering::visitFree(FreeInst &I) {
1155 std::vector<std::pair<SDOperand, const Type*> > Args;
1156 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1157 TLI.getTargetData().getIntPtrType()));
1158 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001159 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001160 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001161 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1162 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001163}
1164
Chris Lattner025c39b2005-08-26 20:54:47 +00001165// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1166// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1167// instructions are special in various ways, which require special support to
1168// insert. The specified MachineInstr is created but not inserted into any
1169// basic blocks, and the scheduler passes ownership of it to this method.
1170MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1171 MachineBasicBlock *MBB) {
1172 std::cerr << "If a target marks an instruction with "
1173 "'usesCustomDAGSchedInserter', it must implement "
1174 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1175 abort();
1176 return 0;
1177}
1178
Nate Begeman4a959452005-10-18 23:23:37 +00001179SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1180 SelectionDAG &DAG) {
1181 return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1182}
1183
Chris Lattnere64e72b2005-07-05 19:57:53 +00001184SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1185 SDOperand VAListP, Value *VAListV,
1186 SelectionDAG &DAG) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001187 // We have no sane default behavior, just emit a useful error message and bail
1188 // out.
Chris Lattner39ae3622005-01-09 00:00:49 +00001189 std::cerr << "Variable arguments handling not implemented on this target!\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00001190 abort();
Chris Lattnere64e72b2005-07-05 19:57:53 +00001191 return SDOperand();
Chris Lattner1c08c712005-01-07 07:47:53 +00001192}
1193
Chris Lattnere64e72b2005-07-05 19:57:53 +00001194SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
Chris Lattner39ae3622005-01-09 00:00:49 +00001195 SelectionDAG &DAG) {
1196 // Default to a noop.
1197 return Chain;
1198}
1199
Chris Lattnere64e72b2005-07-05 19:57:53 +00001200SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1201 SDOperand SrcP, Value *SrcV,
1202 SDOperand DestP, Value *DestV,
1203 SelectionDAG &DAG) {
1204 // Default to copying the input list.
1205 SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1206 SrcP, DAG.getSrcValue(SrcV));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001207 SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001208 Val, DestP, DAG.getSrcValue(DestV));
1209 return Result;
Chris Lattner39ae3622005-01-09 00:00:49 +00001210}
1211
1212std::pair<SDOperand,SDOperand>
Chris Lattnere64e72b2005-07-05 19:57:53 +00001213TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1214 const Type *ArgTy, SelectionDAG &DAG) {
Chris Lattner39ae3622005-01-09 00:00:49 +00001215 // We have no sane default behavior, just emit a useful error message and bail
1216 // out.
1217 std::cerr << "Variable arguments handling not implemented on this target!\n";
1218 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001219 return std::make_pair(SDOperand(), SDOperand());
Chris Lattner39ae3622005-01-09 00:00:49 +00001220}
1221
1222
1223void SelectionDAGLowering::visitVAStart(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001224 DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1225 I.getOperand(1), DAG));
Chris Lattner39ae3622005-01-09 00:00:49 +00001226}
1227
1228void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1229 std::pair<SDOperand,SDOperand> Result =
Chris Lattnere64e72b2005-07-05 19:57:53 +00001230 TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
Andrew Lenharth558bc882005-06-18 18:34:52 +00001231 I.getType(), DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001232 setValue(&I, Result.first);
1233 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001234}
1235
1236void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Jeff Cohen00b168892005-07-27 06:12:32 +00001237 DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
Chris Lattnere64e72b2005-07-05 19:57:53 +00001238 I.getOperand(1), DAG));
Chris Lattner1c08c712005-01-07 07:47:53 +00001239}
1240
1241void SelectionDAGLowering::visitVACopy(CallInst &I) {
Chris Lattnere64e72b2005-07-05 19:57:53 +00001242 SDOperand Result =
1243 TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1244 getValue(I.getOperand(1)), I.getOperand(1), DAG);
1245 DAG.setRoot(Result);
Chris Lattner1c08c712005-01-07 07:47:53 +00001246}
1247
Chris Lattner39ae3622005-01-09 00:00:49 +00001248
1249// It is always conservatively correct for llvm.returnaddress and
1250// llvm.frameaddress to return 0.
1251std::pair<SDOperand, SDOperand>
1252TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1253 unsigned Depth, SelectionDAG &DAG) {
1254 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001255}
1256
Chris Lattner50381b62005-05-14 05:50:48 +00001257SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001258 assert(0 && "LowerOperation not implemented for this target!");
1259 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001260 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001261}
1262
Chris Lattner39ae3622005-01-09 00:00:49 +00001263void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1264 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1265 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001266 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001267 setValue(&I, Result.first);
1268 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001269}
1270
Chris Lattner7041ee32005-01-11 05:56:49 +00001271void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Reid Spencer6ff72402005-11-30 05:21:10 +00001272#if 0
1273 // If the size of the cpy/move/set is constant (known)
1274 if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1275 uint64_t size = op3->getValue();
1276 switch (Op) {
1277 case ISD::MEMSET:
1278 if (size <= TLI.getMaxStoresPerMemSet()) {
1279 if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1280 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1281 uint64_t align = op4.getValue();
1282 while (size > align) {
1283 size -=align;
1284 }
1285 Value *SrcV = I.getOperand(0);
1286 SDOperand Src = getValue(SrcV);
1287 SDOperand Ptr = getValue(I.getOperand(1));
1288 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1289 DAG.getSrcValue(I.getOperand(1))));
1290 }
1291 break;
1292 }
1293 break; // don't do this optimization, use a normal memset
1294 case ISD::MEMMOVE:
1295 case ISD::MEMCPY:
1296 break; // FIXME: not implemented yet
1297 }
1298 }
1299#endif
1300
1301 // Non-optimized version
Chris Lattner7041ee32005-01-11 05:56:49 +00001302 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001303 Ops.push_back(getRoot());
Chris Lattner7041ee32005-01-11 05:56:49 +00001304 Ops.push_back(getValue(I.getOperand(1)));
1305 Ops.push_back(getValue(I.getOperand(2)));
1306 Ops.push_back(getValue(I.getOperand(3)));
1307 Ops.push_back(getValue(I.getOperand(4)));
1308 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00001309}
1310
Chris Lattner7041ee32005-01-11 05:56:49 +00001311//===----------------------------------------------------------------------===//
1312// SelectionDAGISel code
1313//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00001314
1315unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1316 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1317}
1318
Chris Lattner495a0b52005-08-17 06:37:43 +00001319void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00001320 // FIXME: we only modify the CFG to split critical edges. This
1321 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00001322}
Chris Lattner1c08c712005-01-07 07:47:53 +00001323
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001324
1325/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1326/// casting to the type of GEPI.
1327static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1328 Value *Ptr, Value *PtrOffset) {
1329 if (V) return V; // Already computed.
1330
1331 BasicBlock::iterator InsertPt;
1332 if (BB == GEPI->getParent()) {
1333 // If insert into the GEP's block, insert right after the GEP.
1334 InsertPt = GEPI;
1335 ++InsertPt;
1336 } else {
1337 // Otherwise, insert at the top of BB, after any PHI nodes
1338 InsertPt = BB->begin();
1339 while (isa<PHINode>(InsertPt)) ++InsertPt;
1340 }
1341
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001342 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1343 // BB so that there is only one value live across basic blocks (the cast
1344 // operand).
1345 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1346 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1347 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1348
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001349 // Add the offset, cast it to the right type.
1350 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1351 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1352 return V = Ptr;
1353}
1354
1355
1356/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1357/// selection, we want to be a bit careful about some things. In particular, if
1358/// we have a GEP instruction that is used in a different block than it is
1359/// defined, the addressing expression of the GEP cannot be folded into loads or
1360/// stores that use it. In this case, decompose the GEP and move constant
1361/// indices into blocks that use it.
1362static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1363 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001364 // If this GEP is only used inside the block it is defined in, there is no
1365 // need to rewrite it.
1366 bool isUsedOutsideDefBB = false;
1367 BasicBlock *DefBB = GEPI->getParent();
1368 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1369 UI != E; ++UI) {
1370 if (cast<Instruction>(*UI)->getParent() != DefBB) {
1371 isUsedOutsideDefBB = true;
1372 break;
1373 }
1374 }
1375 if (!isUsedOutsideDefBB) return;
1376
1377 // If this GEP has no non-zero constant indices, there is nothing we can do,
1378 // ignore it.
1379 bool hasConstantIndex = false;
1380 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1381 E = GEPI->op_end(); OI != E; ++OI) {
1382 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1383 if (CI->getRawValue()) {
1384 hasConstantIndex = true;
1385 break;
1386 }
1387 }
Chris Lattner3802c252005-12-11 09:05:13 +00001388 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1389 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001390
1391 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
1392 // constant offset (which we now know is non-zero) and deal with it later.
1393 uint64_t ConstantOffset = 0;
1394 const Type *UIntPtrTy = TD.getIntPtrType();
1395 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1396 const Type *Ty = GEPI->getOperand(0)->getType();
1397
1398 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1399 E = GEPI->op_end(); OI != E; ++OI) {
1400 Value *Idx = *OI;
1401 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1402 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1403 if (Field)
1404 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1405 Ty = StTy->getElementType(Field);
1406 } else {
1407 Ty = cast<SequentialType>(Ty)->getElementType();
1408
1409 // Handle constant subscripts.
1410 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1411 if (CI->getRawValue() == 0) continue;
1412
1413 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1414 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1415 else
1416 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1417 continue;
1418 }
1419
1420 // Ptr = Ptr + Idx * ElementSize;
1421
1422 // Cast Idx to UIntPtrTy if needed.
1423 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1424
1425 uint64_t ElementSize = TD.getTypeSize(Ty);
1426 // Mask off bits that should not be set.
1427 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1428 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1429
1430 // Multiply by the element size and add to the base.
1431 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1432 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1433 }
1434 }
1435
1436 // Make sure that the offset fits in uintptr_t.
1437 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1438 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1439
1440 // Okay, we have now emitted all of the variable index parts to the BB that
1441 // the GEP is defined in. Loop over all of the using instructions, inserting
1442 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001443 // instruction to use the newly computed value, making GEPI dead. When the
1444 // user is a load or store instruction address, we emit the add into the user
1445 // block, otherwise we use a canonical version right next to the gep (these
1446 // won't be foldable as addresses, so we might as well share the computation).
1447
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001448 std::map<BasicBlock*,Value*> InsertedExprs;
1449 while (!GEPI->use_empty()) {
1450 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001451
1452 // If this use is not foldable into the addressing mode, use a version
1453 // emitted in the GEP block.
1454 Value *NewVal;
1455 if (!isa<LoadInst>(User) &&
1456 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1457 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1458 Ptr, PtrOffset);
1459 } else {
1460 // Otherwise, insert the code in the User's block so it can be folded into
1461 // any users in that block.
1462 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001463 User->getParent(), GEPI,
1464 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001465 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00001466 User->replaceUsesOfWith(GEPI, NewVal);
1467 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001468
1469 // Finally, the GEP is dead, remove it.
1470 GEPI->eraseFromParent();
1471}
1472
Chris Lattner1c08c712005-01-07 07:47:53 +00001473bool SelectionDAGISel::runOnFunction(Function &Fn) {
1474 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1475 RegMap = MF.getSSARegMap();
1476 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1477
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001478 // First, split all critical edges for PHI nodes with incoming values that are
1479 // constants, this way the load of the constant into a vreg will not be placed
1480 // into MBBs that are used some other way.
1481 //
1482 // In this pass we also look for GEP instructions that are used across basic
1483 // blocks and rewrites them to improve basic-block-at-a-time selection.
1484 //
Chris Lattner36b708f2005-08-18 17:35:14 +00001485 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1486 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001487 BasicBlock::iterator BBI;
1488 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00001489 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1490 if (isa<Constant>(PN->getIncomingValue(i)))
1491 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001492
1493 for (BasicBlock::iterator E = BB->end(); BBI != E; )
1494 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1495 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00001496 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001497
Chris Lattner1c08c712005-01-07 07:47:53 +00001498 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1499
1500 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1501 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00001502
Chris Lattner1c08c712005-01-07 07:47:53 +00001503 return true;
1504}
1505
1506
Chris Lattnerddb870b2005-01-13 17:59:43 +00001507SDOperand SelectionDAGISel::
1508CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001509 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00001510 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001511 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00001512 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001513
1514 // If this type is not legal, we must make sure to not create an invalid
1515 // register use.
1516 MVT::ValueType SrcVT = Op.getValueType();
1517 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1518 SelectionDAG &DAG = SDL.DAG;
1519 if (SrcVT == DestVT) {
1520 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1521 } else if (SrcVT < DestVT) {
1522 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00001523 if (MVT::isFloatingPoint(SrcVT))
1524 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1525 else
Chris Lattnerfab08872005-09-02 00:19:37 +00001526 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00001527 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1528 } else {
1529 // The src value is expanded into multiple registers.
1530 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1531 Op, DAG.getConstant(0, MVT::i32));
1532 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1533 Op, DAG.getConstant(1, MVT::i32));
1534 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1535 return DAG.getCopyToReg(Op, Reg+1, Hi);
1536 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001537}
1538
Chris Lattner068a81e2005-01-17 17:15:02 +00001539void SelectionDAGISel::
1540LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1541 std::vector<SDOperand> &UnorderedChains) {
1542 // If this is the entry block, emit arguments.
1543 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00001544 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00001545 SDOperand OldRoot = SDL.DAG.getRoot();
1546 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00001547
Chris Lattnerbf209482005-10-30 19:42:35 +00001548 unsigned a = 0;
1549 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1550 AI != E; ++AI, ++a)
1551 if (!AI->use_empty()) {
1552 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00001553
Chris Lattnerbf209482005-10-30 19:42:35 +00001554 // If this argument is live outside of the entry block, insert a copy from
1555 // whereever we got it to the vreg that other BB's will reference it as.
1556 if (FuncInfo.ValueMap.count(AI)) {
1557 SDOperand Copy =
1558 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1559 UnorderedChains.push_back(Copy);
1560 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00001561 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001562
1563 // Next, if the function has live ins that need to be copied into vregs,
1564 // emit the copies now, into the top of the block.
1565 MachineFunction &MF = SDL.DAG.getMachineFunction();
1566 if (MF.livein_begin() != MF.livein_end()) {
1567 SSARegMap *RegMap = MF.getSSARegMap();
1568 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1569 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1570 E = MF.livein_end(); LI != E; ++LI)
1571 if (LI->second)
1572 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1573 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00001574 }
Chris Lattnerbf209482005-10-30 19:42:35 +00001575
1576 // Finally, if the target has anything special to do, allow it to do so.
1577 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00001578}
1579
1580
Chris Lattner1c08c712005-01-07 07:47:53 +00001581void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1582 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1583 FunctionLoweringInfo &FuncInfo) {
1584 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001585
1586 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001587
Chris Lattnerbf209482005-10-30 19:42:35 +00001588 // Lower any arguments needed in this block if this is the entry block.
1589 if (LLVMBB == &LLVMBB->getParent()->front())
1590 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00001591
1592 BB = FuncInfo.MBBMap[LLVMBB];
1593 SDL.setCurrentBasicBlock(BB);
1594
1595 // Lower all of the non-terminator instructions.
1596 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1597 I != E; ++I)
1598 SDL.visit(*I);
1599
1600 // Ensure that all instructions which are used outside of their defining
1601 // blocks are available as virtual registers.
1602 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00001603 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00001604 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00001605 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00001606 UnorderedChains.push_back(
1607 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00001608 }
1609
1610 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
1611 // ensure constants are generated when needed. Remember the virtual registers
1612 // that need to be added to the Machine PHI nodes as input. We cannot just
1613 // directly add them, because expansion might result in multiple MBB's for one
1614 // BB. As such, the start of the BB might correspond to a different MBB than
1615 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00001616 //
Chris Lattner1c08c712005-01-07 07:47:53 +00001617
1618 // Emit constants only once even if used by multiple PHI nodes.
1619 std::map<Constant*, unsigned> ConstantsOut;
1620
1621 // Check successor nodes PHI nodes that expect a constant to be available from
1622 // this block.
1623 TerminatorInst *TI = LLVMBB->getTerminator();
1624 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1625 BasicBlock *SuccBB = TI->getSuccessor(succ);
1626 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1627 PHINode *PN;
1628
1629 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1630 // nodes and Machine PHI nodes, but the incoming operands have not been
1631 // emitted yet.
1632 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00001633 (PN = dyn_cast<PHINode>(I)); ++I)
1634 if (!PN->use_empty()) {
1635 unsigned Reg;
1636 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1637 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1638 unsigned &RegOut = ConstantsOut[C];
1639 if (RegOut == 0) {
1640 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001641 UnorderedChains.push_back(
1642 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00001643 }
1644 Reg = RegOut;
1645 } else {
1646 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00001647 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001648 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00001649 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1650 "Didn't codegen value into a register!??");
1651 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00001652 UnorderedChains.push_back(
1653 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00001654 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001655 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001656
Chris Lattnerf44fd882005-01-07 21:34:19 +00001657 // Remember that this register needs to added to the machine PHI node as
1658 // the input for this MBB.
1659 unsigned NumElements =
1660 TLI.getNumElements(TLI.getValueType(PN->getType()));
1661 for (unsigned i = 0, e = NumElements; i != e; ++i)
1662 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00001663 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001664 }
1665 ConstantsOut.clear();
1666
Chris Lattnerddb870b2005-01-13 17:59:43 +00001667 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00001668 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00001669 SDOperand Root = SDL.getRoot();
1670 if (Root.getOpcode() != ISD::EntryToken) {
1671 unsigned i = 0, e = UnorderedChains.size();
1672 for (; i != e; ++i) {
1673 assert(UnorderedChains[i].Val->getNumOperands() > 1);
1674 if (UnorderedChains[i].Val->getOperand(0) == Root)
1675 break; // Don't add the root if we already indirectly depend on it.
1676 }
1677
1678 if (i == e)
1679 UnorderedChains.push_back(Root);
1680 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00001681 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1682 }
1683
Chris Lattner1c08c712005-01-07 07:47:53 +00001684 // Lower the terminator after the copies are emitted.
1685 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00001686
1687 // Make sure the root of the DAG is up-to-date.
1688 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00001689}
1690
1691void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1692 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00001693 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00001694 CurDAG = &DAG;
1695 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1696
1697 // First step, lower LLVM code to some DAG. This DAG may use operations and
1698 // types that are not supported by the target.
1699 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1700
Chris Lattneraf21d552005-10-10 16:47:10 +00001701 // Run the DAG combiner in pre-legalize mode.
1702 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00001703
Chris Lattner1c08c712005-01-07 07:47:53 +00001704 DEBUG(std::cerr << "Lowered selection DAG:\n");
1705 DEBUG(DAG.dump());
1706
1707 // Second step, hack on the DAG until it only uses operations and types that
1708 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00001709 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00001710
1711 DEBUG(std::cerr << "Legalized selection DAG:\n");
1712 DEBUG(DAG.dump());
1713
Chris Lattneraf21d552005-10-10 16:47:10 +00001714 // Run the DAG combiner in post-legalize mode.
1715 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00001716
Evan Chenga9c20912006-01-21 02:32:06 +00001717 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00001718
Chris Lattnera33ef482005-03-30 01:10:47 +00001719 // Third, instruction select all of the operations to machine code, adding the
1720 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00001721 InstructionSelectBasicBlock(DAG);
1722
Chris Lattner1c08c712005-01-07 07:47:53 +00001723 DEBUG(std::cerr << "Selected machine code:\n");
1724 DEBUG(BB->dump());
1725
Chris Lattnera33ef482005-03-30 01:10:47 +00001726 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00001727 // PHI nodes in successors.
1728 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1729 MachineInstr *PHI = PHINodesToUpdate[i].first;
1730 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1731 "This is not a machine PHI node that we are updating!");
1732 PHI->addRegOperand(PHINodesToUpdate[i].second);
1733 PHI->addMachineBasicBlockOperand(BB);
1734 }
Chris Lattnera33ef482005-03-30 01:10:47 +00001735
1736 // Finally, add the CFG edges from the last selected MBB to the successor
1737 // MBBs.
1738 TerminatorInst *TI = LLVMBB->getTerminator();
1739 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1740 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1741 BB->addSuccessor(Succ0MBB);
1742 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001743}
Evan Chenga9c20912006-01-21 02:32:06 +00001744
1745//===----------------------------------------------------------------------===//
1746/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1747/// target node in the graph.
1748void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1749 if (ViewSchedDAGs) DAG.viewGraph();
1750 ScheduleDAG *SL = createSimpleDAGScheduler(DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00001751 BB = SL->Run();
Evan Chenga9c20912006-01-21 02:32:06 +00001752}