blob: 238ed97843542faec4d0fb355136a9d49c9840a9 [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.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 Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.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
Jim Laskey29e635d2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Misha Brukman835702a2005-04-21 22:36:52 +0000187
Chris Lattner49409cb2006-03-16 19:51:18 +0000188 unsigned CreateRegForValue(const Value *V);
189
Chris Lattner7a60d912005-01-07 07:47:53 +0000190 unsigned InitializeRegForValue(const Value *V) {
191 unsigned &R = ValueMap[V];
192 assert(R == 0 && "Already initialized this value register!");
193 return R = CreateRegForValue(V);
194 }
195 };
196}
197
198/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000199/// PHI nodes or outside of the basic block that defines it, or used by a
200/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000201static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
202 if (isa<PHINode>(I)) return true;
203 BasicBlock *BB = I->getParent();
204 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000205 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
206 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 return true;
208 return false;
209}
210
Chris Lattner6871b232005-10-30 19:42:35 +0000211/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000212/// entry block, return true. This includes arguments used by switches, since
213/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000214static bool isOnlyUsedInEntryBlock(Argument *A) {
215 BasicBlock *Entry = A->getParent()->begin();
216 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000217 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000218 return false; // Use not in entry block.
219 return true;
220}
221
Chris Lattner7a60d912005-01-07 07:47:53 +0000222FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000223 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
225
Chris Lattner6871b232005-10-30 19:42:35 +0000226 // Create a vreg for each argument register that is not dead and is used
227 // outside of the entry block for the function.
228 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
229 AI != E; ++AI)
230 if (!isOnlyUsedInEntryBlock(AI))
231 InitializeRegForValue(AI);
232
Chris Lattner7a60d912005-01-07 07:47:53 +0000233 // Initialize the mapping of values to registers. This is only set up for
234 // instruction values that are used outside of the block that defines
235 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000236 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
238 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000239 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000241 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000242 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000243 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000244 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000245
Reid Spencere0fc4df2006-10-20 07:07:24 +0000246 // If the alignment of the value is smaller than the size of the
247 // value, and if the size of the value is particularly small
248 // (<= 8 bytes), round up to the size of the value for potentially
249 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000250 //
251 // FIXME: This could be made better with a preferred alignment hook in
252 // TargetData. It serves primarily to 8-byte align doubles for X86.
253 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000254 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000255 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000257 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 }
259
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (; BB != EB; ++BB)
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000262 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
263 if (!isa<AllocaInst>(I) ||
264 !StaticAllocaMap.count(cast<AllocaInst>(I)))
265 InitializeRegForValue(I);
266
267 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
268 // also creates the initial PHI MachineInstrs, though none of the input
269 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000270 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000271 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
272 MBBMap[BB] = MBB;
273 MF.getBasicBlockList().push_back(MBB);
274
275 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
276 // appropriate.
277 PHINode *PN;
278 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000279 (PN = dyn_cast<PHINode>(I)); ++I)
280 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000281 MVT::ValueType VT = TLI.getValueType(PN->getType());
282 unsigned NumElements;
283 if (VT != MVT::Vector)
284 NumElements = TLI.getNumElements(VT);
285 else {
286 MVT::ValueType VT1,VT2;
287 NumElements =
288 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
289 VT1, VT2);
290 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000291 unsigned PHIReg = ValueMap[PN];
292 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
293 for (unsigned i = 0; i != NumElements; ++i)
294 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
295 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000296 }
297}
298
Chris Lattner49409cb2006-03-16 19:51:18 +0000299/// CreateRegForValue - Allocate the appropriate number of virtual registers of
300/// the correctly promoted or expanded types. Assign these registers
301/// consecutive vreg numbers and return the first assigned number.
302unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
303 MVT::ValueType VT = TLI.getValueType(V->getType());
304
305 // The number of multiples of registers that we need, to, e.g., split up
306 // a <2 x int64> -> 4 x i32 registers.
307 unsigned NumVectorRegs = 1;
308
309 // If this is a packed type, figure out what type it will decompose into
310 // and how many of the elements it will use.
311 if (VT == MVT::Vector) {
312 const PackedType *PTy = cast<PackedType>(V->getType());
313 unsigned NumElts = PTy->getNumElements();
314 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
315
316 // Divide the input until we get to a supported size. This will always
317 // end with a scalar if the target doesn't support vectors.
318 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
319 NumElts >>= 1;
320 NumVectorRegs <<= 1;
321 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000322 if (NumElts == 1)
323 VT = EltTy;
324 else
325 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000326 }
327
328 // The common case is that we will only create one register for this
329 // value. If we have that case, create and return the virtual register.
330 unsigned NV = TLI.getNumElements(VT);
331 if (NV == 1) {
332 // If we are promoting this value, pick the next largest supported type.
333 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
334 unsigned Reg = MakeReg(PromotedType);
335 // If this is a vector of supported or promoted types (e.g. 4 x i16),
336 // create all of the registers.
337 for (unsigned i = 1; i != NumVectorRegs; ++i)
338 MakeReg(PromotedType);
339 return Reg;
340 }
341
342 // If this value is represented with multiple target registers, make sure
343 // to create enough consecutive registers of the right (smaller) type.
344 unsigned NT = VT-1; // Find the type to use.
345 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
346 --NT;
347
348 unsigned R = MakeReg((MVT::ValueType)NT);
349 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
350 MakeReg((MVT::ValueType)NT);
351 return R;
352}
Chris Lattner7a60d912005-01-07 07:47:53 +0000353
354//===----------------------------------------------------------------------===//
355/// SelectionDAGLowering - This is the common target-independent lowering
356/// implementation that is parameterized by a TargetLowering object.
357/// Also, targets can overload any lowering method.
358///
359namespace llvm {
360class SelectionDAGLowering {
361 MachineBasicBlock *CurMBB;
362
363 std::map<const Value*, SDOperand> NodeMap;
364
Chris Lattner4d9651c2005-01-17 22:19:26 +0000365 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
366 /// them up and then emit token factor nodes when possible. This allows us to
367 /// get simple disambiguation between loads without worrying about alias
368 /// analysis.
369 std::vector<SDOperand> PendingLoads;
370
Nate Begemaned728c12006-03-27 01:32:24 +0000371 /// Case - A pair of values to record the Value for a switch case, and the
372 /// case's target basic block.
373 typedef std::pair<Constant*, MachineBasicBlock*> Case;
374 typedef std::vector<Case>::iterator CaseItr;
375 typedef std::pair<CaseItr, CaseItr> CaseRange;
376
377 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
378 /// of conditional branches.
379 struct CaseRec {
380 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
381 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
382
383 /// CaseBB - The MBB in which to emit the compare and branch
384 MachineBasicBlock *CaseBB;
385 /// LT, GE - If nonzero, we know the current case value must be less-than or
386 /// greater-than-or-equal-to these Constants.
387 Constant *LT;
388 Constant *GE;
389 /// Range - A pair of iterators representing the range of case values to be
390 /// processed at this point in the binary search tree.
391 CaseRange Range;
392 };
393
394 /// The comparison function for sorting Case values.
395 struct CaseCmp {
396 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000397 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
398 if (I1->getType()->isUnsigned())
399 return I1->getZExtValue() <
400 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000401
Reid Spencere0fc4df2006-10-20 07:07:24 +0000402 return cast<const ConstantInt>(C1.first)->getSExtValue() <
403 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000404 }
405 };
406
Chris Lattner7a60d912005-01-07 07:47:53 +0000407public:
408 // TLI - This is information that describes the available target features we
409 // need for lowering. This indicates when operations are unavailable,
410 // implemented with a libcall, etc.
411 TargetLowering &TLI;
412 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000413 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000414
Nate Begemaned728c12006-03-27 01:32:24 +0000415 /// SwitchCases - Vector of CaseBlock structures used to communicate
416 /// SwitchInst code generation information.
417 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000418 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000419
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 /// FuncInfo - Information about the function as a whole.
421 ///
422 FunctionLoweringInfo &FuncInfo;
423
424 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000425 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000426 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000427 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 }
429
Chris Lattner4108bb02005-01-17 19:43:36 +0000430 /// getRoot - Return the current virtual root of the Selection DAG.
431 ///
432 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000433 if (PendingLoads.empty())
434 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000435
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 if (PendingLoads.size() == 1) {
437 SDOperand Root = PendingLoads[0];
438 DAG.setRoot(Root);
439 PendingLoads.clear();
440 return Root;
441 }
442
443 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000444 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
445 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000446 PendingLoads.clear();
447 DAG.setRoot(Root);
448 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000449 }
450
Chris Lattner7a60d912005-01-07 07:47:53 +0000451 void visit(Instruction &I) { visit(I.getOpcode(), I); }
452
453 void visit(unsigned Opcode, User &I) {
454 switch (Opcode) {
455 default: assert(0 && "Unknown instruction type encountered!");
456 abort();
457 // Build the switch statement using the Instruction.def file.
458#define HANDLE_INST(NUM, OPCODE, CLASS) \
459 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
460#include "llvm/Instruction.def"
461 }
462 }
463
464 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
465
Chris Lattner4024c002006-03-15 22:19:46 +0000466 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000467 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000468 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
470 SDOperand getIntPtrConstant(uint64_t Val) {
471 return DAG.getConstant(Val, TLI.getPointerTy());
472 }
473
Chris Lattner8471b152006-03-16 19:57:50 +0000474 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000475
476 const SDOperand &setValue(const Value *V, SDOperand NewN) {
477 SDOperand &N = NodeMap[V];
478 assert(N.Val == 0 && "Already set a value for this node!");
479 return N = NewN;
480 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000481
Chris Lattner6f87d182006-02-22 22:37:12 +0000482 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
483 MVT::ValueType VT,
484 bool OutReg, bool InReg,
485 std::set<unsigned> &OutputRegs,
486 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemaned728c12006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Nate Begemanb2e089c2005-11-19 00:36:38 +0000502 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000503 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000504 void visitAdd(User &I) {
505 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000506 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000507 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000508 void visitMul(User &I) {
509 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000510 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000512 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000513 visitBinary(I,
514 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
515 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 }
517 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000518 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000521 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
522 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
523 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000524 void visitShl(User &I) { visitShift(I, ISD::SHL); }
525 void visitShr(User &I) {
526 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000527 }
528
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000529 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
530 ISD::CondCode FPOpc);
531 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
532 ISD::SETOEQ); }
533 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
534 ISD::SETUNE); }
535 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
536 ISD::SETOLE); }
537 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
538 ISD::SETOGE); }
539 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
540 ISD::SETOLT); }
541 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
542 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
Chris Lattner67271862006-03-29 00:11:43 +0000544 void visitExtractElement(User &I);
545 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000546 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000547
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 void visitGetElementPtr(User &I);
549 void visitCast(User &I);
550 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000551
552 void visitMalloc(MallocInst &I);
553 void visitFree(FreeInst &I);
554 void visitAlloca(AllocaInst &I);
555 void visitLoad(LoadInst &I);
556 void visitStore(StoreInst &I);
557 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
558 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000559 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000560 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000561 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000562
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000564 void visitVAArg(VAArgInst &I);
565 void visitVAEnd(CallInst &I);
566 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000567 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568
Chris Lattner875def92005-01-11 05:56:49 +0000569 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000570
571 void visitUserOp1(Instruction &I) {
572 assert(0 && "UserOp1 should not exist at instruction selection time!");
573 abort();
574 }
575 void visitUserOp2(Instruction &I) {
576 assert(0 && "UserOp2 should not exist at instruction selection time!");
577 abort();
578 }
579};
580} // end namespace llvm
581
Chris Lattner8471b152006-03-16 19:57:50 +0000582SDOperand SelectionDAGLowering::getValue(const Value *V) {
583 SDOperand &N = NodeMap[V];
584 if (N.Val) return N;
585
586 const Type *VTy = V->getType();
587 MVT::ValueType VT = TLI.getValueType(VTy);
588 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
590 visit(CE->getOpcode(), *CE);
591 assert(N.Val && "visit didn't populate the ValueMap!");
592 return N;
593 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
594 return N = DAG.getGlobalAddress(GV, VT);
595 } else if (isa<ConstantPointerNull>(C)) {
596 return N = DAG.getConstant(0, TLI.getPointerTy());
597 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000598 if (!isa<PackedType>(VTy))
599 return N = DAG.getNode(ISD::UNDEF, VT);
600
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000601 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000602 const PackedType *PTy = cast<PackedType>(VTy);
603 unsigned NumElements = PTy->getNumElements();
604 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
605
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000606 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000607 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
608
609 // Create a VConstant node with generic Vector type.
610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
613 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000614 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
615 return N = DAG.getConstantFP(CFP->getValue(), VT);
616 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
617 unsigned NumElements = PTy->getNumElements();
618 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000619
620 // Now that we know the number and type of the elements, push a
621 // Constant or ConstantFP node onto the ops list for each element of
622 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000623 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000624 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000625 for (unsigned i = 0; i != NumElements; ++i)
626 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000627 } else {
628 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
629 SDOperand Op;
630 if (MVT::isFloatingPoint(PVT))
631 Op = DAG.getConstantFP(0, PVT);
632 else
633 Op = DAG.getConstant(0, PVT);
634 Ops.assign(NumElements, Op);
635 }
636
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000637 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000638 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
639 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000640 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000641 } else {
642 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000643 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000644 }
645 }
646
647 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
648 std::map<const AllocaInst*, int>::iterator SI =
649 FuncInfo.StaticAllocaMap.find(AI);
650 if (SI != FuncInfo.StaticAllocaMap.end())
651 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
652 }
653
654 std::map<const Value*, unsigned>::const_iterator VMI =
655 FuncInfo.ValueMap.find(V);
656 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
657
658 unsigned InReg = VMI->second;
659
660 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000661 if (VT != MVT::Vector) {
662 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000663
Chris Lattner5fe1f542006-03-31 02:06:56 +0000664 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
665 if (DestVT < VT) {
666 // Source must be expanded. This input value is actually coming from the
667 // register pair VMI->second and VMI->second+1.
668 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
669 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
670 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000671 if (MVT::isFloatingPoint(VT))
672 N = DAG.getNode(ISD::FP_ROUND, VT, N);
673 else
674 N = DAG.getNode(ISD::TRUNCATE, VT, N);
675 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000676 } else {
677 // Otherwise, if this is a vector, make it available as a generic vector
678 // here.
679 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000680 const PackedType *PTy = cast<PackedType>(VTy);
681 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000682 PTyLegalElementVT);
683
684 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000685 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000686 if (PTyElementVT == PTyLegalElementVT) {
687 // If the value types are legal, just VBUILD the CopyFromReg nodes.
688 for (unsigned i = 0; i != NE; ++i)
689 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
690 PTyElementVT));
691 } else if (PTyElementVT < PTyLegalElementVT) {
692 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
693 for (unsigned i = 0; i != NE; ++i) {
694 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
695 PTyElementVT);
696 if (MVT::isFloatingPoint(PTyElementVT))
697 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
698 else
699 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
700 Ops.push_back(Op);
701 }
702 } else {
703 // If the register was expanded, use BUILD_PAIR.
704 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
705 for (unsigned i = 0; i != NE/2; ++i) {
706 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT);
708 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT);
710 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
711 }
712 }
713
714 Ops.push_back(DAG.getConstant(NE, MVT::i32));
715 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000716 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000717
718 // Finally, use a VBIT_CONVERT to make this available as the appropriate
719 // vector type.
720 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
721 DAG.getConstant(PTy->getNumElements(),
722 MVT::i32),
723 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000724 }
725
726 return N;
727}
728
729
Chris Lattner7a60d912005-01-07 07:47:53 +0000730void SelectionDAGLowering::visitRet(ReturnInst &I) {
731 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000732 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000733 return;
734 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000735 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000736 NewValues.push_back(getRoot());
737 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
738 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000739 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000740
741 // If this is an integer return value, we need to promote it ourselves to
742 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
743 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000744 // FIXME: C calling convention requires the return type to be promoted to
745 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000746 if (MVT::isInteger(RetOp.getValueType()) &&
747 RetOp.getValueType() < MVT::i64) {
748 MVT::ValueType TmpVT;
749 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
750 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
751 else
752 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000753
Evan Chenga2e99532006-05-26 23:09:09 +0000754 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000755 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
756 else
757 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
758 }
759 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000760 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000761 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000762 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
763 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000764}
765
766void SelectionDAGLowering::visitBr(BranchInst &I) {
767 // Update machine-CFG edges.
768 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Nate Begemaned728c12006-03-27 01:32:24 +0000769 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000770
771 // Figure out which block is immediately after the current one.
772 MachineBasicBlock *NextBlock = 0;
773 MachineFunction::iterator BBI = CurMBB;
774 if (++BBI != CurMBB->getParent()->end())
775 NextBlock = BBI;
776
777 if (I.isUnconditional()) {
778 // If this is not a fall-through branch, emit the branch.
779 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000780 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000781 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 } else {
783 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000784 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000785
786 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000787 if (Succ1MBB == NextBlock) {
788 // If the condition is false, fall through. This means we should branch
789 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000790 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000791 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000792 } else if (Succ0MBB == NextBlock) {
793 // If the condition is true, fall through. This means we should branch if
794 // the condition is false to Succ #1. Invert the condition first.
795 SDOperand True = DAG.getConstant(1, Cond.getValueType());
796 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000797 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000798 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000799 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000800 std::vector<SDOperand> Ops;
801 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000802 // If the false case is the current basic block, then this is a self
803 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
804 // adds an extra instruction in the loop. Instead, invert the
805 // condition and emit "Loop: ... br!cond Loop; br Out.
806 if (CurMBB == Succ1MBB) {
807 std::swap(Succ0MBB, Succ1MBB);
808 SDOperand True = DAG.getConstant(1, Cond.getValueType());
809 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
810 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000811 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
812 DAG.getBasicBlock(Succ0MBB));
813 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
814 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000815 }
816 }
817}
818
Nate Begemaned728c12006-03-27 01:32:24 +0000819/// visitSwitchCase - Emits the necessary code to represent a single node in
820/// the binary search tree resulting from lowering a switch instruction.
821void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
822 SDOperand SwitchOp = getValue(CB.SwitchV);
823 SDOperand CaseOp = getValue(CB.CaseC);
824 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
825
826 // Set NextBlock to be the MBB immediately after the current one, if any.
827 // This is used to avoid emitting unnecessary branches to the next block.
828 MachineBasicBlock *NextBlock = 0;
829 MachineFunction::iterator BBI = CurMBB;
830 if (++BBI != CurMBB->getParent()->end())
831 NextBlock = BBI;
832
833 // If the lhs block is the next block, invert the condition so that we can
834 // fall through to the lhs instead of the rhs block.
835 if (CB.LHSBB == NextBlock) {
836 std::swap(CB.LHSBB, CB.RHSBB);
837 SDOperand True = DAG.getConstant(1, Cond.getValueType());
838 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
839 }
840 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
841 DAG.getBasicBlock(CB.LHSBB));
842 if (CB.RHSBB == NextBlock)
843 DAG.setRoot(BrCond);
844 else
845 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
846 DAG.getBasicBlock(CB.RHSBB)));
847 // Update successor info
848 CurMBB->addSuccessor(CB.LHSBB);
849 CurMBB->addSuccessor(CB.RHSBB);
850}
851
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000852void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000853 // Emit the code for the jump table
854 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000855 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
856 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +0000857 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000858 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +0000859 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000860 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
861 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000862 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +0000863 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
864 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +0000865 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000866 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +0000867 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +0000868 // For Pic, the sequence is:
869 // BRIND(load(Jumptable + index) + RelocBase)
870 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +0000871 SDOperand Reloc;
872 if (TLI.usesGlobalOffsetTable())
873 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
874 else
875 Reloc = TAB;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000876 ADD = DAG.getNode(ISD::ADD, PTy,
Andrew Lenharth783a4a92006-09-24 19:45:58 +0000877 ((PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD), Reloc);
Nate Begeman78756502006-07-27 01:13:04 +0000878 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
879 } else {
880 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
881 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000882}
883
Nate Begemaned728c12006-03-27 01:32:24 +0000884void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
885 // Figure out which block is immediately after the current one.
886 MachineBasicBlock *NextBlock = 0;
887 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000888
Nate Begemaned728c12006-03-27 01:32:24 +0000889 if (++BBI != CurMBB->getParent()->end())
890 NextBlock = BBI;
891
892 // If there is only the default destination, branch to it if it is not the
893 // next basic block. Otherwise, just fall through.
894 if (I.getNumOperands() == 2) {
895 // Update machine-CFG edges.
896 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000897
Nate Begemaned728c12006-03-27 01:32:24 +0000898 // If this is not a fall-through branch, emit the branch.
899 if (DefaultMBB != NextBlock)
900 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
901 DAG.getBasicBlock(DefaultMBB)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000902
Chris Lattner32d92e02006-06-12 18:25:29 +0000903 CurMBB->addSuccessor(DefaultMBB);
Nate Begemaned728c12006-03-27 01:32:24 +0000904 return;
905 }
906
907 // If there are any non-default case statements, create a vector of Cases
908 // representing each one, and sort the vector so that we can efficiently
909 // create a binary search tree from them.
910 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000911
Nate Begemaned728c12006-03-27 01:32:24 +0000912 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
913 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
914 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
915 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000916
Nate Begemaned728c12006-03-27 01:32:24 +0000917 std::sort(Cases.begin(), Cases.end(), CaseCmp());
918
919 // Get the Value to be switched on and default basic blocks, which will be
920 // inserted into CaseBlock records, representing basic blocks in the binary
921 // search tree.
922 Value *SV = I.getOperand(0);
923 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000924
925 // Get the MachineFunction which holds the current MBB. This is used during
926 // emission of jump tables, and when inserting any additional MBBs necessary
927 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +0000928 MachineFunction *CurMF = CurMBB->getParent();
929 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000930
Nate Begemand7a19102006-05-08 16:51:36 +0000931 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
932 // target supports indirect branches, then emit a jump table rather than
933 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +0000934 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +0000935 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000936 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
937 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +0000938 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
939
Nate Begemand7a19102006-05-08 16:51:36 +0000940 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000941 // Create a new basic block to hold the code for loading the address
942 // of the jump table, and jumping to it. Update successor information;
943 // we will either branch to the default case for the switch, or the jump
944 // table.
945 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
946 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
947 CurMBB->addSuccessor(Default);
948 CurMBB->addSuccessor(JumpTableBB);
949
950 // Subtract the lowest switch case value from the value being switched on
951 // and conditional branch to default mbb if the result is greater than the
952 // difference between smallest and largest cases.
953 SDOperand SwitchOp = getValue(SV);
954 MVT::ValueType VT = SwitchOp.getValueType();
955 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
956 DAG.getConstant(First, VT));
957
958 // The SDNode we just created, which holds the value being switched on
959 // minus the the smallest case value, needs to be copied to a virtual
960 // register so it can be used as an index into the jump table in a
961 // subsequent basic block. This value may be smaller or larger than the
962 // target's pointer type, and therefore require extension or truncating.
963 if (VT > TLI.getPointerTy())
964 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
965 else
966 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000967
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000968 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
969 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
970
971 // Emit the range check for the jump table, and branch to the default
972 // block for the switch statement if the value being switched on exceeds
973 // the largest case in the switch.
974 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
975 DAG.getConstant(Last-First,VT), ISD::SETUGT);
976 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
977 DAG.getBasicBlock(Default)));
978
Nate Begemandf488392006-05-03 03:48:02 +0000979 // Build a vector of destination BBs, corresponding to each target
980 // of the jump table. If the value of the jump table slot corresponds to
981 // a case statement, push the case's BB onto the vector, otherwise, push
982 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000983 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +0000984 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000985 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000986 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +0000987 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +0000988 ++ii;
989 } else {
990 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +0000991 }
Nate Begemandf488392006-05-03 03:48:02 +0000992
993 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +0000994 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
995 E = DestBBs.end(); I != E; ++I)
996 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +0000997
998 // Create a jump table index for this jump table, or return an existing
999 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001000 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1001
1002 // Set the jump table information so that we can codegen it as a second
1003 // MachineBasicBlock
1004 JT.Reg = JumpTableReg;
1005 JT.JTI = JTI;
1006 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001007 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001008 return;
1009 }
1010 }
Nate Begemaned728c12006-03-27 01:32:24 +00001011
1012 // Push the initial CaseRec onto the worklist
1013 std::vector<CaseRec> CaseVec;
1014 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1015
1016 while (!CaseVec.empty()) {
1017 // Grab a record representing a case range to process off the worklist
1018 CaseRec CR = CaseVec.back();
1019 CaseVec.pop_back();
1020
1021 // Size is the number of Cases represented by this range. If Size is 1,
1022 // then we are processing a leaf of the binary search tree. Otherwise,
1023 // we need to pick a pivot, and push left and right ranges onto the
1024 // worklist.
1025 unsigned Size = CR.Range.second - CR.Range.first;
1026
1027 if (Size == 1) {
1028 // Create a CaseBlock record representing a conditional branch to
1029 // the Case's target mbb if the value being switched on SV is equal
1030 // to C. Otherwise, branch to default.
1031 Constant *C = CR.Range.first->first;
1032 MachineBasicBlock *Target = CR.Range.first->second;
1033 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1034 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001035
Nate Begemaned728c12006-03-27 01:32:24 +00001036 // If the MBB representing the leaf node is the current MBB, then just
1037 // call visitSwitchCase to emit the code into the current block.
1038 // Otherwise, push the CaseBlock onto the vector to be later processed
1039 // by SDISel, and insert the node's MBB before the next MBB.
1040 if (CR.CaseBB == CurMBB)
1041 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001042 else
Nate Begemaned728c12006-03-27 01:32:24 +00001043 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001044 } else {
1045 // split case range at pivot
1046 CaseItr Pivot = CR.Range.first + (Size / 2);
1047 CaseRange LHSR(CR.Range.first, Pivot);
1048 CaseRange RHSR(Pivot, CR.Range.second);
1049 Constant *C = Pivot->first;
1050 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001051
Nate Begemaned728c12006-03-27 01:32:24 +00001052 // We know that we branch to the LHS if the Value being switched on is
1053 // less than the Pivot value, C. We use this to optimize our binary
1054 // tree a bit, by recognizing that if SV is greater than or equal to the
1055 // LHS's Case Value, and that Case Value is exactly one less than the
1056 // Pivot's Value, then we can branch directly to the LHS's Target,
1057 // rather than creating a leaf node for it.
1058 if ((LHSR.second - LHSR.first) == 1 &&
1059 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001060 cast<ConstantIntegral>(C)->getZExtValue() ==
1061 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001062 LHSBB = LHSR.first->second;
1063 } else {
1064 LHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001065 CurMF->getBasicBlockList().insert(BBI, LHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001066 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1067 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001068
Nate Begemaned728c12006-03-27 01:32:24 +00001069 // Similar to the optimization above, if the Value being switched on is
1070 // known to be less than the Constant CR.LT, and the current Case Value
1071 // is CR.LT - 1, then we can branch directly to the target block for
1072 // the current Case Value, rather than emitting a RHS leaf node for it.
1073 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001074 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1075 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001076 RHSBB = RHSR.first->second;
1077 } else {
1078 RHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001079 CurMF->getBasicBlockList().insert(BBI, RHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001080 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1081 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001082
Nate Begemaned728c12006-03-27 01:32:24 +00001083 // Create a CaseBlock record representing a conditional branch to
1084 // the LHS node if the value being switched on SV is less than C.
1085 // Otherwise, branch to LHS.
1086 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1087 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001088
Nate Begemaned728c12006-03-27 01:32:24 +00001089 if (CR.CaseBB == CurMBB)
1090 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001091 else
Nate Begemaned728c12006-03-27 01:32:24 +00001092 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001093 }
1094 }
1095}
1096
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001097void SelectionDAGLowering::visitSub(User &I) {
1098 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001099 if (I.getType()->isFloatingPoint()) {
1100 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1101 if (CFP->isExactlyValue(-0.0)) {
1102 SDOperand Op2 = getValue(I.getOperand(1));
1103 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1104 return;
1105 }
Chris Lattner6f3b5772005-09-28 22:28:18 +00001106 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001107 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001108}
1109
Nate Begemanb2e089c2005-11-19 00:36:38 +00001110void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1111 unsigned VecOp) {
1112 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001113 SDOperand Op1 = getValue(I.getOperand(0));
1114 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001115
Chris Lattner19baba62005-11-19 18:40:42 +00001116 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001117 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1118 } else if (Ty->isFloatingPoint()) {
1119 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1120 } else {
1121 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +00001122 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1123 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1124 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001125 }
Nate Begeman127321b2005-11-18 07:42:56 +00001126}
Chris Lattner96c26752005-01-19 22:31:21 +00001127
Nate Begeman127321b2005-11-18 07:42:56 +00001128void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1129 SDOperand Op1 = getValue(I.getOperand(0));
1130 SDOperand Op2 = getValue(I.getOperand(1));
1131
1132 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1133
Chris Lattner7a60d912005-01-07 07:47:53 +00001134 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1135}
1136
1137void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001138 ISD::CondCode UnsignedOpcode,
1139 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001140 SDOperand Op1 = getValue(I.getOperand(0));
1141 SDOperand Op2 = getValue(I.getOperand(1));
1142 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001143 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001144 Opcode = FPOpcode;
1145 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001146 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001147 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001148}
1149
1150void SelectionDAGLowering::visitSelect(User &I) {
1151 SDOperand Cond = getValue(I.getOperand(0));
1152 SDOperand TrueVal = getValue(I.getOperand(1));
1153 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001154 if (!isa<PackedType>(I.getType())) {
1155 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1156 TrueVal, FalseVal));
1157 } else {
1158 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1159 *(TrueVal.Val->op_end()-2),
1160 *(TrueVal.Val->op_end()-1)));
1161 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001162}
1163
1164void SelectionDAGLowering::visitCast(User &I) {
1165 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001166 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001167 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001168
Chris Lattner2f4119a2006-03-22 20:09:35 +00001169 if (DestVT == MVT::Vector) {
1170 // This is a cast to a vector from something else. This is always a bit
1171 // convert. Get information about the input vector.
1172 const PackedType *DestTy = cast<PackedType>(I.getType());
1173 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1174 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1175 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1176 DAG.getValueType(EltVT)));
1177 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001178 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001179 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001180 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001181 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001182 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001183 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001184 } else if (isInteger(SrcVT)) {
1185 if (isInteger(DestVT)) { // Int -> Int cast
1186 if (DestVT < SrcVT) // Truncating cast?
1187 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001188 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001189 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001190 else
Chris Lattner4024c002006-03-15 22:19:46 +00001191 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001192 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001193 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001194 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001195 else
Chris Lattner4024c002006-03-15 22:19:46 +00001196 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001197 } else {
1198 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001199 }
Chris Lattner4024c002006-03-15 22:19:46 +00001200 } else if (isFloatingPoint(SrcVT)) {
1201 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1202 if (DestVT < SrcVT) // Rounding cast?
1203 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001204 else
Chris Lattner4024c002006-03-15 22:19:46 +00001205 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001206 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001207 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001208 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001209 else
Chris Lattner4024c002006-03-15 22:19:46 +00001210 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001211 } else {
1212 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001213 }
1214 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001215 assert(SrcVT == MVT::Vector && "Unknown cast!");
1216 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1217 // This is a cast from a vector to something else. This is always a bit
1218 // convert. Get information about the input vector.
1219 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001220 }
1221}
1222
Chris Lattner67271862006-03-29 00:11:43 +00001223void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001224 SDOperand InVec = getValue(I.getOperand(0));
1225 SDOperand InVal = getValue(I.getOperand(1));
1226 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1227 getValue(I.getOperand(2)));
1228
Chris Lattner29b23012006-03-19 01:17:20 +00001229 SDOperand Num = *(InVec.Val->op_end()-2);
1230 SDOperand Typ = *(InVec.Val->op_end()-1);
1231 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1232 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001233}
1234
Chris Lattner67271862006-03-29 00:11:43 +00001235void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001236 SDOperand InVec = getValue(I.getOperand(0));
1237 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1238 getValue(I.getOperand(1)));
1239 SDOperand Typ = *(InVec.Val->op_end()-1);
1240 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1241 TLI.getValueType(I.getType()), InVec, InIdx));
1242}
Chris Lattner32206f52006-03-18 01:44:44 +00001243
Chris Lattner098c01e2006-04-08 04:15:24 +00001244void SelectionDAGLowering::visitShuffleVector(User &I) {
1245 SDOperand V1 = getValue(I.getOperand(0));
1246 SDOperand V2 = getValue(I.getOperand(1));
1247 SDOperand Mask = getValue(I.getOperand(2));
1248
1249 SDOperand Num = *(V1.Val->op_end()-2);
1250 SDOperand Typ = *(V2.Val->op_end()-1);
1251 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1252 V1, V2, Mask, Num, Typ));
1253}
1254
1255
Chris Lattner7a60d912005-01-07 07:47:53 +00001256void SelectionDAGLowering::visitGetElementPtr(User &I) {
1257 SDOperand N = getValue(I.getOperand(0));
1258 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001259
1260 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1261 OI != E; ++OI) {
1262 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001263 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001264 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001265 if (Field) {
1266 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001267 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001268 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001269 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001270 }
1271 Ty = StTy->getElementType(Field);
1272 } else {
1273 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001274
Chris Lattner43535a12005-11-09 04:45:33 +00001275 // If this is a constant subscript, handle it quickly.
1276 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001277 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001278 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001279 if (CI->getType()->isSigned())
1280 Offs = (int64_t)
1281 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001282 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001283 Offs =
1284 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001285 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1286 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001287 }
Chris Lattner43535a12005-11-09 04:45:33 +00001288
1289 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001290 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001291 SDOperand IdxN = getValue(Idx);
1292
1293 // If the index is smaller or larger than intptr_t, truncate or extend
1294 // it.
1295 if (IdxN.getValueType() < N.getValueType()) {
1296 if (Idx->getType()->isSigned())
1297 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1298 else
1299 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1300 } else if (IdxN.getValueType() > N.getValueType())
1301 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1302
1303 // If this is a multiply by a power of two, turn it into a shl
1304 // immediately. This is a very common case.
1305 if (isPowerOf2_64(ElementSize)) {
1306 unsigned Amt = Log2_64(ElementSize);
1307 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001308 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001309 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1310 continue;
1311 }
1312
1313 SDOperand Scale = getIntPtrConstant(ElementSize);
1314 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1315 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001316 }
1317 }
1318 setValue(&I, N);
1319}
1320
1321void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1322 // If this is a fixed sized alloca in the entry block of the function,
1323 // allocate it statically on the stack.
1324 if (FuncInfo.StaticAllocaMap.count(&I))
1325 return; // getValue will auto-populate this.
1326
1327 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001328 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1329 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001330 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001331
1332 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001333 MVT::ValueType IntPtr = TLI.getPointerTy();
1334 if (IntPtr < AllocSize.getValueType())
1335 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1336 else if (IntPtr > AllocSize.getValueType())
1337 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001338
Chris Lattnereccb73d2005-01-22 23:04:37 +00001339 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001340 getIntPtrConstant(TySize));
1341
1342 // Handle alignment. If the requested alignment is less than or equal to the
1343 // stack alignment, ignore it and round the size of the allocation up to the
1344 // stack alignment size. If the size is greater than the stack alignment, we
1345 // note this in the DYNAMIC_STACKALLOC node.
1346 unsigned StackAlign =
1347 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1348 if (Align <= StackAlign) {
1349 Align = 0;
1350 // Add SA-1 to the size.
1351 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1352 getIntPtrConstant(StackAlign-1));
1353 // Mask out the low bits for alignment purposes.
1354 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1355 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1356 }
1357
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001358 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001359 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1360 MVT::Other);
1361 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001362 DAG.setRoot(setValue(&I, DSA).getValue(1));
1363
1364 // Inform the Frame Information that we have just allocated a variable-sized
1365 // object.
1366 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1367}
1368
Chris Lattner7a60d912005-01-07 07:47:53 +00001369void SelectionDAGLowering::visitLoad(LoadInst &I) {
1370 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001371
Chris Lattner4d9651c2005-01-17 22:19:26 +00001372 SDOperand Root;
1373 if (I.isVolatile())
1374 Root = getRoot();
1375 else {
1376 // Do not serialize non-volatile loads against each other.
1377 Root = DAG.getRoot();
1378 }
Chris Lattner4024c002006-03-15 22:19:46 +00001379
Evan Chenge71fe34d2006-10-09 20:57:25 +00001380 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001381 Root, I.isVolatile()));
1382}
1383
1384SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001385 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001386 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001387 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001388 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001389 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001390 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1391 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001392 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001393 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001394 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001395
Chris Lattner4024c002006-03-15 22:19:46 +00001396 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001397 DAG.setRoot(L.getValue(1));
1398 else
1399 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001400
1401 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001402}
1403
1404
1405void SelectionDAGLowering::visitStore(StoreInst &I) {
1406 Value *SrcV = I.getOperand(0);
1407 SDOperand Src = getValue(SrcV);
1408 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001409 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1410 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001411}
1412
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001413/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1414/// access memory and has no other side effects at all.
1415static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1416#define GET_NO_MEMORY_INTRINSICS
1417#include "llvm/Intrinsics.gen"
1418#undef GET_NO_MEMORY_INTRINSICS
1419 return false;
1420}
1421
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001422// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1423// have any side-effects or if it only reads memory.
1424static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1425#define GET_SIDE_EFFECT_INFO
1426#include "llvm/Intrinsics.gen"
1427#undef GET_SIDE_EFFECT_INFO
1428 return false;
1429}
1430
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001431/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1432/// node.
1433void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1434 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001435 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001436 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001437
1438 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001439 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001440 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1441 if (OnlyLoad) {
1442 // We don't need to serialize loads against other loads.
1443 Ops.push_back(DAG.getRoot());
1444 } else {
1445 Ops.push_back(getRoot());
1446 }
1447 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001448
1449 // Add the intrinsic ID as an integer operand.
1450 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1451
1452 // Add all operands of the call to the operand list.
1453 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1454 SDOperand Op = getValue(I.getOperand(i));
1455
1456 // If this is a vector type, force it to the right packed type.
1457 if (Op.getValueType() == MVT::Vector) {
1458 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1459 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1460
1461 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1462 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1463 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1464 }
1465
1466 assert(TLI.isTypeLegal(Op.getValueType()) &&
1467 "Intrinsic uses a non-legal type?");
1468 Ops.push_back(Op);
1469 }
1470
1471 std::vector<MVT::ValueType> VTs;
1472 if (I.getType() != Type::VoidTy) {
1473 MVT::ValueType VT = TLI.getValueType(I.getType());
1474 if (VT == MVT::Vector) {
1475 const PackedType *DestTy = cast<PackedType>(I.getType());
1476 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1477
1478 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1479 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1480 }
1481
1482 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1483 VTs.push_back(VT);
1484 }
1485 if (HasChain)
1486 VTs.push_back(MVT::Other);
1487
Chris Lattnerbd887772006-08-14 23:53:35 +00001488 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1489
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001490 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001491 SDOperand Result;
1492 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001493 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1494 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001495 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001496 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1497 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001498 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001499 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1500 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001501
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001502 if (HasChain) {
1503 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1504 if (OnlyLoad)
1505 PendingLoads.push_back(Chain);
1506 else
1507 DAG.setRoot(Chain);
1508 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001509 if (I.getType() != Type::VoidTy) {
1510 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1511 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1512 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1513 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1514 DAG.getValueType(EVT));
1515 }
1516 setValue(&I, Result);
1517 }
1518}
1519
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001520/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1521/// we want to emit this as a call to a named external function, return the name
1522/// otherwise lower it and return null.
1523const char *
1524SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1525 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001526 default:
1527 // By default, turn this into a target intrinsic node.
1528 visitTargetIntrinsic(I, Intrinsic);
1529 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001530 case Intrinsic::vastart: visitVAStart(I); return 0;
1531 case Intrinsic::vaend: visitVAEnd(I); return 0;
1532 case Intrinsic::vacopy: visitVACopy(I); return 0;
1533 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1534 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1535 case Intrinsic::setjmp:
1536 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1537 break;
1538 case Intrinsic::longjmp:
1539 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1540 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001541 case Intrinsic::memcpy_i32:
1542 case Intrinsic::memcpy_i64:
1543 visitMemIntrinsic(I, ISD::MEMCPY);
1544 return 0;
1545 case Intrinsic::memset_i32:
1546 case Intrinsic::memset_i64:
1547 visitMemIntrinsic(I, ISD::MEMSET);
1548 return 0;
1549 case Intrinsic::memmove_i32:
1550 case Intrinsic::memmove_i64:
1551 visitMemIntrinsic(I, ISD::MEMMOVE);
1552 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001553
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001554 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001555 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001556 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001557 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001558 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001559
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001560 Ops[0] = getRoot();
1561 Ops[1] = getValue(SPI.getLineValue());
1562 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001563
Jim Laskeya8bdac82006-03-23 18:06:46 +00001564 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001565 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001566 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1567
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001568 Ops[3] = DAG.getString(CompileUnit->getFileName());
1569 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001570
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001571 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001572 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001573
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001574 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001575 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001576 case Intrinsic::dbg_region_start: {
1577 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1578 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001579 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001580 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001581 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1582 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001583 }
1584
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001585 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001586 }
1587 case Intrinsic::dbg_region_end: {
1588 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1589 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001590 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001591 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001592 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1593 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001594 }
1595
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001596 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001597 }
1598 case Intrinsic::dbg_func_start: {
1599 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1600 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001601 if (DebugInfo && FSI.getSubprogram() &&
1602 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001603 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001604 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1605 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001606 }
1607
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001608 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001609 }
1610 case Intrinsic::dbg_declare: {
1611 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1612 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001613 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001614 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001615 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001616 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001617 }
1618
1619 return 0;
1620 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001621
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001622 case Intrinsic::isunordered_f32:
1623 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001624 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1625 getValue(I.getOperand(2)), ISD::SETUO));
1626 return 0;
1627
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001628 case Intrinsic::sqrt_f32:
1629 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001630 setValue(&I, DAG.getNode(ISD::FSQRT,
1631 getValue(I.getOperand(1)).getValueType(),
1632 getValue(I.getOperand(1))));
1633 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001634 case Intrinsic::powi_f32:
1635 case Intrinsic::powi_f64:
1636 setValue(&I, DAG.getNode(ISD::FPOWI,
1637 getValue(I.getOperand(1)).getValueType(),
1638 getValue(I.getOperand(1)),
1639 getValue(I.getOperand(2))));
1640 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001641 case Intrinsic::pcmarker: {
1642 SDOperand Tmp = getValue(I.getOperand(1));
1643 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1644 return 0;
1645 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001646 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001647 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001648 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1649 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1650 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001651 setValue(&I, Tmp);
1652 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001653 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001654 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001655 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001656 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001657 case Intrinsic::bswap_i64:
1658 setValue(&I, DAG.getNode(ISD::BSWAP,
1659 getValue(I.getOperand(1)).getValueType(),
1660 getValue(I.getOperand(1))));
1661 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001662 case Intrinsic::cttz_i8:
1663 case Intrinsic::cttz_i16:
1664 case Intrinsic::cttz_i32:
1665 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001666 setValue(&I, DAG.getNode(ISD::CTTZ,
1667 getValue(I.getOperand(1)).getValueType(),
1668 getValue(I.getOperand(1))));
1669 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001670 case Intrinsic::ctlz_i8:
1671 case Intrinsic::ctlz_i16:
1672 case Intrinsic::ctlz_i32:
1673 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001674 setValue(&I, DAG.getNode(ISD::CTLZ,
1675 getValue(I.getOperand(1)).getValueType(),
1676 getValue(I.getOperand(1))));
1677 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001678 case Intrinsic::ctpop_i8:
1679 case Intrinsic::ctpop_i16:
1680 case Intrinsic::ctpop_i32:
1681 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001682 setValue(&I, DAG.getNode(ISD::CTPOP,
1683 getValue(I.getOperand(1)).getValueType(),
1684 getValue(I.getOperand(1))));
1685 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001686 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001687 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001688 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1689 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001690 setValue(&I, Tmp);
1691 DAG.setRoot(Tmp.getValue(1));
1692 return 0;
1693 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001694 case Intrinsic::stackrestore: {
1695 SDOperand Tmp = getValue(I.getOperand(1));
1696 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001697 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001698 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001699 case Intrinsic::prefetch:
1700 // FIXME: Currently discarding prefetches.
1701 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001702 }
1703}
1704
1705
Chris Lattner7a60d912005-01-07 07:47:53 +00001706void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001707 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001708 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001709 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001710 if (unsigned IID = F->getIntrinsicID()) {
1711 RenameFn = visitIntrinsicCall(I, IID);
1712 if (!RenameFn)
1713 return;
1714 } else { // Not an LLVM intrinsic.
1715 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001716 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1717 if (I.getNumOperands() == 3 && // Basic sanity checks.
1718 I.getOperand(1)->getType()->isFloatingPoint() &&
1719 I.getType() == I.getOperand(1)->getType() &&
1720 I.getType() == I.getOperand(2)->getType()) {
1721 SDOperand LHS = getValue(I.getOperand(1));
1722 SDOperand RHS = getValue(I.getOperand(2));
1723 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1724 LHS, RHS));
1725 return;
1726 }
1727 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001728 if (I.getNumOperands() == 2 && // Basic sanity checks.
1729 I.getOperand(1)->getType()->isFloatingPoint() &&
1730 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001731 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001732 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1733 return;
1734 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001735 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001736 if (I.getNumOperands() == 2 && // Basic sanity checks.
1737 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001738 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001739 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001740 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1741 return;
1742 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001743 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001744 if (I.getNumOperands() == 2 && // Basic sanity checks.
1745 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001746 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001747 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001748 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1749 return;
1750 }
1751 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001752 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001753 } else if (isa<InlineAsm>(I.getOperand(0))) {
1754 visitInlineAsm(I);
1755 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001756 }
Misha Brukman835702a2005-04-21 22:36:52 +00001757
Chris Lattner18d2b342005-01-08 22:48:57 +00001758 SDOperand Callee;
1759 if (!RenameFn)
1760 Callee = getValue(I.getOperand(0));
1761 else
1762 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001763 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001764 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001765 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1766 Value *Arg = I.getOperand(i);
1767 SDOperand ArgNode = getValue(Arg);
1768 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1769 }
Misha Brukman835702a2005-04-21 22:36:52 +00001770
Nate Begemanf6565252005-03-26 01:29:23 +00001771 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1772 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001773
Chris Lattner1f45cd72005-01-08 19:26:18 +00001774 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001775 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001776 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001777 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001778 setValue(&I, Result.first);
1779 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001780}
1781
Chris Lattner6f87d182006-02-22 22:37:12 +00001782SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001783 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001784 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1785 Chain = Val.getValue(1);
1786 Flag = Val.getValue(2);
1787
1788 // If the result was expanded, copy from the top part.
1789 if (Regs.size() > 1) {
1790 assert(Regs.size() == 2 &&
1791 "Cannot expand to more than 2 elts yet!");
1792 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00001793 Chain = Hi.getValue(1);
1794 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001795 if (DAG.getTargetLoweringInfo().isLittleEndian())
1796 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1797 else
1798 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001799 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001800
Chris Lattner705948d2006-06-08 18:22:48 +00001801 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00001802 // appropriate type.
1803 if (RegVT == ValueVT)
1804 return Val;
1805
Chris Lattner705948d2006-06-08 18:22:48 +00001806 if (MVT::isInteger(RegVT)) {
1807 if (ValueVT < RegVT)
1808 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1809 else
1810 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1811 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001812 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00001813 }
Chris Lattner6f87d182006-02-22 22:37:12 +00001814}
1815
Chris Lattner571d9642006-02-23 19:21:04 +00001816/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1817/// specified value into the registers specified by this object. This uses
1818/// Chain/Flag as the input and updates them for the output Chain/Flag.
1819void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00001820 SDOperand &Chain, SDOperand &Flag,
1821 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001822 if (Regs.size() == 1) {
1823 // If there is a single register and the types differ, this must be
1824 // a promotion.
1825 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00001826 if (MVT::isInteger(RegVT)) {
1827 if (RegVT < ValueVT)
1828 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1829 else
1830 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1831 } else
Chris Lattner571d9642006-02-23 19:21:04 +00001832 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1833 }
1834 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1835 Flag = Chain.getValue(1);
1836 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001837 std::vector<unsigned> R(Regs);
1838 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1839 std::reverse(R.begin(), R.end());
1840
1841 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001842 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00001843 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001844 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001845 Flag = Chain.getValue(1);
1846 }
1847 }
1848}
Chris Lattner6f87d182006-02-22 22:37:12 +00001849
Chris Lattner571d9642006-02-23 19:21:04 +00001850/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1851/// operand list. This adds the code marker and includes the number of
1852/// values added into it.
1853void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001854 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001855 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1856 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1857 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1858}
Chris Lattner6f87d182006-02-22 22:37:12 +00001859
1860/// isAllocatableRegister - If the specified register is safe to allocate,
1861/// i.e. it isn't a stack pointer or some other special register, return the
1862/// register class for the register. Otherwise, return null.
1863static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001864isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1865 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001866 MVT::ValueType FoundVT = MVT::Other;
1867 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001868 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1869 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001870 MVT::ValueType ThisVT = MVT::Other;
1871
Chris Lattnerb1124f32006-02-22 23:09:03 +00001872 const TargetRegisterClass *RC = *RCI;
1873 // If none of the the value types for this register class are valid, we
1874 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001875 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1876 I != E; ++I) {
1877 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001878 // If we have already found this register in a different register class,
1879 // choose the one with the largest VT specified. For example, on
1880 // PowerPC, we favor f64 register classes over f32.
1881 if (FoundVT == MVT::Other ||
1882 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1883 ThisVT = *I;
1884 break;
1885 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001886 }
1887 }
1888
Chris Lattnerbec582f2006-04-02 00:24:45 +00001889 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001890
Chris Lattner6f87d182006-02-22 22:37:12 +00001891 // NOTE: This isn't ideal. In particular, this might allocate the
1892 // frame pointer in functions that need it (due to them not being taken
1893 // out of allocation, because a variable sized allocation hasn't been seen
1894 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001895 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1896 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001897 if (*I == Reg) {
1898 // We found a matching register class. Keep looking at others in case
1899 // we find one with larger registers that this physreg is also in.
1900 FoundRC = RC;
1901 FoundVT = ThisVT;
1902 break;
1903 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001904 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001905 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001906}
1907
1908RegsForValue SelectionDAGLowering::
1909GetRegistersForValue(const std::string &ConstrCode,
1910 MVT::ValueType VT, bool isOutReg, bool isInReg,
1911 std::set<unsigned> &OutputRegs,
1912 std::set<unsigned> &InputRegs) {
1913 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1914 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1915 std::vector<unsigned> Regs;
1916
1917 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1918 MVT::ValueType RegVT;
1919 MVT::ValueType ValueVT = VT;
1920
1921 if (PhysReg.first) {
1922 if (VT == MVT::Other)
1923 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00001924
1925 // Get the actual register value type. This is important, because the user
1926 // may have asked for (e.g.) the AX register in i32 type. We need to
1927 // remember that AX is actually i16 to get the right extension.
1928 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00001929
1930 // This is a explicit reference to a physical register.
1931 Regs.push_back(PhysReg.first);
1932
1933 // If this is an expanded reference, add the rest of the regs to Regs.
1934 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001935 TargetRegisterClass::iterator I = PhysReg.second->begin();
1936 TargetRegisterClass::iterator E = PhysReg.second->end();
1937 for (; *I != PhysReg.first; ++I)
1938 assert(I != E && "Didn't find reg!");
1939
1940 // Already added the first reg.
1941 --NumRegs; ++I;
1942 for (; NumRegs; --NumRegs, ++I) {
1943 assert(I != E && "Ran out of registers to allocate!");
1944 Regs.push_back(*I);
1945 }
1946 }
1947 return RegsForValue(Regs, RegVT, ValueVT);
1948 }
1949
1950 // This is a reference to a register class. Allocate NumRegs consecutive,
1951 // available, registers from the class.
1952 std::vector<unsigned> RegClassRegs =
1953 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1954
1955 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1956 MachineFunction &MF = *CurMBB->getParent();
1957 unsigned NumAllocated = 0;
1958 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1959 unsigned Reg = RegClassRegs[i];
1960 // See if this register is available.
1961 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1962 (isInReg && InputRegs.count(Reg))) { // Already used.
1963 // Make sure we find consecutive registers.
1964 NumAllocated = 0;
1965 continue;
1966 }
1967
1968 // Check to see if this register is allocatable (i.e. don't give out the
1969 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001970 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001971 if (!RC) {
1972 // Make sure we find consecutive registers.
1973 NumAllocated = 0;
1974 continue;
1975 }
1976
1977 // Okay, this register is good, we can use it.
1978 ++NumAllocated;
1979
1980 // If we allocated enough consecutive
1981 if (NumAllocated == NumRegs) {
1982 unsigned RegStart = (i-NumAllocated)+1;
1983 unsigned RegEnd = i+1;
1984 // Mark all of the allocated registers used.
1985 for (unsigned i = RegStart; i != RegEnd; ++i) {
1986 unsigned Reg = RegClassRegs[i];
1987 Regs.push_back(Reg);
1988 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1989 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1990 }
1991
1992 return RegsForValue(Regs, *RC->vt_begin(), VT);
1993 }
1994 }
1995
1996 // Otherwise, we couldn't allocate enough registers for this.
1997 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001998}
1999
Chris Lattner6f87d182006-02-22 22:37:12 +00002000
Chris Lattner476e67b2006-01-26 22:24:51 +00002001/// visitInlineAsm - Handle a call to an InlineAsm object.
2002///
2003void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2004 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2005
2006 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2007 MVT::Other);
2008
2009 // Note, we treat inline asms both with and without side-effects as the same.
2010 // If an inline asm doesn't have side effects and doesn't access memory, we
2011 // could not choose to not chain it.
2012 bool hasSideEffects = IA->hasSideEffects();
2013
Chris Lattner3a5ed552006-02-01 01:28:23 +00002014 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002015 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002016
2017 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2018 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2019 /// if it is a def of that register.
2020 std::vector<SDOperand> AsmNodeOperands;
2021 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2022 AsmNodeOperands.push_back(AsmStr);
2023
2024 SDOperand Chain = getRoot();
2025 SDOperand Flag;
2026
Chris Lattner1558fc62006-02-01 18:59:47 +00002027 // We fully assign registers here at isel time. This is not optimal, but
2028 // should work. For register classes that correspond to LLVM classes, we
2029 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2030 // over the constraints, collecting fixed registers that we know we can't use.
2031 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002032 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002033 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2034 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2035 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002036
Chris Lattner7ad77df2006-02-22 00:56:39 +00002037 MVT::ValueType OpVT;
2038
2039 // Compute the value type for each operand and add it to ConstraintVTs.
2040 switch (Constraints[i].Type) {
2041 case InlineAsm::isOutput:
2042 if (!Constraints[i].isIndirectOutput) {
2043 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2044 OpVT = TLI.getValueType(I.getType());
2045 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002046 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002047 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2048 OpNum++; // Consumes a call operand.
2049 }
2050 break;
2051 case InlineAsm::isInput:
2052 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2053 OpNum++; // Consumes a call operand.
2054 break;
2055 case InlineAsm::isClobber:
2056 OpVT = MVT::Other;
2057 break;
2058 }
2059
2060 ConstraintVTs.push_back(OpVT);
2061
Chris Lattner6f87d182006-02-22 22:37:12 +00002062 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2063 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002064
Chris Lattner6f87d182006-02-22 22:37:12 +00002065 // Build a list of regs that this operand uses. This always has a single
2066 // element for promoted/expanded operands.
2067 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2068 false, false,
2069 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002070
2071 switch (Constraints[i].Type) {
2072 case InlineAsm::isOutput:
2073 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002074 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002075 // If this is an early-clobber output, it cannot be assigned to the same
2076 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002077 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002078 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002079 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002080 case InlineAsm::isInput:
2081 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002082 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002083 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002084 case InlineAsm::isClobber:
2085 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002086 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2087 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002088 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002089 }
2090 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002091
Chris Lattner5c79f982006-02-21 23:12:12 +00002092 // Loop over all of the inputs, copying the operand values into the
2093 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002094 RegsForValue RetValRegs;
2095 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002096 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002097
Chris Lattner2e56e892006-01-31 02:03:41 +00002098 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002099 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2100 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002101
Chris Lattner3a5ed552006-02-01 01:28:23 +00002102 switch (Constraints[i].Type) {
2103 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002104 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2105 if (ConstraintCode.size() == 1) // not a physreg name.
2106 CTy = TLI.getConstraintType(ConstraintCode[0]);
2107
2108 if (CTy == TargetLowering::C_Memory) {
2109 // Memory output.
2110 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2111
2112 // Check that the operand (the address to store to) isn't a float.
2113 if (!MVT::isInteger(InOperandVal.getValueType()))
2114 assert(0 && "MATCH FAIL!");
2115
2116 if (!Constraints[i].isIndirectOutput)
2117 assert(0 && "MATCH FAIL!");
2118
2119 OpNum++; // Consumes a call operand.
2120
2121 // Extend/truncate to the right pointer type if needed.
2122 MVT::ValueType PtrType = TLI.getPointerTy();
2123 if (InOperandVal.getValueType() < PtrType)
2124 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2125 else if (InOperandVal.getValueType() > PtrType)
2126 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2127
2128 // Add information to the INLINEASM node to know about this output.
2129 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2130 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2131 AsmNodeOperands.push_back(InOperandVal);
2132 break;
2133 }
2134
2135 // Otherwise, this is a register output.
2136 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2137
Chris Lattner6f87d182006-02-22 22:37:12 +00002138 // If this is an early-clobber output, or if there is an input
2139 // constraint that matches this, we need to reserve the input register
2140 // so no other inputs allocate to it.
2141 bool UsesInputRegister = false;
2142 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2143 UsesInputRegister = true;
2144
2145 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002146 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002147 RegsForValue Regs =
2148 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2149 true, UsesInputRegister,
2150 OutputRegs, InputRegs);
2151 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002152
Chris Lattner3a5ed552006-02-01 01:28:23 +00002153 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002154 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002155 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002156 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002157 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002158 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002159 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2160 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002161 OpNum++; // Consumes a call operand.
2162 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002163
2164 // Add information to the INLINEASM node to know that this register is
2165 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002166 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002167 break;
2168 }
2169 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002170 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002171 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002172
Chris Lattner7f5880b2006-02-02 00:25:23 +00002173 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2174 // If this is required to match an output register we have already set,
2175 // just use its register.
2176 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002177
Chris Lattner571d9642006-02-23 19:21:04 +00002178 // Scan until we find the definition we already emitted of this operand.
2179 // When we find it, create a RegsForValue operand.
2180 unsigned CurOp = 2; // The first operand.
2181 for (; OperandNo; --OperandNo) {
2182 // Advance to the next operand.
2183 unsigned NumOps =
2184 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002185 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2186 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002187 "Skipped past definitions?");
2188 CurOp += (NumOps>>3)+1;
2189 }
2190
2191 unsigned NumOps =
2192 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2193 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2194 "Skipped past definitions?");
2195
2196 // Add NumOps>>3 registers to MatchedRegs.
2197 RegsForValue MatchedRegs;
2198 MatchedRegs.ValueVT = InOperandVal.getValueType();
2199 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2200 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2201 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2202 MatchedRegs.Regs.push_back(Reg);
2203 }
2204
2205 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002206 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2207 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002208 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002209 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002210 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002211
2212 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2213 if (ConstraintCode.size() == 1) // not a physreg name.
2214 CTy = TLI.getConstraintType(ConstraintCode[0]);
2215
2216 if (CTy == TargetLowering::C_Other) {
2217 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2218 assert(0 && "MATCH FAIL!");
2219
2220 // Add information to the INLINEASM node to know about this input.
2221 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2222 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2223 AsmNodeOperands.push_back(InOperandVal);
2224 break;
2225 } else if (CTy == TargetLowering::C_Memory) {
2226 // Memory input.
2227
2228 // Check that the operand isn't a float.
2229 if (!MVT::isInteger(InOperandVal.getValueType()))
2230 assert(0 && "MATCH FAIL!");
2231
2232 // Extend/truncate to the right pointer type if needed.
2233 MVT::ValueType PtrType = TLI.getPointerTy();
2234 if (InOperandVal.getValueType() < PtrType)
2235 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2236 else if (InOperandVal.getValueType() > PtrType)
2237 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2238
2239 // Add information to the INLINEASM node to know about this input.
2240 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2241 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2242 AsmNodeOperands.push_back(InOperandVal);
2243 break;
2244 }
2245
2246 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2247
2248 // Copy the input into the appropriate registers.
2249 RegsForValue InRegs =
2250 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2251 false, true, OutputRegs, InputRegs);
2252 // FIXME: should be match fail.
2253 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2254
Evan Chengef9e07d2006-06-15 08:11:54 +00002255 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002256
2257 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002258 break;
2259 }
Chris Lattner571d9642006-02-23 19:21:04 +00002260 case InlineAsm::isClobber: {
2261 RegsForValue ClobberedRegs =
2262 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2263 OutputRegs, InputRegs);
2264 // Add the clobbered value to the operand list, so that the register
2265 // allocator is aware that the physreg got clobbered.
2266 if (!ClobberedRegs.Regs.empty())
2267 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002268 break;
2269 }
Chris Lattner571d9642006-02-23 19:21:04 +00002270 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002271 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002272
2273 // Finish up input operands.
2274 AsmNodeOperands[0] = Chain;
2275 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2276
Chris Lattnerbd887772006-08-14 23:53:35 +00002277 Chain = DAG.getNode(ISD::INLINEASM,
2278 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002279 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002280 Flag = Chain.getValue(1);
2281
Chris Lattner2e56e892006-01-31 02:03:41 +00002282 // If this asm returns a register value, copy the result from that register
2283 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002284 if (!RetValRegs.Regs.empty())
2285 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002286
Chris Lattner2e56e892006-01-31 02:03:41 +00002287 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2288
2289 // Process indirect outputs, first output all of the flagged copies out of
2290 // physregs.
2291 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002292 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002293 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002294 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2295 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002296 }
2297
2298 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002299 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002300 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002301 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002302 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002303 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002304 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002305 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2306 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002307 DAG.setRoot(Chain);
2308}
2309
2310
Chris Lattner7a60d912005-01-07 07:47:53 +00002311void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2312 SDOperand Src = getValue(I.getOperand(0));
2313
2314 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002315
2316 if (IntPtr < Src.getValueType())
2317 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2318 else if (IntPtr > Src.getValueType())
2319 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002320
2321 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002322 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002323 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2324 Src, getIntPtrConstant(ElementSize));
2325
2326 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002327 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002328
2329 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002330 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002331 DAG.getExternalSymbol("malloc", IntPtr),
2332 Args, DAG);
2333 setValue(&I, Result.first); // Pointers always fit in registers
2334 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002335}
2336
2337void SelectionDAGLowering::visitFree(FreeInst &I) {
2338 std::vector<std::pair<SDOperand, const Type*> > Args;
2339 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002340 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002341 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002342 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002343 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002344 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2345 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002346}
2347
Chris Lattner13d7c252005-08-26 20:54:47 +00002348// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2349// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2350// instructions are special in various ways, which require special support to
2351// insert. The specified MachineInstr is created but not inserted into any
2352// basic blocks, and the scheduler passes ownership of it to this method.
2353MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2354 MachineBasicBlock *MBB) {
2355 std::cerr << "If a target marks an instruction with "
2356 "'usesCustomDAGSchedInserter', it must implement "
2357 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2358 abort();
2359 return 0;
2360}
2361
Chris Lattner58cfd792005-01-09 00:00:49 +00002362void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002363 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2364 getValue(I.getOperand(1)),
2365 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002366}
2367
2368void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002369 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2370 getValue(I.getOperand(0)),
2371 DAG.getSrcValue(I.getOperand(0)));
2372 setValue(&I, V);
2373 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002374}
2375
2376void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002377 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2378 getValue(I.getOperand(1)),
2379 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002380}
2381
2382void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002383 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2384 getValue(I.getOperand(1)),
2385 getValue(I.getOperand(2)),
2386 DAG.getSrcValue(I.getOperand(1)),
2387 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002388}
2389
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002390/// TargetLowering::LowerArguments - This is the default LowerArguments
2391/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002392/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2393/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002394std::vector<SDOperand>
2395TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2396 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2397 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002398 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002399 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2400 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2401
2402 // Add one result value for each formal argument.
2403 std::vector<MVT::ValueType> RetVals;
2404 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2405 MVT::ValueType VT = getValueType(I->getType());
2406
2407 switch (getTypeAction(VT)) {
2408 default: assert(0 && "Unknown type action!");
2409 case Legal:
2410 RetVals.push_back(VT);
2411 break;
2412 case Promote:
2413 RetVals.push_back(getTypeToTransformTo(VT));
2414 break;
2415 case Expand:
2416 if (VT != MVT::Vector) {
2417 // If this is a large integer, it needs to be broken up into small
2418 // integers. Figure out what the destination type is and how many small
2419 // integers it turns into.
2420 MVT::ValueType NVT = getTypeToTransformTo(VT);
2421 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2422 for (unsigned i = 0; i != NumVals; ++i)
2423 RetVals.push_back(NVT);
2424 } else {
2425 // Otherwise, this is a vector type. We only support legal vectors
2426 // right now.
2427 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2428 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002429
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002430 // Figure out if there is a Packed type corresponding to this Vector
2431 // type. If so, convert to the packed type.
2432 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2433 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2434 RetVals.push_back(TVT);
2435 } else {
2436 assert(0 && "Don't support illegal by-val vector arguments yet!");
2437 }
2438 }
2439 break;
2440 }
2441 }
Evan Cheng9618df12006-04-25 23:03:35 +00002442
Chris Lattner3d826992006-05-16 06:45:34 +00002443 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002444
2445 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002446 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2447 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002448 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002449
2450 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002451
2452 // Set up the return result vector.
2453 Ops.clear();
2454 unsigned i = 0;
2455 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2456 MVT::ValueType VT = getValueType(I->getType());
2457
2458 switch (getTypeAction(VT)) {
2459 default: assert(0 && "Unknown type action!");
2460 case Legal:
2461 Ops.push_back(SDOperand(Result, i++));
2462 break;
2463 case Promote: {
2464 SDOperand Op(Result, i++);
2465 if (MVT::isInteger(VT)) {
2466 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2467 : ISD::AssertZext;
2468 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2469 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2470 } else {
2471 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2472 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2473 }
2474 Ops.push_back(Op);
2475 break;
2476 }
2477 case Expand:
2478 if (VT != MVT::Vector) {
2479 // If this is a large integer, it needs to be reassembled from small
2480 // integers. Figure out what the source elt type is and how many small
2481 // integers it is.
2482 MVT::ValueType NVT = getTypeToTransformTo(VT);
2483 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2484 if (NumVals == 2) {
2485 SDOperand Lo = SDOperand(Result, i++);
2486 SDOperand Hi = SDOperand(Result, i++);
2487
2488 if (!isLittleEndian())
2489 std::swap(Lo, Hi);
2490
2491 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2492 } else {
2493 // Value scalarized into many values. Unimp for now.
2494 assert(0 && "Cannot expand i64 -> i16 yet!");
2495 }
2496 } else {
2497 // Otherwise, this is a vector type. We only support legal vectors
2498 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002499 const PackedType *PTy = cast<PackedType>(I->getType());
2500 unsigned NumElems = PTy->getNumElements();
2501 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002502
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002503 // Figure out if there is a Packed type corresponding to this Vector
2504 // type. If so, convert to the packed type.
2505 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002506 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002507 SDOperand N = SDOperand(Result, i++);
2508 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002509 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2510 DAG.getConstant(NumElems, MVT::i32),
2511 DAG.getValueType(getValueType(EltTy)));
2512 Ops.push_back(N);
2513 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002514 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002515 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002516 }
2517 }
2518 break;
2519 }
2520 }
2521 return Ops;
2522}
2523
Chris Lattneraaa23d92006-05-16 22:53:20 +00002524
2525/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2526/// implementation, which just inserts an ISD::CALL node, which is later custom
2527/// lowered by the target to something concrete. FIXME: When all targets are
2528/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2529std::pair<SDOperand, SDOperand>
2530TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2531 unsigned CallingConv, bool isTailCall,
2532 SDOperand Callee,
2533 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002534 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002535 Ops.push_back(Chain); // Op#0 - Chain
2536 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2537 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2538 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2539 Ops.push_back(Callee);
2540
2541 // Handle all of the outgoing arguments.
2542 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2543 MVT::ValueType VT = getValueType(Args[i].second);
2544 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002545 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002546 switch (getTypeAction(VT)) {
2547 default: assert(0 && "Unknown type action!");
2548 case Legal:
2549 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002550 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002551 break;
2552 case Promote:
2553 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002554 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002555 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2556 } else {
2557 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2558 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2559 }
2560 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002561 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002562 break;
2563 case Expand:
2564 if (VT != MVT::Vector) {
2565 // If this is a large integer, it needs to be broken down into small
2566 // integers. Figure out what the source elt type is and how many small
2567 // integers it is.
2568 MVT::ValueType NVT = getTypeToTransformTo(VT);
2569 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2570 if (NumVals == 2) {
2571 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2572 DAG.getConstant(0, getPointerTy()));
2573 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2574 DAG.getConstant(1, getPointerTy()));
2575 if (!isLittleEndian())
2576 std::swap(Lo, Hi);
2577
2578 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002579 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002580 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002581 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002582 } else {
2583 // Value scalarized into many values. Unimp for now.
2584 assert(0 && "Cannot expand i64 -> i16 yet!");
2585 }
2586 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002587 // Otherwise, this is a vector type. We only support legal vectors
2588 // right now.
2589 const PackedType *PTy = cast<PackedType>(Args[i].second);
2590 unsigned NumElems = PTy->getNumElements();
2591 const Type *EltTy = PTy->getElementType();
2592
2593 // Figure out if there is a Packed type corresponding to this Vector
2594 // type. If so, convert to the packed type.
2595 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002596 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2597 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2598 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2599 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002600 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002601 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002602 assert(0 && "Don't support illegal by-val vector call args yet!");
2603 abort();
2604 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002605 }
2606 break;
2607 }
2608 }
2609
2610 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002611 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002612
2613 if (RetTy != Type::VoidTy) {
2614 MVT::ValueType VT = getValueType(RetTy);
2615 switch (getTypeAction(VT)) {
2616 default: assert(0 && "Unknown type action!");
2617 case Legal:
2618 RetTys.push_back(VT);
2619 break;
2620 case Promote:
2621 RetTys.push_back(getTypeToTransformTo(VT));
2622 break;
2623 case Expand:
2624 if (VT != MVT::Vector) {
2625 // If this is a large integer, it needs to be reassembled from small
2626 // integers. Figure out what the source elt type is and how many small
2627 // integers it is.
2628 MVT::ValueType NVT = getTypeToTransformTo(VT);
2629 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2630 for (unsigned i = 0; i != NumVals; ++i)
2631 RetTys.push_back(NVT);
2632 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002633 // Otherwise, this is a vector type. We only support legal vectors
2634 // right now.
2635 const PackedType *PTy = cast<PackedType>(RetTy);
2636 unsigned NumElems = PTy->getNumElements();
2637 const Type *EltTy = PTy->getElementType();
2638
2639 // Figure out if there is a Packed type corresponding to this Vector
2640 // type. If so, convert to the packed type.
2641 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2642 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2643 RetTys.push_back(TVT);
2644 } else {
2645 assert(0 && "Don't support illegal by-val vector call results yet!");
2646 abort();
2647 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002648 }
2649 }
2650 }
2651
2652 RetTys.push_back(MVT::Other); // Always has a chain.
2653
2654 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002655 SDOperand Res = DAG.getNode(ISD::CALL,
2656 DAG.getVTList(&RetTys[0], RetTys.size()),
2657 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002658
2659 // This returns a pair of operands. The first element is the
2660 // return value for the function (if RetTy is not VoidTy). The second
2661 // element is the outgoing token chain.
2662 SDOperand ResVal;
2663 if (RetTys.size() != 1) {
2664 MVT::ValueType VT = getValueType(RetTy);
2665 if (RetTys.size() == 2) {
2666 ResVal = Res;
2667
2668 // If this value was promoted, truncate it down.
2669 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002670 if (VT == MVT::Vector) {
2671 // Insert a VBITCONVERT to convert from the packed result type to the
2672 // MVT::Vector type.
2673 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2674 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2675
2676 // Figure out if there is a Packed type corresponding to this Vector
2677 // type. If so, convert to the packed type.
2678 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2679 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002680 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2681 // "N x PTyElementVT" MVT::Vector type.
2682 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002683 DAG.getConstant(NumElems, MVT::i32),
2684 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002685 } else {
2686 abort();
2687 }
2688 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002689 unsigned AssertOp = RetTy->isSigned() ?
2690 ISD::AssertSext : ISD::AssertZext;
2691 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2692 DAG.getValueType(VT));
2693 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2694 } else {
2695 assert(MVT::isFloatingPoint(VT));
2696 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2697 }
2698 }
2699 } else if (RetTys.size() == 3) {
2700 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2701 Res.getValue(0), Res.getValue(1));
2702
2703 } else {
2704 assert(0 && "Case not handled yet!");
2705 }
2706 }
2707
2708 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2709}
2710
2711
2712
Chris Lattner58cfd792005-01-09 00:00:49 +00002713// It is always conservatively correct for llvm.returnaddress and
2714// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002715//
2716// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2717// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002718std::pair<SDOperand, SDOperand>
2719TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2720 unsigned Depth, SelectionDAG &DAG) {
2721 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002722}
2723
Chris Lattner29dcc712005-05-14 05:50:48 +00002724SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002725 assert(0 && "LowerOperation not implemented for this target!");
2726 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002727 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002728}
2729
Nate Begeman595ec732006-01-28 03:14:31 +00002730SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2731 SelectionDAG &DAG) {
2732 assert(0 && "CustomPromoteOperation not implemented for this target!");
2733 abort();
2734 return SDOperand();
2735}
2736
Chris Lattner58cfd792005-01-09 00:00:49 +00002737void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002738 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00002739 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002740 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002741 setValue(&I, Result.first);
2742 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002743}
2744
Evan Cheng6781b6e2006-02-15 21:59:04 +00002745/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002746/// operand.
2747static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002748 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002749 MVT::ValueType CurVT = VT;
2750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2751 uint64_t Val = C->getValue() & 255;
2752 unsigned Shift = 8;
2753 while (CurVT != MVT::i8) {
2754 Val = (Val << Shift) | Val;
2755 Shift <<= 1;
2756 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002757 }
2758 return DAG.getConstant(Val, VT);
2759 } else {
2760 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2761 unsigned Shift = 8;
2762 while (CurVT != MVT::i8) {
2763 Value =
2764 DAG.getNode(ISD::OR, VT,
2765 DAG.getNode(ISD::SHL, VT, Value,
2766 DAG.getConstant(Shift, MVT::i8)), Value);
2767 Shift <<= 1;
2768 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002769 }
2770
2771 return Value;
2772 }
2773}
2774
Evan Cheng6781b6e2006-02-15 21:59:04 +00002775/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2776/// used when a memcpy is turned into a memset when the source is a constant
2777/// string ptr.
2778static SDOperand getMemsetStringVal(MVT::ValueType VT,
2779 SelectionDAG &DAG, TargetLowering &TLI,
2780 std::string &Str, unsigned Offset) {
2781 MVT::ValueType CurVT = VT;
2782 uint64_t Val = 0;
2783 unsigned MSB = getSizeInBits(VT) / 8;
2784 if (TLI.isLittleEndian())
2785 Offset = Offset + MSB - 1;
2786 for (unsigned i = 0; i != MSB; ++i) {
2787 Val = (Val << 8) | Str[Offset];
2788 Offset += TLI.isLittleEndian() ? -1 : 1;
2789 }
2790 return DAG.getConstant(Val, VT);
2791}
2792
Evan Cheng81fcea82006-02-14 08:22:34 +00002793/// getMemBasePlusOffset - Returns base and offset node for the
2794static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2795 SelectionDAG &DAG, TargetLowering &TLI) {
2796 MVT::ValueType VT = Base.getValueType();
2797 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2798}
2799
Evan Chengdb2a7a72006-02-14 20:12:38 +00002800/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002801/// to replace the memset / memcpy is below the threshold. It also returns the
2802/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002803static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2804 unsigned Limit, uint64_t Size,
2805 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002806 MVT::ValueType VT;
2807
2808 if (TLI.allowsUnalignedMemoryAccesses()) {
2809 VT = MVT::i64;
2810 } else {
2811 switch (Align & 7) {
2812 case 0:
2813 VT = MVT::i64;
2814 break;
2815 case 4:
2816 VT = MVT::i32;
2817 break;
2818 case 2:
2819 VT = MVT::i16;
2820 break;
2821 default:
2822 VT = MVT::i8;
2823 break;
2824 }
2825 }
2826
Evan Chengd5026102006-02-14 09:11:59 +00002827 MVT::ValueType LVT = MVT::i64;
2828 while (!TLI.isTypeLegal(LVT))
2829 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2830 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002831
Evan Chengd5026102006-02-14 09:11:59 +00002832 if (VT > LVT)
2833 VT = LVT;
2834
Evan Cheng04514992006-02-14 23:05:54 +00002835 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002836 while (Size != 0) {
2837 unsigned VTSize = getSizeInBits(VT) / 8;
2838 while (VTSize > Size) {
2839 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002840 VTSize >>= 1;
2841 }
Evan Chengd5026102006-02-14 09:11:59 +00002842 assert(MVT::isInteger(VT));
2843
2844 if (++NumMemOps > Limit)
2845 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002846 MemOps.push_back(VT);
2847 Size -= VTSize;
2848 }
Evan Chengd5026102006-02-14 09:11:59 +00002849
2850 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002851}
2852
Chris Lattner875def92005-01-11 05:56:49 +00002853void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002854 SDOperand Op1 = getValue(I.getOperand(1));
2855 SDOperand Op2 = getValue(I.getOperand(2));
2856 SDOperand Op3 = getValue(I.getOperand(3));
2857 SDOperand Op4 = getValue(I.getOperand(4));
2858 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2859 if (Align == 0) Align = 1;
2860
2861 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2862 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002863
2864 // Expand memset / memcpy to a series of load / store ops
2865 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002866 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00002867 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002868 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002869 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002870 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2871 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002872 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002873 unsigned Offset = 0;
2874 for (unsigned i = 0; i < NumMemOps; i++) {
2875 MVT::ValueType VT = MemOps[i];
2876 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002877 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00002878 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002879 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002880 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00002881 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002882 Offset += VTSize;
2883 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002884 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002885 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002886 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002887 case ISD::MEMCPY: {
2888 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2889 Size->getValue(), Align, TLI)) {
2890 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002891 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002892 GlobalAddressSDNode *G = NULL;
2893 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002894 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002895
2896 if (Op2.getOpcode() == ISD::GlobalAddress)
2897 G = cast<GlobalAddressSDNode>(Op2);
2898 else if (Op2.getOpcode() == ISD::ADD &&
2899 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2900 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2901 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002902 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002903 }
2904 if (G) {
2905 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002906 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002907 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002908 if (!Str.empty()) {
2909 CopyFromStr = true;
2910 SrcOff += SrcDelta;
2911 }
2912 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002913 }
2914
Evan Chenge2038bd2006-02-15 01:54:51 +00002915 for (unsigned i = 0; i < NumMemOps; i++) {
2916 MVT::ValueType VT = MemOps[i];
2917 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002918 SDOperand Value, Chain, Store;
2919
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002920 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002921 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2922 Chain = getRoot();
2923 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002924 DAG.getStore(Chain, Value,
2925 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002926 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002927 } else {
2928 Value = DAG.getLoad(VT, getRoot(),
2929 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00002930 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002931 Chain = Value.getValue(1);
2932 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002933 DAG.getStore(Chain, Value,
2934 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002935 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002936 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002937 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002938 SrcOff += VTSize;
2939 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002940 }
2941 }
2942 break;
2943 }
2944 }
2945
2946 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002947 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
2948 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00002949 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00002950 }
2951 }
2952
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002953 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00002954}
2955
Chris Lattner875def92005-01-11 05:56:49 +00002956//===----------------------------------------------------------------------===//
2957// SelectionDAGISel code
2958//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002959
2960unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2961 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2962}
2963
Chris Lattnerc9950c12005-08-17 06:37:43 +00002964void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002965 // FIXME: we only modify the CFG to split critical edges. This
2966 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00002967 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00002968}
Chris Lattner7a60d912005-01-07 07:47:53 +00002969
Chris Lattner35397782005-12-05 07:10:48 +00002970
Chris Lattner3e3f2c62006-05-05 21:17:49 +00002971/// OptimizeNoopCopyExpression - We have determined that the specified cast
2972/// instruction is a noop copy (e.g. it's casting from one pointer type to
2973/// another, int->uint, or int->sbyte on PPC.
2974///
2975/// Return true if any changes are made.
2976static bool OptimizeNoopCopyExpression(CastInst *CI) {
2977 BasicBlock *DefBB = CI->getParent();
2978
2979 /// InsertedCasts - Only insert a cast in each block once.
2980 std::map<BasicBlock*, CastInst*> InsertedCasts;
2981
2982 bool MadeChange = false;
2983 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2984 UI != E; ) {
2985 Use &TheUse = UI.getUse();
2986 Instruction *User = cast<Instruction>(*UI);
2987
2988 // Figure out which BB this cast is used in. For PHI's this is the
2989 // appropriate predecessor block.
2990 BasicBlock *UserBB = User->getParent();
2991 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2992 unsigned OpVal = UI.getOperandNo()/2;
2993 UserBB = PN->getIncomingBlock(OpVal);
2994 }
2995
2996 // Preincrement use iterator so we don't invalidate it.
2997 ++UI;
2998
2999 // If this user is in the same block as the cast, don't change the cast.
3000 if (UserBB == DefBB) continue;
3001
3002 // If we have already inserted a cast into this block, use it.
3003 CastInst *&InsertedCast = InsertedCasts[UserBB];
3004
3005 if (!InsertedCast) {
3006 BasicBlock::iterator InsertPt = UserBB->begin();
3007 while (isa<PHINode>(InsertPt)) ++InsertPt;
3008
3009 InsertedCast =
3010 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3011 MadeChange = true;
3012 }
3013
3014 // Replace a use of the cast with a use of the new casat.
3015 TheUse = InsertedCast;
3016 }
3017
3018 // If we removed all uses, nuke the cast.
3019 if (CI->use_empty())
3020 CI->eraseFromParent();
3021
3022 return MadeChange;
3023}
3024
Chris Lattner35397782005-12-05 07:10:48 +00003025/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3026/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003027static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3028 Instruction *GEPI, Value *Ptr,
3029 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003030 if (V) return V; // Already computed.
3031
3032 BasicBlock::iterator InsertPt;
3033 if (BB == GEPI->getParent()) {
3034 // If insert into the GEP's block, insert right after the GEP.
3035 InsertPt = GEPI;
3036 ++InsertPt;
3037 } else {
3038 // Otherwise, insert at the top of BB, after any PHI nodes
3039 InsertPt = BB->begin();
3040 while (isa<PHINode>(InsertPt)) ++InsertPt;
3041 }
3042
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003043 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3044 // BB so that there is only one value live across basic blocks (the cast
3045 // operand).
3046 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3047 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3048 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3049
Chris Lattner35397782005-12-05 07:10:48 +00003050 // Add the offset, cast it to the right type.
3051 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003052 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003053}
3054
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003055/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3056/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3057/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3058/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3059/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3060/// the constant add into a load or store instruction. Additionally, if a user
3061/// is a pointer-pointer cast, we look through it to find its users.
3062static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3063 Constant *PtrOffset, BasicBlock *DefBB,
3064 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003065 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003066 while (!RepPtr->use_empty()) {
3067 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003068
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003069 // If the user is a Pointer-Pointer cast, recurse.
3070 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3071 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003072
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003073 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3074 // could invalidate an iterator.
3075 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3076 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003077 }
3078
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003079 // If this is a load of the pointer, or a store through the pointer, emit
3080 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003081 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003082 if (isa<LoadInst>(User) ||
3083 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3084 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3085 User->getParent(), GEPI,
3086 Ptr, PtrOffset);
3087 } else {
3088 // If this use is not foldable into the addressing mode, use a version
3089 // emitted in the GEP block.
3090 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3091 Ptr, PtrOffset);
3092 }
3093
Chris Lattner21cd9902006-05-06 09:10:37 +00003094 if (GEPI->getType() != RepPtr->getType()) {
3095 BasicBlock::iterator IP = NewVal;
3096 ++IP;
3097 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3098 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003099 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003100 }
3101}
Chris Lattner35397782005-12-05 07:10:48 +00003102
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003103
Chris Lattner35397782005-12-05 07:10:48 +00003104/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3105/// selection, we want to be a bit careful about some things. In particular, if
3106/// we have a GEP instruction that is used in a different block than it is
3107/// defined, the addressing expression of the GEP cannot be folded into loads or
3108/// stores that use it. In this case, decompose the GEP and move constant
3109/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003110static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003111 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003112 // If this GEP is only used inside the block it is defined in, there is no
3113 // need to rewrite it.
3114 bool isUsedOutsideDefBB = false;
3115 BasicBlock *DefBB = GEPI->getParent();
3116 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3117 UI != E; ++UI) {
3118 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3119 isUsedOutsideDefBB = true;
3120 break;
3121 }
3122 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003123 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003124
3125 // If this GEP has no non-zero constant indices, there is nothing we can do,
3126 // ignore it.
3127 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003128 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003129 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3130 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003131 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003132 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003133 hasConstantIndex = true;
3134 break;
3135 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003136 } else {
3137 hasVariableIndex = true;
3138 }
Chris Lattner35397782005-12-05 07:10:48 +00003139 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003140
3141 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3142 if (!hasConstantIndex && !hasVariableIndex) {
3143 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3144 GEPI->getName(), GEPI);
3145 GEPI->replaceAllUsesWith(NC);
3146 GEPI->eraseFromParent();
3147 return true;
3148 }
3149
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003150 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003151 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3152 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003153
3154 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3155 // constant offset (which we now know is non-zero) and deal with it later.
3156 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003157 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003158 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3159 const Type *Ty = GEPI->getOperand(0)->getType();
3160
3161 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3162 E = GEPI->op_end(); OI != E; ++OI) {
3163 Value *Idx = *OI;
3164 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003165 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003166 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003167 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003168 Ty = StTy->getElementType(Field);
3169 } else {
3170 Ty = cast<SequentialType>(Ty)->getElementType();
3171
3172 // Handle constant subscripts.
3173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003174 if (CI->getZExtValue() == 0) continue;
3175 if (CI->getType()->isSigned())
3176 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003177 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003178 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003179 continue;
3180 }
3181
3182 // Ptr = Ptr + Idx * ElementSize;
3183
3184 // Cast Idx to UIntPtrTy if needed.
3185 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3186
Owen Anderson20a631f2006-05-03 01:29:57 +00003187 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003188 // Mask off bits that should not be set.
3189 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003190 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003191
3192 // Multiply by the element size and add to the base.
3193 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3194 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3195 }
3196 }
3197
3198 // Make sure that the offset fits in uintptr_t.
3199 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003200 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003201
3202 // Okay, we have now emitted all of the variable index parts to the BB that
3203 // the GEP is defined in. Loop over all of the using instructions, inserting
3204 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003205 // instruction to use the newly computed value, making GEPI dead. When the
3206 // user is a load or store instruction address, we emit the add into the user
3207 // block, otherwise we use a canonical version right next to the gep (these
3208 // won't be foldable as addresses, so we might as well share the computation).
3209
Chris Lattner21cd9902006-05-06 09:10:37 +00003210 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003211 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003212
3213 // Finally, the GEP is dead, remove it.
3214 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003215
3216 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003217}
3218
Chris Lattnera9caf952006-09-28 06:17:10 +00003219/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3220/// constant operands, and if any of the edges feeding the PHI node are
3221/// critical, split them so that the assignments of a constant to a register
3222/// will not be executed on a path that isn't relevant.
3223void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003224 // The most common case is that this is a PHI node with two incoming
3225 // successors handle this case efficiently, because it is simple.
3226 PHINode *PN = cast<PHINode>(BB->begin());
3227 if (PN->getNumIncomingValues() == 2) {
3228 // If neither edge is critical, we never need to split.
3229 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3230 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3231 return;
3232
3233 BasicBlock::iterator BBI = BB->begin();
3234 while ((PN = dyn_cast<PHINode>(BBI++))) {
3235 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3236 if (isa<Constant>(PN->getIncomingValue(i)))
3237 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3238 }
3239 return;
3240 }
3241
3242 // Otherwise, things are a bit trickier.
3243
3244 // BE SMART HERE.
3245
Chris Lattnera9caf952006-09-28 06:17:10 +00003246 BasicBlock::iterator BBI = BB->begin();
3247 while ((PN = dyn_cast<PHINode>(BBI++))) {
3248 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3249 if (isa<Constant>(PN->getIncomingValue(i)))
3250 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3251 }
3252}
3253
3254
Chris Lattner7a60d912005-01-07 07:47:53 +00003255bool SelectionDAGISel::runOnFunction(Function &Fn) {
3256 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3257 RegMap = MF.getSSARegMap();
3258 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3259
Chris Lattner35397782005-12-05 07:10:48 +00003260 // First, split all critical edges for PHI nodes with incoming values that are
3261 // constants, this way the load of the constant into a vreg will not be placed
3262 // into MBBs that are used some other way.
3263 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003264 // In this pass we also look for GEP and cast instructions that are used
3265 // across basic blocks and rewrite them to improve basic-block-at-a-time
3266 // selection.
3267 //
Chris Lattner35397782005-12-05 07:10:48 +00003268 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003269 bool MadeChange = true;
3270 while (MadeChange) {
3271 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003272 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003273 // If this block has any PHI nodes with constant operands, and if any of the
3274 // edges feeding the PHI node are critical, split them.
3275 if (isa<PHINode>(BB->begin()))
3276 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003277
Chris Lattnera9caf952006-09-28 06:17:10 +00003278 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003279 Instruction *I = BBI++;
3280 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003281 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003282 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003283 // If the source of the cast is a constant, then this should have
3284 // already been constant folded. The only reason NOT to constant fold
3285 // it is if something (e.g. LSR) was careful to place the constant
3286 // evaluation in a block other than then one that uses it (e.g. to hoist
3287 // the address of globals out of a loop). If this is the case, we don't
3288 // want to forward-subst the cast.
3289 if (isa<Constant>(CI->getOperand(0)))
3290 continue;
3291
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003292 // If this is a noop copy, sink it into user blocks to reduce the number
3293 // of virtual registers that must be created and coallesced.
3294 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3295 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3296
3297 // This is an fp<->int conversion?
3298 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3299 continue;
3300
3301 // If this is an extension, it will be a zero or sign extension, which
3302 // isn't a noop.
3303 if (SrcVT < DstVT) continue;
3304
3305 // If these values will be promoted, find out what they will be promoted
3306 // to. This helps us consider truncates on PPC as noop copies when they
3307 // are.
3308 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3309 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3310 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3311 DstVT = TLI.getTypeToTransformTo(DstVT);
3312
3313 // If, after promotion, these are the same types, this is a noop copy.
3314 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003315 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003316 }
3317 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003318 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003319 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003320
Chris Lattner7a60d912005-01-07 07:47:53 +00003321 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3322
3323 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3324 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003325
Chris Lattner7a60d912005-01-07 07:47:53 +00003326 return true;
3327}
3328
3329
Chris Lattner718b5c22005-01-13 17:59:43 +00003330SDOperand SelectionDAGISel::
3331CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00003332 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003333 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003334 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003335 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003336
3337 // If this type is not legal, we must make sure to not create an invalid
3338 // register use.
3339 MVT::ValueType SrcVT = Op.getValueType();
3340 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3341 SelectionDAG &DAG = SDL.DAG;
3342 if (SrcVT == DestVT) {
3343 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003344 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003345 // Handle copies from generic vectors to registers.
3346 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3347 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3348 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003349
Chris Lattner5fe1f542006-03-31 02:06:56 +00003350 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3351 // MVT::Vector type.
3352 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3353 DAG.getConstant(NE, MVT::i32),
3354 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003355
Chris Lattner5fe1f542006-03-31 02:06:56 +00003356 // Loop over all of the elements of the resultant vector,
3357 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3358 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003359 SmallVector<SDOperand, 8> OutChains;
Chris Lattner5fe1f542006-03-31 02:06:56 +00003360 SDOperand Root = SDL.getRoot();
3361 for (unsigned i = 0; i != NE; ++i) {
3362 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003363 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003364 if (PTyElementVT == PTyLegalElementVT) {
3365 // Elements are legal.
3366 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3367 } else if (PTyLegalElementVT > PTyElementVT) {
3368 // Elements are promoted.
3369 if (MVT::isFloatingPoint(PTyLegalElementVT))
3370 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3371 else
3372 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3373 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3374 } else {
3375 // Elements are expanded.
3376 // The src value is expanded into multiple registers.
3377 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003378 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003379 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003380 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003381 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3382 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3383 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003384 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003385 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3386 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003387 } else if (SrcVT < DestVT) {
3388 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003389 if (MVT::isFloatingPoint(SrcVT))
3390 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3391 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003392 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003393 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3394 } else {
3395 // The src value is expanded into multiple registers.
3396 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003397 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003398 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003399 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003400 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3401 return DAG.getCopyToReg(Op, Reg+1, Hi);
3402 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003403}
3404
Chris Lattner16f64df2005-01-17 17:15:02 +00003405void SelectionDAGISel::
3406LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3407 std::vector<SDOperand> &UnorderedChains) {
3408 // If this is the entry block, emit arguments.
3409 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003410 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003411 SDOperand OldRoot = SDL.DAG.getRoot();
3412 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003413
Chris Lattner6871b232005-10-30 19:42:35 +00003414 unsigned a = 0;
3415 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3416 AI != E; ++AI, ++a)
3417 if (!AI->use_empty()) {
3418 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003419
Chris Lattner6871b232005-10-30 19:42:35 +00003420 // If this argument is live outside of the entry block, insert a copy from
3421 // whereever we got it to the vreg that other BB's will reference it as.
3422 if (FuncInfo.ValueMap.count(AI)) {
3423 SDOperand Copy =
3424 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3425 UnorderedChains.push_back(Copy);
3426 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003427 }
Chris Lattner6871b232005-10-30 19:42:35 +00003428
Chris Lattner6871b232005-10-30 19:42:35 +00003429 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003430 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003431 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003432}
3433
Chris Lattner7a60d912005-01-07 07:47:53 +00003434void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3435 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003436 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003437 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003438
3439 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003440
Chris Lattner6871b232005-10-30 19:42:35 +00003441 // Lower any arguments needed in this block if this is the entry block.
3442 if (LLVMBB == &LLVMBB->getParent()->front())
3443 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003444
3445 BB = FuncInfo.MBBMap[LLVMBB];
3446 SDL.setCurrentBasicBlock(BB);
3447
3448 // Lower all of the non-terminator instructions.
3449 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3450 I != E; ++I)
3451 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003452
Chris Lattner7a60d912005-01-07 07:47:53 +00003453 // Ensure that all instructions which are used outside of their defining
3454 // blocks are available as virtual registers.
3455 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003456 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003457 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003458 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003459 UnorderedChains.push_back(
3460 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003461 }
3462
3463 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3464 // ensure constants are generated when needed. Remember the virtual registers
3465 // that need to be added to the Machine PHI nodes as input. We cannot just
3466 // directly add them, because expansion might result in multiple MBB's for one
3467 // BB. As such, the start of the BB might correspond to a different MBB than
3468 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003469 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003470
3471 // Emit constants only once even if used by multiple PHI nodes.
3472 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003473
Chris Lattner7a60d912005-01-07 07:47:53 +00003474 // Check successor nodes PHI nodes that expect a constant to be available from
3475 // this block.
3476 TerminatorInst *TI = LLVMBB->getTerminator();
3477 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3478 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003479 if (!isa<PHINode>(SuccBB->begin())) continue;
3480
Chris Lattner7a60d912005-01-07 07:47:53 +00003481 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3482 PHINode *PN;
3483
3484 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3485 // nodes and Machine PHI nodes, but the incoming operands have not been
3486 // emitted yet.
3487 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003488 (PN = dyn_cast<PHINode>(I)); ++I)
3489 if (!PN->use_empty()) {
3490 unsigned Reg;
3491 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3492 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3493 unsigned &RegOut = ConstantsOut[C];
3494 if (RegOut == 0) {
3495 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003496 UnorderedChains.push_back(
3497 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003498 }
3499 Reg = RegOut;
3500 } else {
3501 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003502 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003503 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003504 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3505 "Didn't codegen value into a register!??");
3506 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003507 UnorderedChains.push_back(
3508 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003509 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003510 }
Misha Brukman835702a2005-04-21 22:36:52 +00003511
Chris Lattner8ea875f2005-01-07 21:34:19 +00003512 // Remember that this register needs to added to the machine PHI node as
3513 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003514 MVT::ValueType VT = TLI.getValueType(PN->getType());
3515 unsigned NumElements;
3516 if (VT != MVT::Vector)
3517 NumElements = TLI.getNumElements(VT);
3518 else {
3519 MVT::ValueType VT1,VT2;
3520 NumElements =
3521 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3522 VT1, VT2);
3523 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003524 for (unsigned i = 0, e = NumElements; i != e; ++i)
3525 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003526 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003527 }
3528 ConstantsOut.clear();
3529
Chris Lattner718b5c22005-01-13 17:59:43 +00003530 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003531 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003532 SDOperand Root = SDL.getRoot();
3533 if (Root.getOpcode() != ISD::EntryToken) {
3534 unsigned i = 0, e = UnorderedChains.size();
3535 for (; i != e; ++i) {
3536 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3537 if (UnorderedChains[i].Val->getOperand(0) == Root)
3538 break; // Don't add the root if we already indirectly depend on it.
3539 }
3540
3541 if (i == e)
3542 UnorderedChains.push_back(Root);
3543 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003544 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3545 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003546 }
3547
Chris Lattner7a60d912005-01-07 07:47:53 +00003548 // Lower the terminator after the copies are emitted.
3549 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003550
Nate Begemaned728c12006-03-27 01:32:24 +00003551 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003552 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003553 SwitchCases.clear();
3554 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003555 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003556
Chris Lattner4108bb02005-01-17 19:43:36 +00003557 // Make sure the root of the DAG is up-to-date.
3558 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003559}
3560
Nate Begemaned728c12006-03-27 01:32:24 +00003561void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003562 // Get alias analysis for load/store combining.
3563 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3564
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003565 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003566 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003567
Chris Lattner7a60d912005-01-07 07:47:53 +00003568 DEBUG(std::cerr << "Lowered selection DAG:\n");
3569 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003570
Chris Lattner7a60d912005-01-07 07:47:53 +00003571 // Second step, hack on the DAG until it only uses operations and types that
3572 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003573 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003574
Chris Lattner7a60d912005-01-07 07:47:53 +00003575 DEBUG(std::cerr << "Legalized selection DAG:\n");
3576 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003577
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003578 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003579 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003580
Evan Cheng739a6a42006-01-21 02:32:06 +00003581 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003582
Chris Lattner5ca31d92005-03-30 01:10:47 +00003583 // Third, instruction select all of the operations to machine code, adding the
3584 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003585 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003586
Chris Lattner7a60d912005-01-07 07:47:53 +00003587 DEBUG(std::cerr << "Selected machine code:\n");
3588 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003589}
Chris Lattner7a60d912005-01-07 07:47:53 +00003590
Nate Begemaned728c12006-03-27 01:32:24 +00003591void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3592 FunctionLoweringInfo &FuncInfo) {
3593 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3594 {
3595 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3596 CurDAG = &DAG;
3597
3598 // First step, lower LLVM code to some DAG. This DAG may use operations and
3599 // types that are not supported by the target.
3600 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3601
3602 // Second step, emit the lowered DAG as machine code.
3603 CodeGenAndEmitDAG(DAG);
3604 }
3605
Chris Lattner5ca31d92005-03-30 01:10:47 +00003606 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003607 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003608 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003609 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3610 MachineInstr *PHI = PHINodesToUpdate[i].first;
3611 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3612 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003613 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003614 PHI->addMachineBasicBlockOperand(BB);
3615 }
3616 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003617 }
Nate Begemaned728c12006-03-27 01:32:24 +00003618
Nate Begeman866b4b42006-04-23 06:26:20 +00003619 // If the JumpTable record is filled in, then we need to emit a jump table.
3620 // Updating the PHI nodes is tricky in this case, since we need to determine
3621 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003622 if (JT.Reg) {
3623 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3624 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3625 CurDAG = &SDAG;
3626 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003627 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003628 // Set the current basic block to the mbb we wish to insert the code into
3629 BB = JT.MBB;
3630 SDL.setCurrentBasicBlock(BB);
3631 // Emit the code
3632 SDL.visitJumpTable(JT);
3633 SDAG.setRoot(SDL.getRoot());
3634 CodeGenAndEmitDAG(SDAG);
3635 // Update PHI Nodes
3636 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3637 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3638 MachineBasicBlock *PHIBB = PHI->getParent();
3639 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3640 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003641 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003642 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003643 PHI->addMachineBasicBlockOperand(RangeBB);
3644 }
3645 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003646 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003647 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003648 }
3649 }
3650 return;
3651 }
3652
Nate Begemaned728c12006-03-27 01:32:24 +00003653 // If we generated any switch lowering information, build and codegen any
3654 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003655 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003656 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3657 CurDAG = &SDAG;
3658 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003659
Nate Begemaned728c12006-03-27 01:32:24 +00003660 // Set the current basic block to the mbb we wish to insert the code into
3661 BB = SwitchCases[i].ThisBB;
3662 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003663
Nate Begemaned728c12006-03-27 01:32:24 +00003664 // Emit the code
3665 SDL.visitSwitchCase(SwitchCases[i]);
3666 SDAG.setRoot(SDL.getRoot());
3667 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003668
3669 // Handle any PHI nodes in successors of this chunk, as if we were coming
3670 // from the original BB before switch expansion. Note that PHI nodes can
3671 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3672 // handle them the right number of times.
3673 while ((BB = SwitchCases[i].LHSBB)) { // Handle LHS and RHS.
3674 for (MachineBasicBlock::iterator Phi = BB->begin();
3675 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3676 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3677 for (unsigned pn = 0; ; ++pn) {
3678 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3679 if (PHINodesToUpdate[pn].first == Phi) {
3680 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3681 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3682 break;
3683 }
3684 }
Nate Begemaned728c12006-03-27 01:32:24 +00003685 }
Chris Lattner707339a52006-09-07 01:59:34 +00003686
3687 // Don't process RHS if same block as LHS.
3688 if (BB == SwitchCases[i].RHSBB)
3689 SwitchCases[i].RHSBB = 0;
3690
3691 // If we haven't handled the RHS, do so now. Otherwise, we're done.
3692 SwitchCases[i].LHSBB = SwitchCases[i].RHSBB;
3693 SwitchCases[i].RHSBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003694 }
Chris Lattner707339a52006-09-07 01:59:34 +00003695 assert(SwitchCases[i].LHSBB == 0 && SwitchCases[i].RHSBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003696 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003697}
Evan Cheng739a6a42006-01-21 02:32:06 +00003698
Jim Laskey95eda5b2006-08-01 14:21:23 +00003699
Evan Cheng739a6a42006-01-21 02:32:06 +00003700//===----------------------------------------------------------------------===//
3701/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3702/// target node in the graph.
3703void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3704 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003705
Jim Laskey29e635d2006-08-02 12:30:23 +00003706 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003707
3708 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003709 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003710 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003711 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003712
Jim Laskey03593f72006-08-01 18:29:48 +00003713 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003714 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003715 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003716}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003717
Chris Lattner47639db2006-03-06 00:22:00 +00003718
Jim Laskey03593f72006-08-01 18:29:48 +00003719HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3720 return new HazardRecognizer();
3721}
3722
Chris Lattner6df34962006-10-11 03:58:02 +00003723//===----------------------------------------------------------------------===//
3724// Helper functions used by the generated instruction selector.
3725//===----------------------------------------------------------------------===//
3726// Calls to these methods are generated by tblgen.
3727
3728/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3729/// the dag combiner simplified the 255, we still want to match. RHS is the
3730/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3731/// specified in the .td file (e.g. 255).
3732bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3733 int64_t DesiredMaskS) {
3734 uint64_t ActualMask = RHS->getValue();
3735 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3736
3737 // If the actual mask exactly matches, success!
3738 if (ActualMask == DesiredMask)
3739 return true;
3740
3741 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3742 if (ActualMask & ~DesiredMask)
3743 return false;
3744
3745 // Otherwise, the DAG Combiner may have proven that the value coming in is
3746 // either already zero or is not demanded. Check for known zero input bits.
3747 uint64_t NeededMask = DesiredMask & ~ActualMask;
3748 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3749 return true;
3750
3751 // TODO: check to see if missing bits are just not demanded.
3752
3753 // Otherwise, this pattern doesn't match.
3754 return false;
3755}
3756
3757/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3758/// the dag combiner simplified the 255, we still want to match. RHS is the
3759/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3760/// specified in the .td file (e.g. 255).
3761bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3762 int64_t DesiredMaskS) {
3763 uint64_t ActualMask = RHS->getValue();
3764 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3765
3766 // If the actual mask exactly matches, success!
3767 if (ActualMask == DesiredMask)
3768 return true;
3769
3770 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3771 if (ActualMask & ~DesiredMask)
3772 return false;
3773
3774 // Otherwise, the DAG Combiner may have proven that the value coming in is
3775 // either already zero or is not demanded. Check for known zero input bits.
3776 uint64_t NeededMask = DesiredMask & ~ActualMask;
3777
3778 uint64_t KnownZero, KnownOne;
3779 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
3780
3781 // If all the missing bits in the or are already known to be set, match!
3782 if ((NeededMask & KnownOne) == NeededMask)
3783 return true;
3784
3785 // TODO: check to see if missing bits are just not demanded.
3786
3787 // Otherwise, this pattern doesn't match.
3788 return false;
3789}
3790
Jim Laskey03593f72006-08-01 18:29:48 +00003791
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003792/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3793/// by tblgen. Others should not call it.
3794void SelectionDAGISel::
3795SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3796 std::vector<SDOperand> InOps;
3797 std::swap(InOps, Ops);
3798
3799 Ops.push_back(InOps[0]); // input chain.
3800 Ops.push_back(InOps[1]); // input asm string.
3801
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003802 unsigned i = 2, e = InOps.size();
3803 if (InOps[e-1].getValueType() == MVT::Flag)
3804 --e; // Don't process a flag operand if it is here.
3805
3806 while (i != e) {
3807 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3808 if ((Flags & 7) != 4 /*MEM*/) {
3809 // Just skip over this operand, copying the operands verbatim.
3810 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3811 i += (Flags >> 3) + 1;
3812 } else {
3813 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3814 // Otherwise, this is a memory operand. Ask the target to select it.
3815 std::vector<SDOperand> SelOps;
3816 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3817 std::cerr << "Could not match memory address. Inline asm failure!\n";
3818 exit(1);
3819 }
3820
3821 // Add this to the output node.
3822 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3823 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3824 i += 2;
3825 }
3826 }
3827
3828 // Add the flag input back if present.
3829 if (e != InOps.size())
3830 Ops.push_back(InOps.back());
3831}