blob: 84daabbd635704349fa03a047e1c1997f1429d09 [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"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000026#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey95eda5b2006-08-01 14:21:23 +000032#include "llvm/CodeGen/MachinePassRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000036#include "llvm/Target/TargetData.h"
37#include "llvm/Target/TargetFrameInfo.h"
38#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000041#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000043#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner996795b2006-06-28 23:17:24 +000046#include "llvm/Support/Visibility.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Evan Chengc1e1d972006-01-23 07:01:07 +000064namespace {
Jim Laskey95eda5b2006-08-01 14:21:23 +000065 cl::opt<const char *, false, RegisterPassParser<RegisterScheduler> >
66 ISHeuristic("sched",
67 cl::init("default"),
68 cl::desc("Instruction schedulers available:"));
69
Jim Laskey03593f72006-08-01 18:29:48 +000070 static RegisterScheduler
Jim Laskey95eda5b2006-08-01 14:21:23 +000071 defaultListDAGScheduler("default", " Best scheduler for the target", NULL);
Evan Chengc1e1d972006-01-23 07:01:07 +000072} // namespace
73
Chris Lattner6f87d182006-02-22 22:37:12 +000074namespace {
75 /// RegsForValue - This struct represents the physical registers that a
76 /// particular value is assigned and the type information about the value.
77 /// This is needed because values can be promoted into larger registers and
78 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000079 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000080 /// Regs - This list hold the register (for legal and promoted values)
81 /// or register set (for expanded values) that the value should be assigned
82 /// to.
83 std::vector<unsigned> Regs;
84
85 /// RegVT - The value type of each register.
86 ///
87 MVT::ValueType RegVT;
88
89 /// ValueVT - The value type of the LLVM value, which may be promoted from
90 /// RegVT or made from merging the two expanded parts.
91 MVT::ValueType ValueVT;
92
93 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
94
95 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
96 : RegVT(regvt), ValueVT(valuevt) {
97 Regs.push_back(Reg);
98 }
99 RegsForValue(const std::vector<unsigned> &regs,
100 MVT::ValueType regvt, MVT::ValueType valuevt)
101 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
102 }
103
104 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
105 /// this value and returns the result as a ValueVT value. This uses
106 /// Chain/Flag as the input and updates them for the output Chain/Flag.
107 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000108 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000109
110 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
111 /// specified value into the registers specified by this object. This uses
112 /// Chain/Flag as the input and updates them for the output Chain/Flag.
113 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000114 SDOperand &Chain, SDOperand &Flag,
115 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000116
117 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
118 /// operand list. This adds the code marker and includes the number of
119 /// values added into it.
120 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000121 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000122 };
123}
Evan Chengc1e1d972006-01-23 07:01:07 +0000124
Chris Lattner7a60d912005-01-07 07:47:53 +0000125namespace llvm {
126 //===--------------------------------------------------------------------===//
127 /// FunctionLoweringInfo - This contains information that is global to a
128 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000129 class FunctionLoweringInfo {
130 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000131 TargetLowering &TLI;
132 Function &Fn;
133 MachineFunction &MF;
134 SSARegMap *RegMap;
135
136 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
137
138 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
139 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
140
141 /// ValueMap - Since we emit code for the function a basic block at a time,
142 /// we must remember which virtual registers hold the values for
143 /// cross-basic-block values.
144 std::map<const Value*, unsigned> ValueMap;
145
146 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
147 /// the entry block. This allows the allocas to be efficiently referenced
148 /// anywhere in the function.
149 std::map<const AllocaInst*, int> StaticAllocaMap;
150
151 unsigned MakeReg(MVT::ValueType VT) {
152 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
153 }
Misha Brukman835702a2005-04-21 22:36:52 +0000154
Chris Lattner49409cb2006-03-16 19:51:18 +0000155 unsigned CreateRegForValue(const Value *V);
156
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 unsigned InitializeRegForValue(const Value *V) {
158 unsigned &R = ValueMap[V];
159 assert(R == 0 && "Already initialized this value register!");
160 return R = CreateRegForValue(V);
161 }
162 };
163}
164
165/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000166/// PHI nodes or outside of the basic block that defines it, or used by a
167/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000168static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
169 if (isa<PHINode>(I)) return true;
170 BasicBlock *BB = I->getParent();
171 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000172 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
173 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 return true;
175 return false;
176}
177
Chris Lattner6871b232005-10-30 19:42:35 +0000178/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000179/// entry block, return true. This includes arguments used by switches, since
180/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000181static bool isOnlyUsedInEntryBlock(Argument *A) {
182 BasicBlock *Entry = A->getParent()->begin();
183 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000184 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000185 return false; // Use not in entry block.
186 return true;
187}
188
Chris Lattner7a60d912005-01-07 07:47:53 +0000189FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000190 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000191 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
192
Chris Lattner6871b232005-10-30 19:42:35 +0000193 // Create a vreg for each argument register that is not dead and is used
194 // outside of the entry block for the function.
195 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
196 AI != E; ++AI)
197 if (!isOnlyUsedInEntryBlock(AI))
198 InitializeRegForValue(AI);
199
Chris Lattner7a60d912005-01-07 07:47:53 +0000200 // Initialize the mapping of values to registers. This is only set up for
201 // instruction values that are used outside of the block that defines
202 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000203 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000204 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
205 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
206 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
207 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000208 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000209 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000210 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000211 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000212
213 // If the alignment of the value is smaller than the size of the value,
214 // and if the size of the value is particularly small (<= 8 bytes),
215 // round up to the size of the value for potentially better performance.
216 //
217 // FIXME: This could be made better with a preferred alignment hook in
218 // TargetData. It serves primarily to 8-byte align doubles for X86.
219 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000220 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000221 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000222 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000223 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 }
225
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000226 for (; BB != EB; ++BB)
227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
229 if (!isa<AllocaInst>(I) ||
230 !StaticAllocaMap.count(cast<AllocaInst>(I)))
231 InitializeRegForValue(I);
232
233 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
234 // also creates the initial PHI MachineInstrs, though none of the input
235 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000236 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
238 MBBMap[BB] = MBB;
239 MF.getBasicBlockList().push_back(MBB);
240
241 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
242 // appropriate.
243 PHINode *PN;
244 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000245 (PN = dyn_cast<PHINode>(I)); ++I)
246 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000247 MVT::ValueType VT = TLI.getValueType(PN->getType());
248 unsigned NumElements;
249 if (VT != MVT::Vector)
250 NumElements = TLI.getNumElements(VT);
251 else {
252 MVT::ValueType VT1,VT2;
253 NumElements =
254 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
255 VT1, VT2);
256 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000257 unsigned PHIReg = ValueMap[PN];
258 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
259 for (unsigned i = 0; i != NumElements; ++i)
260 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
261 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000262 }
263}
264
Chris Lattner49409cb2006-03-16 19:51:18 +0000265/// CreateRegForValue - Allocate the appropriate number of virtual registers of
266/// the correctly promoted or expanded types. Assign these registers
267/// consecutive vreg numbers and return the first assigned number.
268unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
269 MVT::ValueType VT = TLI.getValueType(V->getType());
270
271 // The number of multiples of registers that we need, to, e.g., split up
272 // a <2 x int64> -> 4 x i32 registers.
273 unsigned NumVectorRegs = 1;
274
275 // If this is a packed type, figure out what type it will decompose into
276 // and how many of the elements it will use.
277 if (VT == MVT::Vector) {
278 const PackedType *PTy = cast<PackedType>(V->getType());
279 unsigned NumElts = PTy->getNumElements();
280 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
281
282 // Divide the input until we get to a supported size. This will always
283 // end with a scalar if the target doesn't support vectors.
284 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
285 NumElts >>= 1;
286 NumVectorRegs <<= 1;
287 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000288 if (NumElts == 1)
289 VT = EltTy;
290 else
291 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000292 }
293
294 // The common case is that we will only create one register for this
295 // value. If we have that case, create and return the virtual register.
296 unsigned NV = TLI.getNumElements(VT);
297 if (NV == 1) {
298 // If we are promoting this value, pick the next largest supported type.
299 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
300 unsigned Reg = MakeReg(PromotedType);
301 // If this is a vector of supported or promoted types (e.g. 4 x i16),
302 // create all of the registers.
303 for (unsigned i = 1; i != NumVectorRegs; ++i)
304 MakeReg(PromotedType);
305 return Reg;
306 }
307
308 // If this value is represented with multiple target registers, make sure
309 // to create enough consecutive registers of the right (smaller) type.
310 unsigned NT = VT-1; // Find the type to use.
311 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
312 --NT;
313
314 unsigned R = MakeReg((MVT::ValueType)NT);
315 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
316 MakeReg((MVT::ValueType)NT);
317 return R;
318}
Chris Lattner7a60d912005-01-07 07:47:53 +0000319
320//===----------------------------------------------------------------------===//
321/// SelectionDAGLowering - This is the common target-independent lowering
322/// implementation that is parameterized by a TargetLowering object.
323/// Also, targets can overload any lowering method.
324///
325namespace llvm {
326class SelectionDAGLowering {
327 MachineBasicBlock *CurMBB;
328
329 std::map<const Value*, SDOperand> NodeMap;
330
Chris Lattner4d9651c2005-01-17 22:19:26 +0000331 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
332 /// them up and then emit token factor nodes when possible. This allows us to
333 /// get simple disambiguation between loads without worrying about alias
334 /// analysis.
335 std::vector<SDOperand> PendingLoads;
336
Nate Begemaned728c12006-03-27 01:32:24 +0000337 /// Case - A pair of values to record the Value for a switch case, and the
338 /// case's target basic block.
339 typedef std::pair<Constant*, MachineBasicBlock*> Case;
340 typedef std::vector<Case>::iterator CaseItr;
341 typedef std::pair<CaseItr, CaseItr> CaseRange;
342
343 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
344 /// of conditional branches.
345 struct CaseRec {
346 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
347 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
348
349 /// CaseBB - The MBB in which to emit the compare and branch
350 MachineBasicBlock *CaseBB;
351 /// LT, GE - If nonzero, we know the current case value must be less-than or
352 /// greater-than-or-equal-to these Constants.
353 Constant *LT;
354 Constant *GE;
355 /// Range - A pair of iterators representing the range of case values to be
356 /// processed at this point in the binary search tree.
357 CaseRange Range;
358 };
359
360 /// The comparison function for sorting Case values.
361 struct CaseCmp {
362 bool operator () (const Case& C1, const Case& C2) {
363 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
364 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
365
366 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
367 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
368 }
369 };
370
Chris Lattner7a60d912005-01-07 07:47:53 +0000371public:
372 // TLI - This is information that describes the available target features we
373 // need for lowering. This indicates when operations are unavailable,
374 // implemented with a libcall, etc.
375 TargetLowering &TLI;
376 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000377 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000378
Nate Begemaned728c12006-03-27 01:32:24 +0000379 /// SwitchCases - Vector of CaseBlock structures used to communicate
380 /// SwitchInst code generation information.
381 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000382 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000383
Chris Lattner7a60d912005-01-07 07:47:53 +0000384 /// FuncInfo - Information about the function as a whole.
385 ///
386 FunctionLoweringInfo &FuncInfo;
387
388 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000389 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000390 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000391 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000392 }
393
Chris Lattner4108bb02005-01-17 19:43:36 +0000394 /// getRoot - Return the current virtual root of the Selection DAG.
395 ///
396 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000397 if (PendingLoads.empty())
398 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000399
Chris Lattner4d9651c2005-01-17 22:19:26 +0000400 if (PendingLoads.size() == 1) {
401 SDOperand Root = PendingLoads[0];
402 DAG.setRoot(Root);
403 PendingLoads.clear();
404 return Root;
405 }
406
407 // Otherwise, we have to make a token factor node.
408 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
409 PendingLoads.clear();
410 DAG.setRoot(Root);
411 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000412 }
413
Chris Lattner7a60d912005-01-07 07:47:53 +0000414 void visit(Instruction &I) { visit(I.getOpcode(), I); }
415
416 void visit(unsigned Opcode, User &I) {
417 switch (Opcode) {
418 default: assert(0 && "Unknown instruction type encountered!");
419 abort();
420 // Build the switch statement using the Instruction.def file.
421#define HANDLE_INST(NUM, OPCODE, CLASS) \
422 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
423#include "llvm/Instruction.def"
424 }
425 }
426
427 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
428
Chris Lattner4024c002006-03-15 22:19:46 +0000429 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
430 SDOperand SrcValue, SDOperand Root,
431 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000432
433 SDOperand getIntPtrConstant(uint64_t Val) {
434 return DAG.getConstant(Val, TLI.getPointerTy());
435 }
436
Chris Lattner8471b152006-03-16 19:57:50 +0000437 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000438
439 const SDOperand &setValue(const Value *V, SDOperand NewN) {
440 SDOperand &N = NodeMap[V];
441 assert(N.Val == 0 && "Already set a value for this node!");
442 return N = NewN;
443 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000444
Chris Lattner6f87d182006-02-22 22:37:12 +0000445 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
446 MVT::ValueType VT,
447 bool OutReg, bool InReg,
448 std::set<unsigned> &OutputRegs,
449 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000450
Chris Lattner7a60d912005-01-07 07:47:53 +0000451 // Terminator instructions.
452 void visitRet(ReturnInst &I);
453 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000454 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 void visitUnreachable(UnreachableInst &I) { /* noop */ }
456
Nate Begemaned728c12006-03-27 01:32:24 +0000457 // Helper for visitSwitch
458 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000459 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000460
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000462 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
463 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
464
Nate Begemanb2e089c2005-11-19 00:36:38 +0000465 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000466 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000467 void visitAdd(User &I) {
468 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000469 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000470 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000471 void visitMul(User &I) {
472 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000473 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000475 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000476 visitBinary(I,
477 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
478 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 }
480 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000481 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000482 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000483 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000484 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
485 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
486 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000487 void visitShl(User &I) { visitShift(I, ISD::SHL); }
488 void visitShr(User &I) {
489 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000490 }
491
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000492 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
493 ISD::CondCode FPOpc);
494 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
495 ISD::SETOEQ); }
496 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
497 ISD::SETUNE); }
498 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
499 ISD::SETOLE); }
500 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
501 ISD::SETOGE); }
502 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
503 ISD::SETOLT); }
504 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
505 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000506
Chris Lattner67271862006-03-29 00:11:43 +0000507 void visitExtractElement(User &I);
508 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000509 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000510
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 void visitGetElementPtr(User &I);
512 void visitCast(User &I);
513 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000514
515 void visitMalloc(MallocInst &I);
516 void visitFree(FreeInst &I);
517 void visitAlloca(AllocaInst &I);
518 void visitLoad(LoadInst &I);
519 void visitStore(StoreInst &I);
520 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
521 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000522 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000523 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000524 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000525
Chris Lattner7a60d912005-01-07 07:47:53 +0000526 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527 void visitVAArg(VAArgInst &I);
528 void visitVAEnd(CallInst &I);
529 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000530 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000531
Chris Lattner875def92005-01-11 05:56:49 +0000532 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000533
534 void visitUserOp1(Instruction &I) {
535 assert(0 && "UserOp1 should not exist at instruction selection time!");
536 abort();
537 }
538 void visitUserOp2(Instruction &I) {
539 assert(0 && "UserOp2 should not exist at instruction selection time!");
540 abort();
541 }
542};
543} // end namespace llvm
544
Chris Lattner8471b152006-03-16 19:57:50 +0000545SDOperand SelectionDAGLowering::getValue(const Value *V) {
546 SDOperand &N = NodeMap[V];
547 if (N.Val) return N;
548
549 const Type *VTy = V->getType();
550 MVT::ValueType VT = TLI.getValueType(VTy);
551 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
553 visit(CE->getOpcode(), *CE);
554 assert(N.Val && "visit didn't populate the ValueMap!");
555 return N;
556 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
557 return N = DAG.getGlobalAddress(GV, VT);
558 } else if (isa<ConstantPointerNull>(C)) {
559 return N = DAG.getConstant(0, TLI.getPointerTy());
560 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000561 if (!isa<PackedType>(VTy))
562 return N = DAG.getNode(ISD::UNDEF, VT);
563
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000564 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000565 const PackedType *PTy = cast<PackedType>(VTy);
566 unsigned NumElements = PTy->getNumElements();
567 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
568
569 std::vector<SDOperand> Ops;
570 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
571
572 // Create a VConstant node with generic Vector type.
573 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
574 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000575 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000576 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
577 return N = DAG.getConstantFP(CFP->getValue(), VT);
578 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
579 unsigned NumElements = PTy->getNumElements();
580 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000581
582 // Now that we know the number and type of the elements, push a
583 // Constant or ConstantFP node onto the ops list for each element of
584 // the packed constant.
585 std::vector<SDOperand> Ops;
586 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000587 for (unsigned i = 0; i != NumElements; ++i)
588 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000589 } else {
590 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
591 SDOperand Op;
592 if (MVT::isFloatingPoint(PVT))
593 Op = DAG.getConstantFP(0, PVT);
594 else
595 Op = DAG.getConstant(0, PVT);
596 Ops.assign(NumElements, Op);
597 }
598
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000599 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000600 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
601 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000602 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner8471b152006-03-16 19:57:50 +0000603 } else {
604 // Canonicalize all constant ints to be unsigned.
605 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
606 }
607 }
608
609 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
610 std::map<const AllocaInst*, int>::iterator SI =
611 FuncInfo.StaticAllocaMap.find(AI);
612 if (SI != FuncInfo.StaticAllocaMap.end())
613 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
614 }
615
616 std::map<const Value*, unsigned>::const_iterator VMI =
617 FuncInfo.ValueMap.find(V);
618 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
619
620 unsigned InReg = VMI->second;
621
622 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000623 if (VT != MVT::Vector) {
624 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000625
Chris Lattner5fe1f542006-03-31 02:06:56 +0000626 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
627 if (DestVT < VT) {
628 // Source must be expanded. This input value is actually coming from the
629 // register pair VMI->second and VMI->second+1.
630 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
631 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
632 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000633 if (MVT::isFloatingPoint(VT))
634 N = DAG.getNode(ISD::FP_ROUND, VT, N);
635 else
636 N = DAG.getNode(ISD::TRUNCATE, VT, N);
637 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000638 } else {
639 // Otherwise, if this is a vector, make it available as a generic vector
640 // here.
641 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000642 const PackedType *PTy = cast<PackedType>(VTy);
643 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000644 PTyLegalElementVT);
645
646 // Build a VBUILD_VECTOR with the input registers.
647 std::vector<SDOperand> Ops;
648 if (PTyElementVT == PTyLegalElementVT) {
649 // If the value types are legal, just VBUILD the CopyFromReg nodes.
650 for (unsigned i = 0; i != NE; ++i)
651 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
652 PTyElementVT));
653 } else if (PTyElementVT < PTyLegalElementVT) {
654 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
655 for (unsigned i = 0; i != NE; ++i) {
656 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
657 PTyElementVT);
658 if (MVT::isFloatingPoint(PTyElementVT))
659 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
660 else
661 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
662 Ops.push_back(Op);
663 }
664 } else {
665 // If the register was expanded, use BUILD_PAIR.
666 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
667 for (unsigned i = 0; i != NE/2; ++i) {
668 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
669 PTyElementVT);
670 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
671 PTyElementVT);
672 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
673 }
674 }
675
676 Ops.push_back(DAG.getConstant(NE, MVT::i32));
677 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
678 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
Chris Lattner4a2413a2006-04-05 06:54:42 +0000679
680 // Finally, use a VBIT_CONVERT to make this available as the appropriate
681 // vector type.
682 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
683 DAG.getConstant(PTy->getNumElements(),
684 MVT::i32),
685 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000686 }
687
688 return N;
689}
690
691
Chris Lattner7a60d912005-01-07 07:47:53 +0000692void SelectionDAGLowering::visitRet(ReturnInst &I) {
693 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000694 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000695 return;
696 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000697 std::vector<SDOperand> NewValues;
698 NewValues.push_back(getRoot());
699 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
700 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000701 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000702
703 // If this is an integer return value, we need to promote it ourselves to
704 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
705 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000706 // FIXME: C calling convention requires the return type to be promoted to
707 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000708 if (MVT::isInteger(RetOp.getValueType()) &&
709 RetOp.getValueType() < MVT::i64) {
710 MVT::ValueType TmpVT;
711 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
712 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
713 else
714 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000715
Evan Chenga2e99532006-05-26 23:09:09 +0000716 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000717 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
718 else
719 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
720 }
721 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000722 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000723 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000724 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000725}
726
727void SelectionDAGLowering::visitBr(BranchInst &I) {
728 // Update machine-CFG edges.
729 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000730 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000731
732 // Figure out which block is immediately after the current one.
733 MachineBasicBlock *NextBlock = 0;
734 MachineFunction::iterator BBI = CurMBB;
735 if (++BBI != CurMBB->getParent()->end())
736 NextBlock = BBI;
737
738 if (I.isUnconditional()) {
739 // If this is not a fall-through branch, emit the branch.
740 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000741 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000742 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000743 } else {
744 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000745 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000746
747 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000748 if (Succ1MBB == NextBlock) {
749 // If the condition is false, fall through. This means we should branch
750 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000751 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000752 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000753 } else if (Succ0MBB == NextBlock) {
754 // If the condition is true, fall through. This means we should branch if
755 // the condition is false to Succ #1. Invert the condition first.
756 SDOperand True = DAG.getConstant(1, Cond.getValueType());
757 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000758 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000759 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000760 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000761 std::vector<SDOperand> Ops;
762 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000763 // If the false case is the current basic block, then this is a self
764 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
765 // adds an extra instruction in the loop. Instead, invert the
766 // condition and emit "Loop: ... br!cond Loop; br Out.
767 if (CurMBB == Succ1MBB) {
768 std::swap(Succ0MBB, Succ1MBB);
769 SDOperand True = DAG.getConstant(1, Cond.getValueType());
770 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
771 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000772 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
773 DAG.getBasicBlock(Succ0MBB));
774 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
775 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000776 }
777 }
778}
779
Nate Begemaned728c12006-03-27 01:32:24 +0000780/// visitSwitchCase - Emits the necessary code to represent a single node in
781/// the binary search tree resulting from lowering a switch instruction.
782void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
783 SDOperand SwitchOp = getValue(CB.SwitchV);
784 SDOperand CaseOp = getValue(CB.CaseC);
785 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
786
787 // Set NextBlock to be the MBB immediately after the current one, if any.
788 // This is used to avoid emitting unnecessary branches to the next block.
789 MachineBasicBlock *NextBlock = 0;
790 MachineFunction::iterator BBI = CurMBB;
791 if (++BBI != CurMBB->getParent()->end())
792 NextBlock = BBI;
793
794 // If the lhs block is the next block, invert the condition so that we can
795 // fall through to the lhs instead of the rhs block.
796 if (CB.LHSBB == NextBlock) {
797 std::swap(CB.LHSBB, CB.RHSBB);
798 SDOperand True = DAG.getConstant(1, Cond.getValueType());
799 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
800 }
801 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
802 DAG.getBasicBlock(CB.LHSBB));
803 if (CB.RHSBB == NextBlock)
804 DAG.setRoot(BrCond);
805 else
806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
807 DAG.getBasicBlock(CB.RHSBB)));
808 // Update successor info
809 CurMBB->addSuccessor(CB.LHSBB);
810 CurMBB->addSuccessor(CB.RHSBB);
811}
812
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000813/// visitSwitchCase - Emits the necessary code to represent a single node in
814/// the binary search tree resulting from lowering a switch instruction.
815void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
816 // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
817 // we need to add the address of the jump table to the value loaded, since
818 // the entries in the jump table will be differences rather than absolute
819 // addresses.
820
821 // Emit the code for the jump table
822 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000823 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
824 "Jump table entries are 32-bit values");
825 // PIC jump table entries are 32-bit values.
826 unsigned EntrySize =
827 (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_)
828 ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000829 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
830 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000831 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +0000832 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
833 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000834 SDOperand LD = DAG.getLoad(MVT::i32, Copy.getValue(1), ADD,
835 DAG.getSrcValue(0));
Nate Begeman78756502006-07-27 01:13:04 +0000836 if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000837 ADD = DAG.getNode(ISD::ADD, PTy,
838 ((PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD), TAB);
Nate Begeman78756502006-07-27 01:13:04 +0000839 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
840 } else {
841 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
842 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000843}
844
Nate Begemaned728c12006-03-27 01:32:24 +0000845void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
846 // Figure out which block is immediately after the current one.
847 MachineBasicBlock *NextBlock = 0;
848 MachineFunction::iterator BBI = CurMBB;
849 if (++BBI != CurMBB->getParent()->end())
850 NextBlock = BBI;
851
852 // If there is only the default destination, branch to it if it is not the
853 // next basic block. Otherwise, just fall through.
854 if (I.getNumOperands() == 2) {
855 // Update machine-CFG edges.
856 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
857 // If this is not a fall-through branch, emit the branch.
858 if (DefaultMBB != NextBlock)
859 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
860 DAG.getBasicBlock(DefaultMBB)));
Chris Lattner32d92e02006-06-12 18:25:29 +0000861 CurMBB->addSuccessor(DefaultMBB);
Nate Begemaned728c12006-03-27 01:32:24 +0000862 return;
863 }
864
865 // If there are any non-default case statements, create a vector of Cases
866 // representing each one, and sort the vector so that we can efficiently
867 // create a binary search tree from them.
868 std::vector<Case> Cases;
869 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
870 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
871 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
872 }
873 std::sort(Cases.begin(), Cases.end(), CaseCmp());
874
875 // Get the Value to be switched on and default basic blocks, which will be
876 // inserted into CaseBlock records, representing basic blocks in the binary
877 // search tree.
878 Value *SV = I.getOperand(0);
879 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000880
881 // Get the MachineFunction which holds the current MBB. This is used during
882 // emission of jump tables, and when inserting any additional MBBs necessary
883 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +0000884 MachineFunction *CurMF = CurMBB->getParent();
885 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000886
Nate Begemand7a19102006-05-08 16:51:36 +0000887 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
888 // target supports indirect branches, then emit a jump table rather than
889 // lowering the switch to a binary tree of conditional branches.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000890 // FIXME: Make this work with PIC code
Nate Begeman866b4b42006-04-23 06:26:20 +0000891 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +0000892 Cases.size() > 5) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000893 uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
894 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
Nate Begemandf488392006-05-03 03:48:02 +0000895 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
896
Nate Begemand7a19102006-05-08 16:51:36 +0000897 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000898 // Create a new basic block to hold the code for loading the address
899 // of the jump table, and jumping to it. Update successor information;
900 // we will either branch to the default case for the switch, or the jump
901 // table.
902 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
903 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
904 CurMBB->addSuccessor(Default);
905 CurMBB->addSuccessor(JumpTableBB);
906
907 // Subtract the lowest switch case value from the value being switched on
908 // and conditional branch to default mbb if the result is greater than the
909 // difference between smallest and largest cases.
910 SDOperand SwitchOp = getValue(SV);
911 MVT::ValueType VT = SwitchOp.getValueType();
912 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
913 DAG.getConstant(First, VT));
914
915 // The SDNode we just created, which holds the value being switched on
916 // minus the the smallest case value, needs to be copied to a virtual
917 // register so it can be used as an index into the jump table in a
918 // subsequent basic block. This value may be smaller or larger than the
919 // target's pointer type, and therefore require extension or truncating.
920 if (VT > TLI.getPointerTy())
921 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
922 else
923 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
924 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
925 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
926
927 // Emit the range check for the jump table, and branch to the default
928 // block for the switch statement if the value being switched on exceeds
929 // the largest case in the switch.
930 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
931 DAG.getConstant(Last-First,VT), ISD::SETUGT);
932 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
933 DAG.getBasicBlock(Default)));
934
Nate Begemandf488392006-05-03 03:48:02 +0000935 // Build a vector of destination BBs, corresponding to each target
936 // of the jump table. If the value of the jump table slot corresponds to
937 // a case statement, push the case's BB onto the vector, otherwise, push
938 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000939 std::set<MachineBasicBlock*> UniqueBBs;
940 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +0000941 uint64_t TEI = First;
942 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
943 if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
944 DestBBs.push_back(ii->second);
945 UniqueBBs.insert(ii->second);
946 ++ii;
947 } else {
948 DestBBs.push_back(Default);
949 UniqueBBs.insert(Default);
950 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000951 }
Nate Begemandf488392006-05-03 03:48:02 +0000952
953 // Update successor info
954 for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(),
955 ee = UniqueBBs.end(); ii != ee; ++ii)
956 JumpTableBB->addSuccessor(*ii);
957
958 // Create a jump table index for this jump table, or return an existing
959 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000960 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
961
962 // Set the jump table information so that we can codegen it as a second
963 // MachineBasicBlock
964 JT.Reg = JumpTableReg;
965 JT.JTI = JTI;
966 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +0000967 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000968 return;
969 }
970 }
Nate Begemaned728c12006-03-27 01:32:24 +0000971
972 // Push the initial CaseRec onto the worklist
973 std::vector<CaseRec> CaseVec;
974 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
975
976 while (!CaseVec.empty()) {
977 // Grab a record representing a case range to process off the worklist
978 CaseRec CR = CaseVec.back();
979 CaseVec.pop_back();
980
981 // Size is the number of Cases represented by this range. If Size is 1,
982 // then we are processing a leaf of the binary search tree. Otherwise,
983 // we need to pick a pivot, and push left and right ranges onto the
984 // worklist.
985 unsigned Size = CR.Range.second - CR.Range.first;
986
987 if (Size == 1) {
988 // Create a CaseBlock record representing a conditional branch to
989 // the Case's target mbb if the value being switched on SV is equal
990 // to C. Otherwise, branch to default.
991 Constant *C = CR.Range.first->first;
992 MachineBasicBlock *Target = CR.Range.first->second;
993 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
994 CR.CaseBB);
995 // If the MBB representing the leaf node is the current MBB, then just
996 // call visitSwitchCase to emit the code into the current block.
997 // Otherwise, push the CaseBlock onto the vector to be later processed
998 // by SDISel, and insert the node's MBB before the next MBB.
999 if (CR.CaseBB == CurMBB)
1000 visitSwitchCase(CB);
1001 else {
1002 SwitchCases.push_back(CB);
1003 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1004 }
1005 } else {
1006 // split case range at pivot
1007 CaseItr Pivot = CR.Range.first + (Size / 2);
1008 CaseRange LHSR(CR.Range.first, Pivot);
1009 CaseRange RHSR(Pivot, CR.Range.second);
1010 Constant *C = Pivot->first;
1011 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1012 // We know that we branch to the LHS if the Value being switched on is
1013 // less than the Pivot value, C. We use this to optimize our binary
1014 // tree a bit, by recognizing that if SV is greater than or equal to the
1015 // LHS's Case Value, and that Case Value is exactly one less than the
1016 // Pivot's Value, then we can branch directly to the LHS's Target,
1017 // rather than creating a leaf node for it.
1018 if ((LHSR.second - LHSR.first) == 1 &&
1019 LHSR.first->first == CR.GE &&
1020 cast<ConstantIntegral>(C)->getRawValue() ==
1021 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1022 LHSBB = LHSR.first->second;
1023 } else {
1024 LHSBB = new MachineBasicBlock(LLVMBB);
1025 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1026 }
1027 // Similar to the optimization above, if the Value being switched on is
1028 // known to be less than the Constant CR.LT, and the current Case Value
1029 // is CR.LT - 1, then we can branch directly to the target block for
1030 // the current Case Value, rather than emitting a RHS leaf node for it.
1031 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1032 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1033 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1034 RHSBB = RHSR.first->second;
1035 } else {
1036 RHSBB = new MachineBasicBlock(LLVMBB);
1037 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1038 }
1039 // Create a CaseBlock record representing a conditional branch to
1040 // the LHS node if the value being switched on SV is less than C.
1041 // Otherwise, branch to LHS.
1042 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1043 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1044 if (CR.CaseBB == CurMBB)
1045 visitSwitchCase(CB);
1046 else {
1047 SwitchCases.push_back(CB);
1048 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1049 }
1050 }
1051 }
1052}
1053
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001054void SelectionDAGLowering::visitSub(User &I) {
1055 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001056 if (I.getType()->isFloatingPoint()) {
1057 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1058 if (CFP->isExactlyValue(-0.0)) {
1059 SDOperand Op2 = getValue(I.getOperand(1));
1060 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1061 return;
1062 }
Chris Lattner6f3b5772005-09-28 22:28:18 +00001063 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001064 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001065}
1066
Nate Begemanb2e089c2005-11-19 00:36:38 +00001067void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1068 unsigned VecOp) {
1069 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001070 SDOperand Op1 = getValue(I.getOperand(0));
1071 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001072
Chris Lattner19baba62005-11-19 18:40:42 +00001073 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001074 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1075 } else if (Ty->isFloatingPoint()) {
1076 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1077 } else {
1078 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +00001079 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1080 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1081 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001082 }
Nate Begeman127321b2005-11-18 07:42:56 +00001083}
Chris Lattner96c26752005-01-19 22:31:21 +00001084
Nate Begeman127321b2005-11-18 07:42:56 +00001085void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1086 SDOperand Op1 = getValue(I.getOperand(0));
1087 SDOperand Op2 = getValue(I.getOperand(1));
1088
1089 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1090
Chris Lattner7a60d912005-01-07 07:47:53 +00001091 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1092}
1093
1094void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001095 ISD::CondCode UnsignedOpcode,
1096 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001097 SDOperand Op1 = getValue(I.getOperand(0));
1098 SDOperand Op2 = getValue(I.getOperand(1));
1099 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001100 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001101 Opcode = FPOpcode;
1102 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001103 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001104 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001105}
1106
1107void SelectionDAGLowering::visitSelect(User &I) {
1108 SDOperand Cond = getValue(I.getOperand(0));
1109 SDOperand TrueVal = getValue(I.getOperand(1));
1110 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001111 if (!isa<PackedType>(I.getType())) {
1112 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1113 TrueVal, FalseVal));
1114 } else {
1115 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1116 *(TrueVal.Val->op_end()-2),
1117 *(TrueVal.Val->op_end()-1)));
1118 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001119}
1120
1121void SelectionDAGLowering::visitCast(User &I) {
1122 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001123 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001124 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001125
Chris Lattner2f4119a2006-03-22 20:09:35 +00001126 if (DestVT == MVT::Vector) {
1127 // This is a cast to a vector from something else. This is always a bit
1128 // convert. Get information about the input vector.
1129 const PackedType *DestTy = cast<PackedType>(I.getType());
1130 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1131 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1132 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1133 DAG.getValueType(EltVT)));
1134 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001135 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001136 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001137 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001138 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001139 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001140 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001141 } else if (isInteger(SrcVT)) {
1142 if (isInteger(DestVT)) { // Int -> Int cast
1143 if (DestVT < SrcVT) // Truncating cast?
1144 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001145 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001146 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001147 else
Chris Lattner4024c002006-03-15 22:19:46 +00001148 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001149 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001150 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001151 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001152 else
Chris Lattner4024c002006-03-15 22:19:46 +00001153 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001154 } else {
1155 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001156 }
Chris Lattner4024c002006-03-15 22:19:46 +00001157 } else if (isFloatingPoint(SrcVT)) {
1158 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1159 if (DestVT < SrcVT) // Rounding cast?
1160 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001161 else
Chris Lattner4024c002006-03-15 22:19:46 +00001162 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001163 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001164 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001165 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001166 else
Chris Lattner4024c002006-03-15 22:19:46 +00001167 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001168 } else {
1169 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001170 }
1171 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001172 assert(SrcVT == MVT::Vector && "Unknown cast!");
1173 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1174 // This is a cast from a vector to something else. This is always a bit
1175 // convert. Get information about the input vector.
1176 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001177 }
1178}
1179
Chris Lattner67271862006-03-29 00:11:43 +00001180void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001181 SDOperand InVec = getValue(I.getOperand(0));
1182 SDOperand InVal = getValue(I.getOperand(1));
1183 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1184 getValue(I.getOperand(2)));
1185
Chris Lattner29b23012006-03-19 01:17:20 +00001186 SDOperand Num = *(InVec.Val->op_end()-2);
1187 SDOperand Typ = *(InVec.Val->op_end()-1);
1188 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1189 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001190}
1191
Chris Lattner67271862006-03-29 00:11:43 +00001192void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001193 SDOperand InVec = getValue(I.getOperand(0));
1194 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1195 getValue(I.getOperand(1)));
1196 SDOperand Typ = *(InVec.Val->op_end()-1);
1197 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1198 TLI.getValueType(I.getType()), InVec, InIdx));
1199}
Chris Lattner32206f52006-03-18 01:44:44 +00001200
Chris Lattner098c01e2006-04-08 04:15:24 +00001201void SelectionDAGLowering::visitShuffleVector(User &I) {
1202 SDOperand V1 = getValue(I.getOperand(0));
1203 SDOperand V2 = getValue(I.getOperand(1));
1204 SDOperand Mask = getValue(I.getOperand(2));
1205
1206 SDOperand Num = *(V1.Val->op_end()-2);
1207 SDOperand Typ = *(V2.Val->op_end()-1);
1208 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1209 V1, V2, Mask, Num, Typ));
1210}
1211
1212
Chris Lattner7a60d912005-01-07 07:47:53 +00001213void SelectionDAGLowering::visitGetElementPtr(User &I) {
1214 SDOperand N = getValue(I.getOperand(0));
1215 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001216
1217 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1218 OI != E; ++OI) {
1219 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001220 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001221 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1222 if (Field) {
1223 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001224 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001225 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001226 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001227 }
1228 Ty = StTy->getElementType(Field);
1229 } else {
1230 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001231
Chris Lattner43535a12005-11-09 04:45:33 +00001232 // If this is a constant subscript, handle it quickly.
1233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1234 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +00001235
Chris Lattner43535a12005-11-09 04:45:33 +00001236 uint64_t Offs;
1237 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
Owen Anderson20a631f2006-05-03 01:29:57 +00001238 Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001239 else
Owen Anderson20a631f2006-05-03 01:29:57 +00001240 Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001241 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1242 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001243 }
Chris Lattner43535a12005-11-09 04:45:33 +00001244
1245 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001246 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001247 SDOperand IdxN = getValue(Idx);
1248
1249 // If the index is smaller or larger than intptr_t, truncate or extend
1250 // it.
1251 if (IdxN.getValueType() < N.getValueType()) {
1252 if (Idx->getType()->isSigned())
1253 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1254 else
1255 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1256 } else if (IdxN.getValueType() > N.getValueType())
1257 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1258
1259 // If this is a multiply by a power of two, turn it into a shl
1260 // immediately. This is a very common case.
1261 if (isPowerOf2_64(ElementSize)) {
1262 unsigned Amt = Log2_64(ElementSize);
1263 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001264 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001265 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1266 continue;
1267 }
1268
1269 SDOperand Scale = getIntPtrConstant(ElementSize);
1270 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1271 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001272 }
1273 }
1274 setValue(&I, N);
1275}
1276
1277void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1278 // If this is a fixed sized alloca in the entry block of the function,
1279 // allocate it statically on the stack.
1280 if (FuncInfo.StaticAllocaMap.count(&I))
1281 return; // getValue will auto-populate this.
1282
1283 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001284 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1285 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001286 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001287
1288 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001289 MVT::ValueType IntPtr = TLI.getPointerTy();
1290 if (IntPtr < AllocSize.getValueType())
1291 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1292 else if (IntPtr > AllocSize.getValueType())
1293 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001294
Chris Lattnereccb73d2005-01-22 23:04:37 +00001295 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001296 getIntPtrConstant(TySize));
1297
1298 // Handle alignment. If the requested alignment is less than or equal to the
1299 // stack alignment, ignore it and round the size of the allocation up to the
1300 // stack alignment size. If the size is greater than the stack alignment, we
1301 // note this in the DYNAMIC_STACKALLOC node.
1302 unsigned StackAlign =
1303 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1304 if (Align <= StackAlign) {
1305 Align = 0;
1306 // Add SA-1 to the size.
1307 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1308 getIntPtrConstant(StackAlign-1));
1309 // Mask out the low bits for alignment purposes.
1310 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1311 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1312 }
1313
Chris Lattner96c262e2005-05-14 07:29:57 +00001314 std::vector<MVT::ValueType> VTs;
1315 VTs.push_back(AllocSize.getValueType());
1316 VTs.push_back(MVT::Other);
1317 std::vector<SDOperand> Ops;
1318 Ops.push_back(getRoot());
1319 Ops.push_back(AllocSize);
1320 Ops.push_back(getIntPtrConstant(Align));
1321 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +00001322 DAG.setRoot(setValue(&I, DSA).getValue(1));
1323
1324 // Inform the Frame Information that we have just allocated a variable-sized
1325 // object.
1326 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1327}
1328
Chris Lattner7a60d912005-01-07 07:47:53 +00001329void SelectionDAGLowering::visitLoad(LoadInst &I) {
1330 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001331
Chris Lattner4d9651c2005-01-17 22:19:26 +00001332 SDOperand Root;
1333 if (I.isVolatile())
1334 Root = getRoot();
1335 else {
1336 // Do not serialize non-volatile loads against each other.
1337 Root = DAG.getRoot();
1338 }
Chris Lattner4024c002006-03-15 22:19:46 +00001339
1340 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1341 Root, I.isVolatile()));
1342}
1343
1344SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1345 SDOperand SrcValue, SDOperand Root,
1346 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001347 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001348 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001349 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner32206f52006-03-18 01:44:44 +00001350 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001351 } else {
Chris Lattner4024c002006-03-15 22:19:46 +00001352 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001353 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001354
Chris Lattner4024c002006-03-15 22:19:46 +00001355 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001356 DAG.setRoot(L.getValue(1));
1357 else
1358 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001359
1360 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001361}
1362
1363
1364void SelectionDAGLowering::visitStore(StoreInst &I) {
1365 Value *SrcV = I.getOperand(0);
1366 SDOperand Src = getValue(SrcV);
1367 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +00001368 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +00001369 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001370}
1371
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001372/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1373/// access memory and has no other side effects at all.
1374static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1375#define GET_NO_MEMORY_INTRINSICS
1376#include "llvm/Intrinsics.gen"
1377#undef GET_NO_MEMORY_INTRINSICS
1378 return false;
1379}
1380
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001381// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1382// have any side-effects or if it only reads memory.
1383static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1384#define GET_SIDE_EFFECT_INFO
1385#include "llvm/Intrinsics.gen"
1386#undef GET_SIDE_EFFECT_INFO
1387 return false;
1388}
1389
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001390/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1391/// node.
1392void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1393 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001394 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001395 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001396
1397 // Build the operand list.
1398 std::vector<SDOperand> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001399 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1400 if (OnlyLoad) {
1401 // We don't need to serialize loads against other loads.
1402 Ops.push_back(DAG.getRoot());
1403 } else {
1404 Ops.push_back(getRoot());
1405 }
1406 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001407
1408 // Add the intrinsic ID as an integer operand.
1409 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1410
1411 // Add all operands of the call to the operand list.
1412 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1413 SDOperand Op = getValue(I.getOperand(i));
1414
1415 // If this is a vector type, force it to the right packed type.
1416 if (Op.getValueType() == MVT::Vector) {
1417 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1418 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1419
1420 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1421 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1422 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1423 }
1424
1425 assert(TLI.isTypeLegal(Op.getValueType()) &&
1426 "Intrinsic uses a non-legal type?");
1427 Ops.push_back(Op);
1428 }
1429
1430 std::vector<MVT::ValueType> VTs;
1431 if (I.getType() != Type::VoidTy) {
1432 MVT::ValueType VT = TLI.getValueType(I.getType());
1433 if (VT == MVT::Vector) {
1434 const PackedType *DestTy = cast<PackedType>(I.getType());
1435 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1436
1437 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1438 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1439 }
1440
1441 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1442 VTs.push_back(VT);
1443 }
1444 if (HasChain)
1445 VTs.push_back(MVT::Other);
1446
1447 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001448 SDOperand Result;
1449 if (!HasChain)
1450 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1451 else if (I.getType() != Type::VoidTy)
1452 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1453 else
1454 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1455
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001456 if (HasChain) {
1457 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1458 if (OnlyLoad)
1459 PendingLoads.push_back(Chain);
1460 else
1461 DAG.setRoot(Chain);
1462 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001463 if (I.getType() != Type::VoidTy) {
1464 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1465 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1466 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1467 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1468 DAG.getValueType(EVT));
1469 }
1470 setValue(&I, Result);
1471 }
1472}
1473
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001474/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1475/// we want to emit this as a call to a named external function, return the name
1476/// otherwise lower it and return null.
1477const char *
1478SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1479 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001480 default:
1481 // By default, turn this into a target intrinsic node.
1482 visitTargetIntrinsic(I, Intrinsic);
1483 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001484 case Intrinsic::vastart: visitVAStart(I); return 0;
1485 case Intrinsic::vaend: visitVAEnd(I); return 0;
1486 case Intrinsic::vacopy: visitVACopy(I); return 0;
1487 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1488 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1489 case Intrinsic::setjmp:
1490 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1491 break;
1492 case Intrinsic::longjmp:
1493 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1494 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001495 case Intrinsic::memcpy_i32:
1496 case Intrinsic::memcpy_i64:
1497 visitMemIntrinsic(I, ISD::MEMCPY);
1498 return 0;
1499 case Intrinsic::memset_i32:
1500 case Intrinsic::memset_i64:
1501 visitMemIntrinsic(I, ISD::MEMSET);
1502 return 0;
1503 case Intrinsic::memmove_i32:
1504 case Intrinsic::memmove_i64:
1505 visitMemIntrinsic(I, ISD::MEMMOVE);
1506 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001507
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001508 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001509 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001510 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001511 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Jim Laskey5995d012006-02-11 01:01:30 +00001512 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +00001513
Jim Laskey5995d012006-02-11 01:01:30 +00001514 Ops.push_back(getRoot());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001515 Ops.push_back(getValue(SPI.getLineValue()));
1516 Ops.push_back(getValue(SPI.getColumnValue()));
Chris Lattner435b4022005-11-29 06:21:05 +00001517
Jim Laskeya8bdac82006-03-23 18:06:46 +00001518 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001519 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001520 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1521
Jim Laskey5995d012006-02-11 01:01:30 +00001522 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1523 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1524
Jim Laskeya8bdac82006-03-23 18:06:46 +00001525 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001526 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001527
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001528 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001529 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001530 case Intrinsic::dbg_region_start: {
1531 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1532 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001533 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001534 std::vector<SDOperand> Ops;
1535
1536 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1537
1538 Ops.push_back(getRoot());
1539 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1540
1541 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1542 }
1543
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001544 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001545 }
1546 case Intrinsic::dbg_region_end: {
1547 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1548 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001549 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001550 std::vector<SDOperand> Ops;
1551
1552 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1553
1554 Ops.push_back(getRoot());
1555 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1556
1557 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1558 }
1559
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001560 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001561 }
1562 case Intrinsic::dbg_func_start: {
1563 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1564 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001565 if (DebugInfo && FSI.getSubprogram() &&
1566 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001567 std::vector<SDOperand> Ops;
1568
1569 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1570
1571 Ops.push_back(getRoot());
1572 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1573
1574 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1575 }
1576
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001577 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001578 }
1579 case Intrinsic::dbg_declare: {
1580 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1581 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001582 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001583 std::vector<SDOperand> Ops;
1584
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001585 SDOperand AddressOp = getValue(DI.getAddress());
1586 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001587 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1588 }
1589 }
1590
1591 return 0;
1592 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001593
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001594 case Intrinsic::isunordered_f32:
1595 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001596 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1597 getValue(I.getOperand(2)), ISD::SETUO));
1598 return 0;
1599
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001600 case Intrinsic::sqrt_f32:
1601 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001602 setValue(&I, DAG.getNode(ISD::FSQRT,
1603 getValue(I.getOperand(1)).getValueType(),
1604 getValue(I.getOperand(1))));
1605 return 0;
1606 case Intrinsic::pcmarker: {
1607 SDOperand Tmp = getValue(I.getOperand(1));
1608 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1609 return 0;
1610 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001611 case Intrinsic::readcyclecounter: {
1612 std::vector<MVT::ValueType> VTs;
1613 VTs.push_back(MVT::i64);
1614 VTs.push_back(MVT::Other);
1615 std::vector<SDOperand> Ops;
1616 Ops.push_back(getRoot());
1617 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1618 setValue(&I, Tmp);
1619 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001620 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001621 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001622 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001623 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001624 case Intrinsic::bswap_i64:
1625 setValue(&I, DAG.getNode(ISD::BSWAP,
1626 getValue(I.getOperand(1)).getValueType(),
1627 getValue(I.getOperand(1))));
1628 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001629 case Intrinsic::cttz_i8:
1630 case Intrinsic::cttz_i16:
1631 case Intrinsic::cttz_i32:
1632 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001633 setValue(&I, DAG.getNode(ISD::CTTZ,
1634 getValue(I.getOperand(1)).getValueType(),
1635 getValue(I.getOperand(1))));
1636 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001637 case Intrinsic::ctlz_i8:
1638 case Intrinsic::ctlz_i16:
1639 case Intrinsic::ctlz_i32:
1640 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001641 setValue(&I, DAG.getNode(ISD::CTLZ,
1642 getValue(I.getOperand(1)).getValueType(),
1643 getValue(I.getOperand(1))));
1644 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001645 case Intrinsic::ctpop_i8:
1646 case Intrinsic::ctpop_i16:
1647 case Intrinsic::ctpop_i32:
1648 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001649 setValue(&I, DAG.getNode(ISD::CTPOP,
1650 getValue(I.getOperand(1)).getValueType(),
1651 getValue(I.getOperand(1))));
1652 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001653 case Intrinsic::stacksave: {
1654 std::vector<MVT::ValueType> VTs;
1655 VTs.push_back(TLI.getPointerTy());
1656 VTs.push_back(MVT::Other);
1657 std::vector<SDOperand> Ops;
1658 Ops.push_back(getRoot());
1659 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1660 setValue(&I, Tmp);
1661 DAG.setRoot(Tmp.getValue(1));
1662 return 0;
1663 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001664 case Intrinsic::stackrestore: {
1665 SDOperand Tmp = getValue(I.getOperand(1));
1666 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001667 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001668 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001669 case Intrinsic::prefetch:
1670 // FIXME: Currently discarding prefetches.
1671 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001672 }
1673}
1674
1675
Chris Lattner7a60d912005-01-07 07:47:53 +00001676void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001677 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001678 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001679 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001680 if (unsigned IID = F->getIntrinsicID()) {
1681 RenameFn = visitIntrinsicCall(I, IID);
1682 if (!RenameFn)
1683 return;
1684 } else { // Not an LLVM intrinsic.
1685 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001686 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1687 if (I.getNumOperands() == 3 && // Basic sanity checks.
1688 I.getOperand(1)->getType()->isFloatingPoint() &&
1689 I.getType() == I.getOperand(1)->getType() &&
1690 I.getType() == I.getOperand(2)->getType()) {
1691 SDOperand LHS = getValue(I.getOperand(1));
1692 SDOperand RHS = getValue(I.getOperand(2));
1693 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1694 LHS, RHS));
1695 return;
1696 }
1697 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001698 if (I.getNumOperands() == 2 && // Basic sanity checks.
1699 I.getOperand(1)->getType()->isFloatingPoint() &&
1700 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001701 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001702 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1703 return;
1704 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001705 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001706 if (I.getNumOperands() == 2 && // Basic sanity checks.
1707 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001708 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001709 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001710 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1711 return;
1712 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001713 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001714 if (I.getNumOperands() == 2 && // Basic sanity checks.
1715 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001716 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001717 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001718 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1719 return;
1720 }
1721 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001722 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001723 } else if (isa<InlineAsm>(I.getOperand(0))) {
1724 visitInlineAsm(I);
1725 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001726 }
Misha Brukman835702a2005-04-21 22:36:52 +00001727
Chris Lattner18d2b342005-01-08 22:48:57 +00001728 SDOperand Callee;
1729 if (!RenameFn)
1730 Callee = getValue(I.getOperand(0));
1731 else
1732 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001733 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001734 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001735 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1736 Value *Arg = I.getOperand(i);
1737 SDOperand ArgNode = getValue(Arg);
1738 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1739 }
Misha Brukman835702a2005-04-21 22:36:52 +00001740
Nate Begemanf6565252005-03-26 01:29:23 +00001741 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1742 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001743
Chris Lattner1f45cd72005-01-08 19:26:18 +00001744 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001745 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001746 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001747 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001748 setValue(&I, Result.first);
1749 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001750}
1751
Chris Lattner6f87d182006-02-22 22:37:12 +00001752SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001753 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001754 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1755 Chain = Val.getValue(1);
1756 Flag = Val.getValue(2);
1757
1758 // If the result was expanded, copy from the top part.
1759 if (Regs.size() > 1) {
1760 assert(Regs.size() == 2 &&
1761 "Cannot expand to more than 2 elts yet!");
1762 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1763 Chain = Val.getValue(1);
1764 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001765 if (DAG.getTargetLoweringInfo().isLittleEndian())
1766 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1767 else
1768 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001769 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001770
Chris Lattner705948d2006-06-08 18:22:48 +00001771 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00001772 // appropriate type.
1773 if (RegVT == ValueVT)
1774 return Val;
1775
Chris Lattner705948d2006-06-08 18:22:48 +00001776 if (MVT::isInteger(RegVT)) {
1777 if (ValueVT < RegVT)
1778 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1779 else
1780 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1781 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001782 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00001783 }
Chris Lattner6f87d182006-02-22 22:37:12 +00001784}
1785
Chris Lattner571d9642006-02-23 19:21:04 +00001786/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1787/// specified value into the registers specified by this object. This uses
1788/// Chain/Flag as the input and updates them for the output Chain/Flag.
1789void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00001790 SDOperand &Chain, SDOperand &Flag,
1791 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001792 if (Regs.size() == 1) {
1793 // If there is a single register and the types differ, this must be
1794 // a promotion.
1795 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00001796 if (MVT::isInteger(RegVT)) {
1797 if (RegVT < ValueVT)
1798 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1799 else
1800 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1801 } else
Chris Lattner571d9642006-02-23 19:21:04 +00001802 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1803 }
1804 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1805 Flag = Chain.getValue(1);
1806 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001807 std::vector<unsigned> R(Regs);
1808 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1809 std::reverse(R.begin(), R.end());
1810
1811 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001812 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00001813 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001814 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001815 Flag = Chain.getValue(1);
1816 }
1817 }
1818}
Chris Lattner6f87d182006-02-22 22:37:12 +00001819
Chris Lattner571d9642006-02-23 19:21:04 +00001820/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1821/// operand list. This adds the code marker and includes the number of
1822/// values added into it.
1823void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001824 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001825 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1826 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1827 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1828}
Chris Lattner6f87d182006-02-22 22:37:12 +00001829
1830/// isAllocatableRegister - If the specified register is safe to allocate,
1831/// i.e. it isn't a stack pointer or some other special register, return the
1832/// register class for the register. Otherwise, return null.
1833static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001834isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1835 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001836 MVT::ValueType FoundVT = MVT::Other;
1837 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001838 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1839 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001840 MVT::ValueType ThisVT = MVT::Other;
1841
Chris Lattnerb1124f32006-02-22 23:09:03 +00001842 const TargetRegisterClass *RC = *RCI;
1843 // If none of the the value types for this register class are valid, we
1844 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001845 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1846 I != E; ++I) {
1847 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001848 // If we have already found this register in a different register class,
1849 // choose the one with the largest VT specified. For example, on
1850 // PowerPC, we favor f64 register classes over f32.
1851 if (FoundVT == MVT::Other ||
1852 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1853 ThisVT = *I;
1854 break;
1855 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001856 }
1857 }
1858
Chris Lattnerbec582f2006-04-02 00:24:45 +00001859 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001860
Chris Lattner6f87d182006-02-22 22:37:12 +00001861 // NOTE: This isn't ideal. In particular, this might allocate the
1862 // frame pointer in functions that need it (due to them not being taken
1863 // out of allocation, because a variable sized allocation hasn't been seen
1864 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001865 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1866 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001867 if (*I == Reg) {
1868 // We found a matching register class. Keep looking at others in case
1869 // we find one with larger registers that this physreg is also in.
1870 FoundRC = RC;
1871 FoundVT = ThisVT;
1872 break;
1873 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001874 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001875 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001876}
1877
1878RegsForValue SelectionDAGLowering::
1879GetRegistersForValue(const std::string &ConstrCode,
1880 MVT::ValueType VT, bool isOutReg, bool isInReg,
1881 std::set<unsigned> &OutputRegs,
1882 std::set<unsigned> &InputRegs) {
1883 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1884 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1885 std::vector<unsigned> Regs;
1886
1887 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1888 MVT::ValueType RegVT;
1889 MVT::ValueType ValueVT = VT;
1890
1891 if (PhysReg.first) {
1892 if (VT == MVT::Other)
1893 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00001894
1895 // Get the actual register value type. This is important, because the user
1896 // may have asked for (e.g.) the AX register in i32 type. We need to
1897 // remember that AX is actually i16 to get the right extension.
1898 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00001899
1900 // This is a explicit reference to a physical register.
1901 Regs.push_back(PhysReg.first);
1902
1903 // If this is an expanded reference, add the rest of the regs to Regs.
1904 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001905 TargetRegisterClass::iterator I = PhysReg.second->begin();
1906 TargetRegisterClass::iterator E = PhysReg.second->end();
1907 for (; *I != PhysReg.first; ++I)
1908 assert(I != E && "Didn't find reg!");
1909
1910 // Already added the first reg.
1911 --NumRegs; ++I;
1912 for (; NumRegs; --NumRegs, ++I) {
1913 assert(I != E && "Ran out of registers to allocate!");
1914 Regs.push_back(*I);
1915 }
1916 }
1917 return RegsForValue(Regs, RegVT, ValueVT);
1918 }
1919
1920 // This is a reference to a register class. Allocate NumRegs consecutive,
1921 // available, registers from the class.
1922 std::vector<unsigned> RegClassRegs =
1923 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1924
1925 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1926 MachineFunction &MF = *CurMBB->getParent();
1927 unsigned NumAllocated = 0;
1928 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1929 unsigned Reg = RegClassRegs[i];
1930 // See if this register is available.
1931 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1932 (isInReg && InputRegs.count(Reg))) { // Already used.
1933 // Make sure we find consecutive registers.
1934 NumAllocated = 0;
1935 continue;
1936 }
1937
1938 // Check to see if this register is allocatable (i.e. don't give out the
1939 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001940 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001941 if (!RC) {
1942 // Make sure we find consecutive registers.
1943 NumAllocated = 0;
1944 continue;
1945 }
1946
1947 // Okay, this register is good, we can use it.
1948 ++NumAllocated;
1949
1950 // If we allocated enough consecutive
1951 if (NumAllocated == NumRegs) {
1952 unsigned RegStart = (i-NumAllocated)+1;
1953 unsigned RegEnd = i+1;
1954 // Mark all of the allocated registers used.
1955 for (unsigned i = RegStart; i != RegEnd; ++i) {
1956 unsigned Reg = RegClassRegs[i];
1957 Regs.push_back(Reg);
1958 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1959 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1960 }
1961
1962 return RegsForValue(Regs, *RC->vt_begin(), VT);
1963 }
1964 }
1965
1966 // Otherwise, we couldn't allocate enough registers for this.
1967 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001968}
1969
Chris Lattner6f87d182006-02-22 22:37:12 +00001970
Chris Lattner476e67b2006-01-26 22:24:51 +00001971/// visitInlineAsm - Handle a call to an InlineAsm object.
1972///
1973void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1974 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1975
1976 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1977 MVT::Other);
1978
1979 // Note, we treat inline asms both with and without side-effects as the same.
1980 // If an inline asm doesn't have side effects and doesn't access memory, we
1981 // could not choose to not chain it.
1982 bool hasSideEffects = IA->hasSideEffects();
1983
Chris Lattner3a5ed552006-02-01 01:28:23 +00001984 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001985 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001986
1987 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1988 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1989 /// if it is a def of that register.
1990 std::vector<SDOperand> AsmNodeOperands;
1991 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1992 AsmNodeOperands.push_back(AsmStr);
1993
1994 SDOperand Chain = getRoot();
1995 SDOperand Flag;
1996
Chris Lattner1558fc62006-02-01 18:59:47 +00001997 // We fully assign registers here at isel time. This is not optimal, but
1998 // should work. For register classes that correspond to LLVM classes, we
1999 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2000 // over the constraints, collecting fixed registers that we know we can't use.
2001 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002002 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002003 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2004 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2005 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002006
Chris Lattner7ad77df2006-02-22 00:56:39 +00002007 MVT::ValueType OpVT;
2008
2009 // Compute the value type for each operand and add it to ConstraintVTs.
2010 switch (Constraints[i].Type) {
2011 case InlineAsm::isOutput:
2012 if (!Constraints[i].isIndirectOutput) {
2013 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2014 OpVT = TLI.getValueType(I.getType());
2015 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002016 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002017 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2018 OpNum++; // Consumes a call operand.
2019 }
2020 break;
2021 case InlineAsm::isInput:
2022 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2023 OpNum++; // Consumes a call operand.
2024 break;
2025 case InlineAsm::isClobber:
2026 OpVT = MVT::Other;
2027 break;
2028 }
2029
2030 ConstraintVTs.push_back(OpVT);
2031
Chris Lattner6f87d182006-02-22 22:37:12 +00002032 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2033 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002034
Chris Lattner6f87d182006-02-22 22:37:12 +00002035 // Build a list of regs that this operand uses. This always has a single
2036 // element for promoted/expanded operands.
2037 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2038 false, false,
2039 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002040
2041 switch (Constraints[i].Type) {
2042 case InlineAsm::isOutput:
2043 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002044 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002045 // If this is an early-clobber output, it cannot be assigned to the same
2046 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002047 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002048 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002049 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002050 case InlineAsm::isInput:
2051 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002052 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002053 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002054 case InlineAsm::isClobber:
2055 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002056 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2057 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002058 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002059 }
2060 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002061
Chris Lattner5c79f982006-02-21 23:12:12 +00002062 // Loop over all of the inputs, copying the operand values into the
2063 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002064 RegsForValue RetValRegs;
2065 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002066 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002067
Chris Lattner2e56e892006-01-31 02:03:41 +00002068 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002069 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2070 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002071
Chris Lattner3a5ed552006-02-01 01:28:23 +00002072 switch (Constraints[i].Type) {
2073 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002074 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2075 if (ConstraintCode.size() == 1) // not a physreg name.
2076 CTy = TLI.getConstraintType(ConstraintCode[0]);
2077
2078 if (CTy == TargetLowering::C_Memory) {
2079 // Memory output.
2080 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2081
2082 // Check that the operand (the address to store to) isn't a float.
2083 if (!MVT::isInteger(InOperandVal.getValueType()))
2084 assert(0 && "MATCH FAIL!");
2085
2086 if (!Constraints[i].isIndirectOutput)
2087 assert(0 && "MATCH FAIL!");
2088
2089 OpNum++; // Consumes a call operand.
2090
2091 // Extend/truncate to the right pointer type if needed.
2092 MVT::ValueType PtrType = TLI.getPointerTy();
2093 if (InOperandVal.getValueType() < PtrType)
2094 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2095 else if (InOperandVal.getValueType() > PtrType)
2096 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2097
2098 // Add information to the INLINEASM node to know about this output.
2099 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2100 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2101 AsmNodeOperands.push_back(InOperandVal);
2102 break;
2103 }
2104
2105 // Otherwise, this is a register output.
2106 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2107
Chris Lattner6f87d182006-02-22 22:37:12 +00002108 // If this is an early-clobber output, or if there is an input
2109 // constraint that matches this, we need to reserve the input register
2110 // so no other inputs allocate to it.
2111 bool UsesInputRegister = false;
2112 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2113 UsesInputRegister = true;
2114
2115 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002116 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002117 RegsForValue Regs =
2118 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2119 true, UsesInputRegister,
2120 OutputRegs, InputRegs);
2121 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002122
Chris Lattner3a5ed552006-02-01 01:28:23 +00002123 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002124 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002125 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002126 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002127 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002128 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002129 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2130 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002131 OpNum++; // Consumes a call operand.
2132 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002133
2134 // Add information to the INLINEASM node to know that this register is
2135 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002136 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002137 break;
2138 }
2139 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002140 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002141 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002142
Chris Lattner7f5880b2006-02-02 00:25:23 +00002143 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2144 // If this is required to match an output register we have already set,
2145 // just use its register.
2146 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002147
Chris Lattner571d9642006-02-23 19:21:04 +00002148 // Scan until we find the definition we already emitted of this operand.
2149 // When we find it, create a RegsForValue operand.
2150 unsigned CurOp = 2; // The first operand.
2151 for (; OperandNo; --OperandNo) {
2152 // Advance to the next operand.
2153 unsigned NumOps =
2154 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002155 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2156 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002157 "Skipped past definitions?");
2158 CurOp += (NumOps>>3)+1;
2159 }
2160
2161 unsigned NumOps =
2162 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2163 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2164 "Skipped past definitions?");
2165
2166 // Add NumOps>>3 registers to MatchedRegs.
2167 RegsForValue MatchedRegs;
2168 MatchedRegs.ValueVT = InOperandVal.getValueType();
2169 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2170 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2171 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2172 MatchedRegs.Regs.push_back(Reg);
2173 }
2174
2175 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002176 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2177 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002178 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002179 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002180 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002181
2182 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2183 if (ConstraintCode.size() == 1) // not a physreg name.
2184 CTy = TLI.getConstraintType(ConstraintCode[0]);
2185
2186 if (CTy == TargetLowering::C_Other) {
2187 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2188 assert(0 && "MATCH FAIL!");
2189
2190 // Add information to the INLINEASM node to know about this input.
2191 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2192 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2193 AsmNodeOperands.push_back(InOperandVal);
2194 break;
2195 } else if (CTy == TargetLowering::C_Memory) {
2196 // Memory input.
2197
2198 // Check that the operand isn't a float.
2199 if (!MVT::isInteger(InOperandVal.getValueType()))
2200 assert(0 && "MATCH FAIL!");
2201
2202 // Extend/truncate to the right pointer type if needed.
2203 MVT::ValueType PtrType = TLI.getPointerTy();
2204 if (InOperandVal.getValueType() < PtrType)
2205 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2206 else if (InOperandVal.getValueType() > PtrType)
2207 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2208
2209 // Add information to the INLINEASM node to know about this input.
2210 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2211 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2212 AsmNodeOperands.push_back(InOperandVal);
2213 break;
2214 }
2215
2216 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2217
2218 // Copy the input into the appropriate registers.
2219 RegsForValue InRegs =
2220 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2221 false, true, OutputRegs, InputRegs);
2222 // FIXME: should be match fail.
2223 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2224
Evan Chengef9e07d2006-06-15 08:11:54 +00002225 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002226
2227 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002228 break;
2229 }
Chris Lattner571d9642006-02-23 19:21:04 +00002230 case InlineAsm::isClobber: {
2231 RegsForValue ClobberedRegs =
2232 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2233 OutputRegs, InputRegs);
2234 // Add the clobbered value to the operand list, so that the register
2235 // allocator is aware that the physreg got clobbered.
2236 if (!ClobberedRegs.Regs.empty())
2237 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002238 break;
2239 }
Chris Lattner571d9642006-02-23 19:21:04 +00002240 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002241 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002242
2243 // Finish up input operands.
2244 AsmNodeOperands[0] = Chain;
2245 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2246
2247 std::vector<MVT::ValueType> VTs;
2248 VTs.push_back(MVT::Other);
2249 VTs.push_back(MVT::Flag);
2250 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2251 Flag = Chain.getValue(1);
2252
Chris Lattner2e56e892006-01-31 02:03:41 +00002253 // If this asm returns a register value, copy the result from that register
2254 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002255 if (!RetValRegs.Regs.empty())
2256 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002257
Chris Lattner2e56e892006-01-31 02:03:41 +00002258 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2259
2260 // Process indirect outputs, first output all of the flagged copies out of
2261 // physregs.
2262 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002263 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002264 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002265 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2266 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002267 }
2268
2269 // Emit the non-flagged stores from the physregs.
2270 std::vector<SDOperand> OutChains;
2271 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2272 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2273 StoresToEmit[i].first,
2274 getValue(StoresToEmit[i].second),
2275 DAG.getSrcValue(StoresToEmit[i].second)));
2276 if (!OutChains.empty())
2277 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00002278 DAG.setRoot(Chain);
2279}
2280
2281
Chris Lattner7a60d912005-01-07 07:47:53 +00002282void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2283 SDOperand Src = getValue(I.getOperand(0));
2284
2285 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002286
2287 if (IntPtr < Src.getValueType())
2288 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2289 else if (IntPtr > Src.getValueType())
2290 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002291
2292 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002293 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002294 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2295 Src, getIntPtrConstant(ElementSize));
2296
2297 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002298 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002299
2300 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002301 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002302 DAG.getExternalSymbol("malloc", IntPtr),
2303 Args, DAG);
2304 setValue(&I, Result.first); // Pointers always fit in registers
2305 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002306}
2307
2308void SelectionDAGLowering::visitFree(FreeInst &I) {
2309 std::vector<std::pair<SDOperand, const Type*> > Args;
2310 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002311 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002312 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002313 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002314 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002315 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2316 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002317}
2318
Chris Lattner13d7c252005-08-26 20:54:47 +00002319// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2320// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2321// instructions are special in various ways, which require special support to
2322// insert. The specified MachineInstr is created but not inserted into any
2323// basic blocks, and the scheduler passes ownership of it to this method.
2324MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2325 MachineBasicBlock *MBB) {
2326 std::cerr << "If a target marks an instruction with "
2327 "'usesCustomDAGSchedInserter', it must implement "
2328 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2329 abort();
2330 return 0;
2331}
2332
Chris Lattner58cfd792005-01-09 00:00:49 +00002333void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002334 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2335 getValue(I.getOperand(1)),
2336 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002337}
2338
2339void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002340 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2341 getValue(I.getOperand(0)),
2342 DAG.getSrcValue(I.getOperand(0)));
2343 setValue(&I, V);
2344 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002345}
2346
2347void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002348 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2349 getValue(I.getOperand(1)),
2350 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002351}
2352
2353void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002354 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2355 getValue(I.getOperand(1)),
2356 getValue(I.getOperand(2)),
2357 DAG.getSrcValue(I.getOperand(1)),
2358 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002359}
2360
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002361/// TargetLowering::LowerArguments - This is the default LowerArguments
2362/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002363/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2364/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002365std::vector<SDOperand>
2366TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2367 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2368 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002369 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002370 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2371 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2372
2373 // Add one result value for each formal argument.
2374 std::vector<MVT::ValueType> RetVals;
2375 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2376 MVT::ValueType VT = getValueType(I->getType());
2377
2378 switch (getTypeAction(VT)) {
2379 default: assert(0 && "Unknown type action!");
2380 case Legal:
2381 RetVals.push_back(VT);
2382 break;
2383 case Promote:
2384 RetVals.push_back(getTypeToTransformTo(VT));
2385 break;
2386 case Expand:
2387 if (VT != MVT::Vector) {
2388 // If this is a large integer, it needs to be broken up into small
2389 // integers. Figure out what the destination type is and how many small
2390 // integers it turns into.
2391 MVT::ValueType NVT = getTypeToTransformTo(VT);
2392 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2393 for (unsigned i = 0; i != NumVals; ++i)
2394 RetVals.push_back(NVT);
2395 } else {
2396 // Otherwise, this is a vector type. We only support legal vectors
2397 // right now.
2398 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2399 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002400
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002401 // Figure out if there is a Packed type corresponding to this Vector
2402 // type. If so, convert to the packed type.
2403 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2404 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2405 RetVals.push_back(TVT);
2406 } else {
2407 assert(0 && "Don't support illegal by-val vector arguments yet!");
2408 }
2409 }
2410 break;
2411 }
2412 }
Evan Cheng9618df12006-04-25 23:03:35 +00002413
Chris Lattner3d826992006-05-16 06:45:34 +00002414 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002415
2416 // Create the node.
2417 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002418
2419 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002420
2421 // Set up the return result vector.
2422 Ops.clear();
2423 unsigned i = 0;
2424 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2425 MVT::ValueType VT = getValueType(I->getType());
2426
2427 switch (getTypeAction(VT)) {
2428 default: assert(0 && "Unknown type action!");
2429 case Legal:
2430 Ops.push_back(SDOperand(Result, i++));
2431 break;
2432 case Promote: {
2433 SDOperand Op(Result, i++);
2434 if (MVT::isInteger(VT)) {
2435 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2436 : ISD::AssertZext;
2437 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2438 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2439 } else {
2440 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2441 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2442 }
2443 Ops.push_back(Op);
2444 break;
2445 }
2446 case Expand:
2447 if (VT != MVT::Vector) {
2448 // If this is a large integer, it needs to be reassembled from small
2449 // integers. Figure out what the source elt type is and how many small
2450 // integers it is.
2451 MVT::ValueType NVT = getTypeToTransformTo(VT);
2452 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2453 if (NumVals == 2) {
2454 SDOperand Lo = SDOperand(Result, i++);
2455 SDOperand Hi = SDOperand(Result, i++);
2456
2457 if (!isLittleEndian())
2458 std::swap(Lo, Hi);
2459
2460 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2461 } else {
2462 // Value scalarized into many values. Unimp for now.
2463 assert(0 && "Cannot expand i64 -> i16 yet!");
2464 }
2465 } else {
2466 // Otherwise, this is a vector type. We only support legal vectors
2467 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002468 const PackedType *PTy = cast<PackedType>(I->getType());
2469 unsigned NumElems = PTy->getNumElements();
2470 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002471
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002472 // Figure out if there is a Packed type corresponding to this Vector
2473 // type. If so, convert to the packed type.
2474 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002475 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002476 SDOperand N = SDOperand(Result, i++);
2477 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002478 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2479 DAG.getConstant(NumElems, MVT::i32),
2480 DAG.getValueType(getValueType(EltTy)));
2481 Ops.push_back(N);
2482 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002483 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002484 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002485 }
2486 }
2487 break;
2488 }
2489 }
2490 return Ops;
2491}
2492
Chris Lattneraaa23d92006-05-16 22:53:20 +00002493
2494/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2495/// implementation, which just inserts an ISD::CALL node, which is later custom
2496/// lowered by the target to something concrete. FIXME: When all targets are
2497/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2498std::pair<SDOperand, SDOperand>
2499TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2500 unsigned CallingConv, bool isTailCall,
2501 SDOperand Callee,
2502 ArgListTy &Args, SelectionDAG &DAG) {
2503 std::vector<SDOperand> Ops;
2504 Ops.push_back(Chain); // Op#0 - Chain
2505 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2506 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2507 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2508 Ops.push_back(Callee);
2509
2510 // Handle all of the outgoing arguments.
2511 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2512 MVT::ValueType VT = getValueType(Args[i].second);
2513 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002514 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002515 switch (getTypeAction(VT)) {
2516 default: assert(0 && "Unknown type action!");
2517 case Legal:
2518 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002519 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002520 break;
2521 case Promote:
2522 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002523 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002524 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2525 } else {
2526 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2527 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2528 }
2529 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002530 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002531 break;
2532 case Expand:
2533 if (VT != MVT::Vector) {
2534 // If this is a large integer, it needs to be broken down into small
2535 // integers. Figure out what the source elt type is and how many small
2536 // integers it is.
2537 MVT::ValueType NVT = getTypeToTransformTo(VT);
2538 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2539 if (NumVals == 2) {
2540 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2541 DAG.getConstant(0, getPointerTy()));
2542 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2543 DAG.getConstant(1, getPointerTy()));
2544 if (!isLittleEndian())
2545 std::swap(Lo, Hi);
2546
2547 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002548 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002549 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002550 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002551 } else {
2552 // Value scalarized into many values. Unimp for now.
2553 assert(0 && "Cannot expand i64 -> i16 yet!");
2554 }
2555 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002556 // Otherwise, this is a vector type. We only support legal vectors
2557 // right now.
2558 const PackedType *PTy = cast<PackedType>(Args[i].second);
2559 unsigned NumElems = PTy->getNumElements();
2560 const Type *EltTy = PTy->getElementType();
2561
2562 // Figure out if there is a Packed type corresponding to this Vector
2563 // type. If so, convert to the packed type.
2564 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002565 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2566 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2567 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2568 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002569 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002570 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002571 assert(0 && "Don't support illegal by-val vector call args yet!");
2572 abort();
2573 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002574 }
2575 break;
2576 }
2577 }
2578
2579 // Figure out the result value types.
2580 std::vector<MVT::ValueType> RetTys;
2581
2582 if (RetTy != Type::VoidTy) {
2583 MVT::ValueType VT = getValueType(RetTy);
2584 switch (getTypeAction(VT)) {
2585 default: assert(0 && "Unknown type action!");
2586 case Legal:
2587 RetTys.push_back(VT);
2588 break;
2589 case Promote:
2590 RetTys.push_back(getTypeToTransformTo(VT));
2591 break;
2592 case Expand:
2593 if (VT != MVT::Vector) {
2594 // If this is a large integer, it needs to be reassembled from small
2595 // integers. Figure out what the source elt type is and how many small
2596 // integers it is.
2597 MVT::ValueType NVT = getTypeToTransformTo(VT);
2598 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2599 for (unsigned i = 0; i != NumVals; ++i)
2600 RetTys.push_back(NVT);
2601 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002602 // Otherwise, this is a vector type. We only support legal vectors
2603 // right now.
2604 const PackedType *PTy = cast<PackedType>(RetTy);
2605 unsigned NumElems = PTy->getNumElements();
2606 const Type *EltTy = PTy->getElementType();
2607
2608 // Figure out if there is a Packed type corresponding to this Vector
2609 // type. If so, convert to the packed type.
2610 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2611 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2612 RetTys.push_back(TVT);
2613 } else {
2614 assert(0 && "Don't support illegal by-val vector call results yet!");
2615 abort();
2616 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002617 }
2618 }
2619 }
2620
2621 RetTys.push_back(MVT::Other); // Always has a chain.
2622
2623 // Finally, create the CALL node.
2624 SDOperand Res = DAG.getNode(ISD::CALL, RetTys, Ops);
2625
2626 // This returns a pair of operands. The first element is the
2627 // return value for the function (if RetTy is not VoidTy). The second
2628 // element is the outgoing token chain.
2629 SDOperand ResVal;
2630 if (RetTys.size() != 1) {
2631 MVT::ValueType VT = getValueType(RetTy);
2632 if (RetTys.size() == 2) {
2633 ResVal = Res;
2634
2635 // If this value was promoted, truncate it down.
2636 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002637 if (VT == MVT::Vector) {
2638 // Insert a VBITCONVERT to convert from the packed result type to the
2639 // MVT::Vector type.
2640 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2641 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2642
2643 // Figure out if there is a Packed type corresponding to this Vector
2644 // type. If so, convert to the packed type.
2645 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2646 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002647 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2648 // "N x PTyElementVT" MVT::Vector type.
2649 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002650 DAG.getConstant(NumElems, MVT::i32),
2651 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002652 } else {
2653 abort();
2654 }
2655 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002656 unsigned AssertOp = RetTy->isSigned() ?
2657 ISD::AssertSext : ISD::AssertZext;
2658 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2659 DAG.getValueType(VT));
2660 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2661 } else {
2662 assert(MVT::isFloatingPoint(VT));
2663 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2664 }
2665 }
2666 } else if (RetTys.size() == 3) {
2667 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2668 Res.getValue(0), Res.getValue(1));
2669
2670 } else {
2671 assert(0 && "Case not handled yet!");
2672 }
2673 }
2674
2675 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2676}
2677
2678
2679
Chris Lattner58cfd792005-01-09 00:00:49 +00002680// It is always conservatively correct for llvm.returnaddress and
2681// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002682//
2683// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2684// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002685std::pair<SDOperand, SDOperand>
2686TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2687 unsigned Depth, SelectionDAG &DAG) {
2688 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002689}
2690
Chris Lattner29dcc712005-05-14 05:50:48 +00002691SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002692 assert(0 && "LowerOperation not implemented for this target!");
2693 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002694 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002695}
2696
Nate Begeman595ec732006-01-28 03:14:31 +00002697SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2698 SelectionDAG &DAG) {
2699 assert(0 && "CustomPromoteOperation not implemented for this target!");
2700 abort();
2701 return SDOperand();
2702}
2703
Chris Lattner58cfd792005-01-09 00:00:49 +00002704void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2705 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2706 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002707 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002708 setValue(&I, Result.first);
2709 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002710}
2711
Evan Cheng6781b6e2006-02-15 21:59:04 +00002712/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002713/// operand.
2714static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002715 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002716 MVT::ValueType CurVT = VT;
2717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2718 uint64_t Val = C->getValue() & 255;
2719 unsigned Shift = 8;
2720 while (CurVT != MVT::i8) {
2721 Val = (Val << Shift) | Val;
2722 Shift <<= 1;
2723 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002724 }
2725 return DAG.getConstant(Val, VT);
2726 } else {
2727 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2728 unsigned Shift = 8;
2729 while (CurVT != MVT::i8) {
2730 Value =
2731 DAG.getNode(ISD::OR, VT,
2732 DAG.getNode(ISD::SHL, VT, Value,
2733 DAG.getConstant(Shift, MVT::i8)), Value);
2734 Shift <<= 1;
2735 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002736 }
2737
2738 return Value;
2739 }
2740}
2741
Evan Cheng6781b6e2006-02-15 21:59:04 +00002742/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2743/// used when a memcpy is turned into a memset when the source is a constant
2744/// string ptr.
2745static SDOperand getMemsetStringVal(MVT::ValueType VT,
2746 SelectionDAG &DAG, TargetLowering &TLI,
2747 std::string &Str, unsigned Offset) {
2748 MVT::ValueType CurVT = VT;
2749 uint64_t Val = 0;
2750 unsigned MSB = getSizeInBits(VT) / 8;
2751 if (TLI.isLittleEndian())
2752 Offset = Offset + MSB - 1;
2753 for (unsigned i = 0; i != MSB; ++i) {
2754 Val = (Val << 8) | Str[Offset];
2755 Offset += TLI.isLittleEndian() ? -1 : 1;
2756 }
2757 return DAG.getConstant(Val, VT);
2758}
2759
Evan Cheng81fcea82006-02-14 08:22:34 +00002760/// getMemBasePlusOffset - Returns base and offset node for the
2761static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2762 SelectionDAG &DAG, TargetLowering &TLI) {
2763 MVT::ValueType VT = Base.getValueType();
2764 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2765}
2766
Evan Chengdb2a7a72006-02-14 20:12:38 +00002767/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002768/// to replace the memset / memcpy is below the threshold. It also returns the
2769/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002770static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2771 unsigned Limit, uint64_t Size,
2772 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002773 MVT::ValueType VT;
2774
2775 if (TLI.allowsUnalignedMemoryAccesses()) {
2776 VT = MVT::i64;
2777 } else {
2778 switch (Align & 7) {
2779 case 0:
2780 VT = MVT::i64;
2781 break;
2782 case 4:
2783 VT = MVT::i32;
2784 break;
2785 case 2:
2786 VT = MVT::i16;
2787 break;
2788 default:
2789 VT = MVT::i8;
2790 break;
2791 }
2792 }
2793
Evan Chengd5026102006-02-14 09:11:59 +00002794 MVT::ValueType LVT = MVT::i64;
2795 while (!TLI.isTypeLegal(LVT))
2796 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2797 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002798
Evan Chengd5026102006-02-14 09:11:59 +00002799 if (VT > LVT)
2800 VT = LVT;
2801
Evan Cheng04514992006-02-14 23:05:54 +00002802 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002803 while (Size != 0) {
2804 unsigned VTSize = getSizeInBits(VT) / 8;
2805 while (VTSize > Size) {
2806 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002807 VTSize >>= 1;
2808 }
Evan Chengd5026102006-02-14 09:11:59 +00002809 assert(MVT::isInteger(VT));
2810
2811 if (++NumMemOps > Limit)
2812 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002813 MemOps.push_back(VT);
2814 Size -= VTSize;
2815 }
Evan Chengd5026102006-02-14 09:11:59 +00002816
2817 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002818}
2819
Chris Lattner875def92005-01-11 05:56:49 +00002820void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002821 SDOperand Op1 = getValue(I.getOperand(1));
2822 SDOperand Op2 = getValue(I.getOperand(2));
2823 SDOperand Op3 = getValue(I.getOperand(3));
2824 SDOperand Op4 = getValue(I.getOperand(4));
2825 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2826 if (Align == 0) Align = 1;
2827
2828 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2829 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002830
2831 // Expand memset / memcpy to a series of load / store ops
2832 // if the size operand falls below a certain threshold.
2833 std::vector<SDOperand> OutChains;
2834 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002835 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002836 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002837 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2838 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002839 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002840 unsigned Offset = 0;
2841 for (unsigned i = 0; i < NumMemOps; i++) {
2842 MVT::ValueType VT = MemOps[i];
2843 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002844 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00002845 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2846 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002847 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2848 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00002849 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002850 Offset += VTSize;
2851 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002852 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002853 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002854 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002855 case ISD::MEMCPY: {
2856 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2857 Size->getValue(), Align, TLI)) {
2858 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002859 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002860 GlobalAddressSDNode *G = NULL;
2861 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002862 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002863
2864 if (Op2.getOpcode() == ISD::GlobalAddress)
2865 G = cast<GlobalAddressSDNode>(Op2);
2866 else if (Op2.getOpcode() == ISD::ADD &&
2867 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2868 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2869 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002870 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002871 }
2872 if (G) {
2873 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002874 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002875 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002876 if (!Str.empty()) {
2877 CopyFromStr = true;
2878 SrcOff += SrcDelta;
2879 }
2880 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002881 }
2882
Evan Chenge2038bd2006-02-15 01:54:51 +00002883 for (unsigned i = 0; i < NumMemOps; i++) {
2884 MVT::ValueType VT = MemOps[i];
2885 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002886 SDOperand Value, Chain, Store;
2887
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002888 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002889 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2890 Chain = getRoot();
2891 Store =
2892 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2893 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2894 DAG.getSrcValue(I.getOperand(1), DstOff));
2895 } else {
2896 Value = DAG.getLoad(VT, getRoot(),
2897 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2898 DAG.getSrcValue(I.getOperand(2), SrcOff));
2899 Chain = Value.getValue(1);
2900 Store =
2901 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2902 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2903 DAG.getSrcValue(I.getOperand(1), DstOff));
2904 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002905 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002906 SrcOff += VTSize;
2907 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002908 }
2909 }
2910 break;
2911 }
2912 }
2913
2914 if (!OutChains.empty()) {
2915 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2916 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002917 }
2918 }
2919
Chris Lattner875def92005-01-11 05:56:49 +00002920 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00002921 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002922 Ops.push_back(Op1);
2923 Ops.push_back(Op2);
2924 Ops.push_back(Op3);
2925 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002926 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002927}
2928
Chris Lattner875def92005-01-11 05:56:49 +00002929//===----------------------------------------------------------------------===//
2930// SelectionDAGISel code
2931//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002932
2933unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2934 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2935}
2936
Chris Lattnerc9950c12005-08-17 06:37:43 +00002937void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002938 // FIXME: we only modify the CFG to split critical edges. This
2939 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002940}
Chris Lattner7a60d912005-01-07 07:47:53 +00002941
Chris Lattner35397782005-12-05 07:10:48 +00002942
Chris Lattner3e3f2c62006-05-05 21:17:49 +00002943/// OptimizeNoopCopyExpression - We have determined that the specified cast
2944/// instruction is a noop copy (e.g. it's casting from one pointer type to
2945/// another, int->uint, or int->sbyte on PPC.
2946///
2947/// Return true if any changes are made.
2948static bool OptimizeNoopCopyExpression(CastInst *CI) {
2949 BasicBlock *DefBB = CI->getParent();
2950
2951 /// InsertedCasts - Only insert a cast in each block once.
2952 std::map<BasicBlock*, CastInst*> InsertedCasts;
2953
2954 bool MadeChange = false;
2955 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2956 UI != E; ) {
2957 Use &TheUse = UI.getUse();
2958 Instruction *User = cast<Instruction>(*UI);
2959
2960 // Figure out which BB this cast is used in. For PHI's this is the
2961 // appropriate predecessor block.
2962 BasicBlock *UserBB = User->getParent();
2963 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2964 unsigned OpVal = UI.getOperandNo()/2;
2965 UserBB = PN->getIncomingBlock(OpVal);
2966 }
2967
2968 // Preincrement use iterator so we don't invalidate it.
2969 ++UI;
2970
2971 // If this user is in the same block as the cast, don't change the cast.
2972 if (UserBB == DefBB) continue;
2973
2974 // If we have already inserted a cast into this block, use it.
2975 CastInst *&InsertedCast = InsertedCasts[UserBB];
2976
2977 if (!InsertedCast) {
2978 BasicBlock::iterator InsertPt = UserBB->begin();
2979 while (isa<PHINode>(InsertPt)) ++InsertPt;
2980
2981 InsertedCast =
2982 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2983 MadeChange = true;
2984 }
2985
2986 // Replace a use of the cast with a use of the new casat.
2987 TheUse = InsertedCast;
2988 }
2989
2990 // If we removed all uses, nuke the cast.
2991 if (CI->use_empty())
2992 CI->eraseFromParent();
2993
2994 return MadeChange;
2995}
2996
Chris Lattner35397782005-12-05 07:10:48 +00002997/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2998/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00002999static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3000 Instruction *GEPI, Value *Ptr,
3001 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003002 if (V) return V; // Already computed.
3003
3004 BasicBlock::iterator InsertPt;
3005 if (BB == GEPI->getParent()) {
3006 // If insert into the GEP's block, insert right after the GEP.
3007 InsertPt = GEPI;
3008 ++InsertPt;
3009 } else {
3010 // Otherwise, insert at the top of BB, after any PHI nodes
3011 InsertPt = BB->begin();
3012 while (isa<PHINode>(InsertPt)) ++InsertPt;
3013 }
3014
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003015 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3016 // BB so that there is only one value live across basic blocks (the cast
3017 // operand).
3018 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3019 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3020 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3021
Chris Lattner35397782005-12-05 07:10:48 +00003022 // Add the offset, cast it to the right type.
3023 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003024 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003025}
3026
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003027/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3028/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3029/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3030/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3031/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3032/// the constant add into a load or store instruction. Additionally, if a user
3033/// is a pointer-pointer cast, we look through it to find its users.
3034static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3035 Constant *PtrOffset, BasicBlock *DefBB,
3036 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003037 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003038 while (!RepPtr->use_empty()) {
3039 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003040
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003041 // If the user is a Pointer-Pointer cast, recurse.
3042 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3043 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003044
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003045 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3046 // could invalidate an iterator.
3047 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3048 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003049 }
3050
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003051 // If this is a load of the pointer, or a store through the pointer, emit
3052 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003053 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003054 if (isa<LoadInst>(User) ||
3055 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3056 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3057 User->getParent(), GEPI,
3058 Ptr, PtrOffset);
3059 } else {
3060 // If this use is not foldable into the addressing mode, use a version
3061 // emitted in the GEP block.
3062 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3063 Ptr, PtrOffset);
3064 }
3065
Chris Lattner21cd9902006-05-06 09:10:37 +00003066 if (GEPI->getType() != RepPtr->getType()) {
3067 BasicBlock::iterator IP = NewVal;
3068 ++IP;
3069 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3070 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003071 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003072 }
3073}
Chris Lattner35397782005-12-05 07:10:48 +00003074
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003075
Chris Lattner35397782005-12-05 07:10:48 +00003076/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3077/// selection, we want to be a bit careful about some things. In particular, if
3078/// we have a GEP instruction that is used in a different block than it is
3079/// defined, the addressing expression of the GEP cannot be folded into loads or
3080/// stores that use it. In this case, decompose the GEP and move constant
3081/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003082static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003083 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003084 // If this GEP is only used inside the block it is defined in, there is no
3085 // need to rewrite it.
3086 bool isUsedOutsideDefBB = false;
3087 BasicBlock *DefBB = GEPI->getParent();
3088 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3089 UI != E; ++UI) {
3090 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3091 isUsedOutsideDefBB = true;
3092 break;
3093 }
3094 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003095 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003096
3097 // If this GEP has no non-zero constant indices, there is nothing we can do,
3098 // ignore it.
3099 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003100 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003101 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3102 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003103 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Chris Lattner35397782005-12-05 07:10:48 +00003104 if (CI->getRawValue()) {
3105 hasConstantIndex = true;
3106 break;
3107 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003108 } else {
3109 hasVariableIndex = true;
3110 }
Chris Lattner35397782005-12-05 07:10:48 +00003111 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003112
3113 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3114 if (!hasConstantIndex && !hasVariableIndex) {
3115 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3116 GEPI->getName(), GEPI);
3117 GEPI->replaceAllUsesWith(NC);
3118 GEPI->eraseFromParent();
3119 return true;
3120 }
3121
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003122 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003123 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3124 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003125
3126 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3127 // constant offset (which we now know is non-zero) and deal with it later.
3128 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003129 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003130 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3131 const Type *Ty = GEPI->getOperand(0)->getType();
3132
3133 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3134 E = GEPI->op_end(); OI != E; ++OI) {
3135 Value *Idx = *OI;
3136 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3137 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
3138 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003139 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003140 Ty = StTy->getElementType(Field);
3141 } else {
3142 Ty = cast<SequentialType>(Ty)->getElementType();
3143
3144 // Handle constant subscripts.
3145 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3146 if (CI->getRawValue() == 0) continue;
3147
3148 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
Owen Anderson20a631f2006-05-03 01:29:57 +00003149 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
Chris Lattner35397782005-12-05 07:10:48 +00003150 else
Owen Anderson20a631f2006-05-03 01:29:57 +00003151 ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
Chris Lattner35397782005-12-05 07:10:48 +00003152 continue;
3153 }
3154
3155 // Ptr = Ptr + Idx * ElementSize;
3156
3157 // Cast Idx to UIntPtrTy if needed.
3158 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3159
Owen Anderson20a631f2006-05-03 01:29:57 +00003160 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003161 // Mask off bits that should not be set.
3162 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3163 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
3164
3165 // Multiply by the element size and add to the base.
3166 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3167 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3168 }
3169 }
3170
3171 // Make sure that the offset fits in uintptr_t.
3172 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3173 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
3174
3175 // Okay, we have now emitted all of the variable index parts to the BB that
3176 // the GEP is defined in. Loop over all of the using instructions, inserting
3177 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003178 // instruction to use the newly computed value, making GEPI dead. When the
3179 // user is a load or store instruction address, we emit the add into the user
3180 // block, otherwise we use a canonical version right next to the gep (these
3181 // won't be foldable as addresses, so we might as well share the computation).
3182
Chris Lattner21cd9902006-05-06 09:10:37 +00003183 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003184 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003185
3186 // Finally, the GEP is dead, remove it.
3187 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003188
3189 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003190}
3191
Chris Lattner7a60d912005-01-07 07:47:53 +00003192bool SelectionDAGISel::runOnFunction(Function &Fn) {
3193 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3194 RegMap = MF.getSSARegMap();
3195 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3196
Chris Lattner35397782005-12-05 07:10:48 +00003197 // First, split all critical edges for PHI nodes with incoming values that are
3198 // constants, this way the load of the constant into a vreg will not be placed
3199 // into MBBs that are used some other way.
3200 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003201 // In this pass we also look for GEP and cast instructions that are used
3202 // across basic blocks and rewrite them to improve basic-block-at-a-time
3203 // selection.
3204 //
Chris Lattner35397782005-12-05 07:10:48 +00003205 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003206 bool MadeChange = true;
3207 while (MadeChange) {
3208 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003209 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3210 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00003211 BasicBlock::iterator BBI;
3212 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00003213 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3214 if (isa<Constant>(PN->getIncomingValue(i)))
3215 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00003216
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003217 for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3218 Instruction *I = BBI++;
3219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003220 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003221 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3222 // If this is a noop copy, sink it into user blocks to reduce the number
3223 // of virtual registers that must be created and coallesced.
3224 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3225 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3226
3227 // This is an fp<->int conversion?
3228 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3229 continue;
3230
3231 // If this is an extension, it will be a zero or sign extension, which
3232 // isn't a noop.
3233 if (SrcVT < DstVT) continue;
3234
3235 // If these values will be promoted, find out what they will be promoted
3236 // to. This helps us consider truncates on PPC as noop copies when they
3237 // are.
3238 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3239 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3240 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3241 DstVT = TLI.getTypeToTransformTo(DstVT);
3242
3243 // If, after promotion, these are the same types, this is a noop copy.
3244 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003245 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003246 }
3247 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003248 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003249 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003250
Chris Lattner7a60d912005-01-07 07:47:53 +00003251 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3252
3253 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3254 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003255
Chris Lattner7a60d912005-01-07 07:47:53 +00003256 return true;
3257}
3258
3259
Chris Lattner718b5c22005-01-13 17:59:43 +00003260SDOperand SelectionDAGISel::
3261CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00003262 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003263 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003264 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003265 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003266
3267 // If this type is not legal, we must make sure to not create an invalid
3268 // register use.
3269 MVT::ValueType SrcVT = Op.getValueType();
3270 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3271 SelectionDAG &DAG = SDL.DAG;
3272 if (SrcVT == DestVT) {
3273 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003274 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003275 // Handle copies from generic vectors to registers.
3276 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3277 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3278 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003279
Chris Lattner5fe1f542006-03-31 02:06:56 +00003280 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3281 // MVT::Vector type.
3282 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3283 DAG.getConstant(NE, MVT::i32),
3284 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003285
Chris Lattner5fe1f542006-03-31 02:06:56 +00003286 // Loop over all of the elements of the resultant vector,
3287 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3288 // copying them into output registers.
3289 std::vector<SDOperand> OutChains;
3290 SDOperand Root = SDL.getRoot();
3291 for (unsigned i = 0; i != NE; ++i) {
3292 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003293 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003294 if (PTyElementVT == PTyLegalElementVT) {
3295 // Elements are legal.
3296 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3297 } else if (PTyLegalElementVT > PTyElementVT) {
3298 // Elements are promoted.
3299 if (MVT::isFloatingPoint(PTyLegalElementVT))
3300 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3301 else
3302 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3303 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3304 } else {
3305 // Elements are expanded.
3306 // The src value is expanded into multiple registers.
3307 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003308 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003309 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003310 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003311 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3312 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3313 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003314 }
Chris Lattner5fe1f542006-03-31 02:06:56 +00003315 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner33182322005-08-16 21:55:35 +00003316 } else if (SrcVT < DestVT) {
3317 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003318 if (MVT::isFloatingPoint(SrcVT))
3319 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3320 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003321 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003322 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3323 } else {
3324 // The src value is expanded into multiple registers.
3325 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003326 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003327 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003328 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003329 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3330 return DAG.getCopyToReg(Op, Reg+1, Hi);
3331 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003332}
3333
Chris Lattner16f64df2005-01-17 17:15:02 +00003334void SelectionDAGISel::
3335LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3336 std::vector<SDOperand> &UnorderedChains) {
3337 // If this is the entry block, emit arguments.
3338 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003339 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003340 SDOperand OldRoot = SDL.DAG.getRoot();
3341 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003342
Chris Lattner6871b232005-10-30 19:42:35 +00003343 unsigned a = 0;
3344 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3345 AI != E; ++AI, ++a)
3346 if (!AI->use_empty()) {
3347 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003348
Chris Lattner6871b232005-10-30 19:42:35 +00003349 // If this argument is live outside of the entry block, insert a copy from
3350 // whereever we got it to the vreg that other BB's will reference it as.
3351 if (FuncInfo.ValueMap.count(AI)) {
3352 SDOperand Copy =
3353 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3354 UnorderedChains.push_back(Copy);
3355 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003356 }
Chris Lattner6871b232005-10-30 19:42:35 +00003357
Chris Lattner6871b232005-10-30 19:42:35 +00003358 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003359 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003360 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003361}
3362
Chris Lattner7a60d912005-01-07 07:47:53 +00003363void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3364 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003365 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003366 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003367
3368 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003369
Chris Lattner6871b232005-10-30 19:42:35 +00003370 // Lower any arguments needed in this block if this is the entry block.
3371 if (LLVMBB == &LLVMBB->getParent()->front())
3372 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003373
3374 BB = FuncInfo.MBBMap[LLVMBB];
3375 SDL.setCurrentBasicBlock(BB);
3376
3377 // Lower all of the non-terminator instructions.
3378 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3379 I != E; ++I)
3380 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003381
Chris Lattner7a60d912005-01-07 07:47:53 +00003382 // Ensure that all instructions which are used outside of their defining
3383 // blocks are available as virtual registers.
3384 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003385 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003386 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003387 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003388 UnorderedChains.push_back(
3389 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003390 }
3391
3392 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3393 // ensure constants are generated when needed. Remember the virtual registers
3394 // that need to be added to the Machine PHI nodes as input. We cannot just
3395 // directly add them, because expansion might result in multiple MBB's for one
3396 // BB. As such, the start of the BB might correspond to a different MBB than
3397 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003398 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003399
3400 // Emit constants only once even if used by multiple PHI nodes.
3401 std::map<Constant*, unsigned> ConstantsOut;
3402
3403 // Check successor nodes PHI nodes that expect a constant to be available from
3404 // this block.
3405 TerminatorInst *TI = LLVMBB->getTerminator();
3406 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3407 BasicBlock *SuccBB = TI->getSuccessor(succ);
3408 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3409 PHINode *PN;
3410
3411 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3412 // nodes and Machine PHI nodes, but the incoming operands have not been
3413 // emitted yet.
3414 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003415 (PN = dyn_cast<PHINode>(I)); ++I)
3416 if (!PN->use_empty()) {
3417 unsigned Reg;
3418 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3419 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3420 unsigned &RegOut = ConstantsOut[C];
3421 if (RegOut == 0) {
3422 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003423 UnorderedChains.push_back(
3424 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003425 }
3426 Reg = RegOut;
3427 } else {
3428 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003429 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003430 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003431 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3432 "Didn't codegen value into a register!??");
3433 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003434 UnorderedChains.push_back(
3435 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003436 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003437 }
Misha Brukman835702a2005-04-21 22:36:52 +00003438
Chris Lattner8ea875f2005-01-07 21:34:19 +00003439 // Remember that this register needs to added to the machine PHI node as
3440 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003441 MVT::ValueType VT = TLI.getValueType(PN->getType());
3442 unsigned NumElements;
3443 if (VT != MVT::Vector)
3444 NumElements = TLI.getNumElements(VT);
3445 else {
3446 MVT::ValueType VT1,VT2;
3447 NumElements =
3448 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3449 VT1, VT2);
3450 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003451 for (unsigned i = 0, e = NumElements; i != e; ++i)
3452 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003453 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003454 }
3455 ConstantsOut.clear();
3456
Chris Lattner718b5c22005-01-13 17:59:43 +00003457 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003458 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003459 SDOperand Root = SDL.getRoot();
3460 if (Root.getOpcode() != ISD::EntryToken) {
3461 unsigned i = 0, e = UnorderedChains.size();
3462 for (; i != e; ++i) {
3463 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3464 if (UnorderedChains[i].Val->getOperand(0) == Root)
3465 break; // Don't add the root if we already indirectly depend on it.
3466 }
3467
3468 if (i == e)
3469 UnorderedChains.push_back(Root);
3470 }
Chris Lattner718b5c22005-01-13 17:59:43 +00003471 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3472 }
3473
Chris Lattner7a60d912005-01-07 07:47:53 +00003474 // Lower the terminator after the copies are emitted.
3475 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003476
Nate Begemaned728c12006-03-27 01:32:24 +00003477 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003478 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003479 SwitchCases.clear();
3480 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003481 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003482
Chris Lattner4108bb02005-01-17 19:43:36 +00003483 // Make sure the root of the DAG is up-to-date.
3484 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003485}
3486
Nate Begemaned728c12006-03-27 01:32:24 +00003487void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003488 // Run the DAG combiner in pre-legalize mode.
3489 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00003490
Chris Lattner7a60d912005-01-07 07:47:53 +00003491 DEBUG(std::cerr << "Lowered selection DAG:\n");
3492 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003493
Chris Lattner7a60d912005-01-07 07:47:53 +00003494 // Second step, hack on the DAG until it only uses operations and types that
3495 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003496 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003497
Chris Lattner7a60d912005-01-07 07:47:53 +00003498 DEBUG(std::cerr << "Legalized selection DAG:\n");
3499 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003500
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003501 // Run the DAG combiner in post-legalize mode.
3502 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00003503
Evan Cheng739a6a42006-01-21 02:32:06 +00003504 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003505
Chris Lattner5ca31d92005-03-30 01:10:47 +00003506 // Third, instruction select all of the operations to machine code, adding the
3507 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003508 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003509
Chris Lattner7a60d912005-01-07 07:47:53 +00003510 DEBUG(std::cerr << "Selected machine code:\n");
3511 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003512}
Chris Lattner7a60d912005-01-07 07:47:53 +00003513
Nate Begemaned728c12006-03-27 01:32:24 +00003514void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3515 FunctionLoweringInfo &FuncInfo) {
3516 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3517 {
3518 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3519 CurDAG = &DAG;
3520
3521 // First step, lower LLVM code to some DAG. This DAG may use operations and
3522 // types that are not supported by the target.
3523 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3524
3525 // Second step, emit the lowered DAG as machine code.
3526 CodeGenAndEmitDAG(DAG);
3527 }
3528
Chris Lattner5ca31d92005-03-30 01:10:47 +00003529 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003530 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003531 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003532 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3533 MachineInstr *PHI = PHINodesToUpdate[i].first;
3534 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3535 "This is not a machine PHI node that we are updating!");
3536 PHI->addRegOperand(PHINodesToUpdate[i].second);
3537 PHI->addMachineBasicBlockOperand(BB);
3538 }
3539 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003540 }
Nate Begemaned728c12006-03-27 01:32:24 +00003541
Nate Begeman866b4b42006-04-23 06:26:20 +00003542 // If the JumpTable record is filled in, then we need to emit a jump table.
3543 // Updating the PHI nodes is tricky in this case, since we need to determine
3544 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003545 if (JT.Reg) {
3546 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3547 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3548 CurDAG = &SDAG;
3549 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003550 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003551 // Set the current basic block to the mbb we wish to insert the code into
3552 BB = JT.MBB;
3553 SDL.setCurrentBasicBlock(BB);
3554 // Emit the code
3555 SDL.visitJumpTable(JT);
3556 SDAG.setRoot(SDL.getRoot());
3557 CodeGenAndEmitDAG(SDAG);
3558 // Update PHI Nodes
3559 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3560 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3561 MachineBasicBlock *PHIBB = PHI->getParent();
3562 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3563 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003564 if (PHIBB == JT.Default) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003565 PHI->addRegOperand(PHINodesToUpdate[pi].second);
Nate Begemandf488392006-05-03 03:48:02 +00003566 PHI->addMachineBasicBlockOperand(RangeBB);
3567 }
3568 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3569 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3570 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003571 }
3572 }
3573 return;
3574 }
3575
Nate Begemaned728c12006-03-27 01:32:24 +00003576 // If we generated any switch lowering information, build and codegen any
3577 // additional DAGs necessary.
3578 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3579 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3580 CurDAG = &SDAG;
3581 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3582 // Set the current basic block to the mbb we wish to insert the code into
3583 BB = SwitchCases[i].ThisBB;
3584 SDL.setCurrentBasicBlock(BB);
3585 // Emit the code
3586 SDL.visitSwitchCase(SwitchCases[i]);
3587 SDAG.setRoot(SDL.getRoot());
3588 CodeGenAndEmitDAG(SDAG);
3589 // Iterate over the phi nodes, if there is a phi node in a successor of this
3590 // block (for instance, the default block), then add a pair of operands to
3591 // the phi node for this block, as if we were coming from the original
3592 // BB before switch expansion.
3593 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3594 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3595 MachineBasicBlock *PHIBB = PHI->getParent();
3596 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3597 "This is not a machine PHI node that we are updating!");
3598 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3599 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3600 PHI->addMachineBasicBlockOperand(BB);
3601 }
3602 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00003603 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003604}
Evan Cheng739a6a42006-01-21 02:32:06 +00003605
Jim Laskey95eda5b2006-08-01 14:21:23 +00003606
Evan Cheng739a6a42006-01-21 02:32:06 +00003607//===----------------------------------------------------------------------===//
3608/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3609/// target node in the graph.
3610void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3611 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003612
Jim Laskey95eda5b2006-08-01 14:21:23 +00003613 static RegisterScheduler::FunctionPassCtor Ctor =
Jim Laskey03593f72006-08-01 18:29:48 +00003614 RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003615
3616 if (!Ctor) {
3617 if (std::string("default") == std::string(ISHeuristic)) {
3618 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3619 Ctor = RegisterScheduler::FindCtor("list-td");
3620 else {
3621 assert(TLI.getSchedulingPreference() ==
Chris Lattnerb21d3bf2006-04-21 17:16:16 +00003622 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Jim Laskey95eda5b2006-08-01 14:21:23 +00003623 Ctor = RegisterScheduler::FindCtor("list-burr");
3624 }
3625
3626 assert(Ctor && "Default instruction scheduler not present");
3627 if (!Ctor) Ctor = RegisterScheduler::FindCtor("none");
3628 } else {
3629 Ctor = RegisterScheduler::FindCtor(ISHeuristic);
Chris Lattnerb21d3bf2006-04-21 17:16:16 +00003630 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003631
Jim Laskey03593f72006-08-01 18:29:48 +00003632 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003633 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003634
3635 assert(Ctor && "No instruction scheduler found");
Jim Laskey03593f72006-08-01 18:29:48 +00003636 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003637 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003638 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003639}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003640
Chris Lattner47639db2006-03-06 00:22:00 +00003641
Jim Laskey03593f72006-08-01 18:29:48 +00003642HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3643 return new HazardRecognizer();
3644}
3645
3646
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003647/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3648/// by tblgen. Others should not call it.
3649void SelectionDAGISel::
3650SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3651 std::vector<SDOperand> InOps;
3652 std::swap(InOps, Ops);
3653
3654 Ops.push_back(InOps[0]); // input chain.
3655 Ops.push_back(InOps[1]); // input asm string.
3656
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003657 unsigned i = 2, e = InOps.size();
3658 if (InOps[e-1].getValueType() == MVT::Flag)
3659 --e; // Don't process a flag operand if it is here.
3660
3661 while (i != e) {
3662 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3663 if ((Flags & 7) != 4 /*MEM*/) {
3664 // Just skip over this operand, copying the operands verbatim.
3665 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3666 i += (Flags >> 3) + 1;
3667 } else {
3668 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3669 // Otherwise, this is a memory operand. Ask the target to select it.
3670 std::vector<SDOperand> SelOps;
3671 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3672 std::cerr << "Could not match memory address. Inline asm failure!\n";
3673 exit(1);
3674 }
3675
3676 // Add this to the output node.
3677 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3678 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3679 i += 2;
3680 }
3681 }
3682
3683 // Add the flag input back if present.
3684 if (e != InOps.size())
3685 Ops.push_back(InOps.back());
3686}