blob: 2387e9b5d77be239761f6fdcde92a7f852b368d7 [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/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000025#include "llvm/IntrinsicInst.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000029#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000031#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000034#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Target/TargetFrameInfo.h"
37#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000040#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000041#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000042#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000043#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000044#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000045using namespace llvm;
46
Chris Lattner975f5c92005-09-01 18:44:10 +000047#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000048static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000049ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
51static cl::opt<bool>
52ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000054#else
Chris Lattneref598052006-04-02 03:07:27 +000055static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000056#endif
57
Jim Laskey29e635d2006-08-02 12:30:23 +000058//===---------------------------------------------------------------------===//
59///
60/// RegisterScheduler class - Track the registration of instruction schedulers.
61///
62//===---------------------------------------------------------------------===//
63MachinePassRegistry RegisterScheduler::Registry;
64
65//===---------------------------------------------------------------------===//
66///
67/// ISHeuristic command line option for instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000071 cl::opt<RegisterScheduler::FunctionPassCtor, false,
72 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000073 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000074 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000075 cl::desc("Instruction schedulers available:"));
76
Jim Laskey03593f72006-08-01 18:29:48 +000077 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000078 defaultListDAGScheduler("default", " Best scheduler for the target",
79 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000080} // namespace
81
Chris Lattner6f87d182006-02-22 22:37:12 +000082namespace {
83 /// RegsForValue - This struct represents the physical registers that a
84 /// particular value is assigned and the type information about the value.
85 /// This is needed because values can be promoted into larger registers and
86 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000087 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000088 /// Regs - This list hold the register (for legal and promoted values)
89 /// or register set (for expanded values) that the value should be assigned
90 /// to.
91 std::vector<unsigned> Regs;
92
93 /// RegVT - The value type of each register.
94 ///
95 MVT::ValueType RegVT;
96
97 /// ValueVT - The value type of the LLVM value, which may be promoted from
98 /// RegVT or made from merging the two expanded parts.
99 MVT::ValueType ValueVT;
100
101 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102
103 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
104 : RegVT(regvt), ValueVT(valuevt) {
105 Regs.push_back(Reg);
106 }
107 RegsForValue(const std::vector<unsigned> &regs,
108 MVT::ValueType regvt, MVT::ValueType valuevt)
109 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
110 }
111
112 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
113 /// this value and returns the result as a ValueVT value. This uses
114 /// Chain/Flag as the input and updates them for the output Chain/Flag.
115 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000116 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000117
118 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
119 /// specified value into the registers specified by this object. This uses
120 /// Chain/Flag as the input and updates them for the output Chain/Flag.
121 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000122 SDOperand &Chain, SDOperand &Flag,
123 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
126 /// operand list. This adds the code marker and includes the number of
127 /// values added into it.
128 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000129 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000130 };
131}
Evan Chengc1e1d972006-01-23 07:01:07 +0000132
Chris Lattner7a60d912005-01-07 07:47:53 +0000133namespace llvm {
134 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000135 /// createDefaultScheduler - This creates an instruction scheduler appropriate
136 /// for the target.
137 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
138 SelectionDAG *DAG,
139 MachineBasicBlock *BB) {
140 TargetLowering &TLI = IS->getTargetLowering();
141
142 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
143 return createTDListDAGScheduler(IS, DAG, BB);
144 } else {
145 assert(TLI.getSchedulingPreference() ==
146 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
147 return createBURRListDAGScheduler(IS, DAG, BB);
148 }
149 }
150
151
152 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000153 /// FunctionLoweringInfo - This contains information that is global to a
154 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000155 class FunctionLoweringInfo {
156 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 TargetLowering &TLI;
158 Function &Fn;
159 MachineFunction &MF;
160 SSARegMap *RegMap;
161
162 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
163
164 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
165 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
166
167 /// ValueMap - Since we emit code for the function a basic block at a time,
168 /// we must remember which virtual registers hold the values for
169 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000170 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000171
172 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
173 /// the entry block. This allows the allocas to be efficiently referenced
174 /// anywhere in the function.
175 std::map<const AllocaInst*, int> StaticAllocaMap;
176
177 unsigned MakeReg(MVT::ValueType VT) {
178 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
179 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000180
181 /// isExportedInst - Return true if the specified value is an instruction
182 /// exported from its block.
183 bool isExportedInst(const Value *V) {
184 return ValueMap.count(V);
185 }
Misha Brukman835702a2005-04-21 22:36:52 +0000186
Chris Lattner49409cb2006-03-16 19:51:18 +0000187 unsigned CreateRegForValue(const Value *V);
188
Chris Lattner7a60d912005-01-07 07:47:53 +0000189 unsigned InitializeRegForValue(const Value *V) {
190 unsigned &R = ValueMap[V];
191 assert(R == 0 && "Already initialized this value register!");
192 return R = CreateRegForValue(V);
193 }
194 };
195}
196
197/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000198/// PHI nodes or outside of the basic block that defines it, or used by a
199/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000200static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
201 if (isa<PHINode>(I)) return true;
202 BasicBlock *BB = I->getParent();
203 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000204 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000205 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000206 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 =
Chris Lattner945e4372007-02-14 05:52:17 +0000243 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(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 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000247 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000249 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000250 }
251
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000252 for (; BB != EB; ++BB)
253 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
255 if (!isa<AllocaInst>(I) ||
256 !StaticAllocaMap.count(cast<AllocaInst>(I)))
257 InitializeRegForValue(I);
258
259 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
260 // also creates the initial PHI MachineInstrs, though none of the input
261 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000262 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000263 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
264 MBBMap[BB] = MBB;
265 MF.getBasicBlockList().push_back(MBB);
266
267 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
268 // appropriate.
269 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000270 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
271 if (PN->use_empty()) continue;
272
273 MVT::ValueType VT = TLI.getValueType(PN->getType());
274 unsigned NumElements;
275 if (VT != MVT::Vector)
276 NumElements = TLI.getNumElements(VT);
277 else {
278 MVT::ValueType VT1,VT2;
279 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000280 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000281 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000282 }
Chris Lattner84a03502006-10-27 23:50:33 +0000283 unsigned PHIReg = ValueMap[PN];
284 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000285 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000286 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000287 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000288 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000289 }
290}
291
Chris Lattner49409cb2006-03-16 19:51:18 +0000292/// CreateRegForValue - Allocate the appropriate number of virtual registers of
293/// the correctly promoted or expanded types. Assign these registers
294/// consecutive vreg numbers and return the first assigned number.
295unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
296 MVT::ValueType VT = TLI.getValueType(V->getType());
297
298 // The number of multiples of registers that we need, to, e.g., split up
299 // a <2 x int64> -> 4 x i32 registers.
300 unsigned NumVectorRegs = 1;
301
Reid Spencer09575ba2007-02-15 03:39:18 +0000302 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000303 // and how many of the elements it will use.
304 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000305 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000306 unsigned NumElts = PTy->getNumElements();
307 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
308
309 // Divide the input until we get to a supported size. This will always
310 // end with a scalar if the target doesn't support vectors.
311 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
312 NumElts >>= 1;
313 NumVectorRegs <<= 1;
314 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000315 if (NumElts == 1)
316 VT = EltTy;
317 else
318 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000319 }
320
321 // The common case is that we will only create one register for this
322 // value. If we have that case, create and return the virtual register.
323 unsigned NV = TLI.getNumElements(VT);
324 if (NV == 1) {
325 // If we are promoting this value, pick the next largest supported type.
326 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
327 unsigned Reg = MakeReg(PromotedType);
328 // If this is a vector of supported or promoted types (e.g. 4 x i16),
329 // create all of the registers.
330 for (unsigned i = 1; i != NumVectorRegs; ++i)
331 MakeReg(PromotedType);
332 return Reg;
333 }
334
335 // If this value is represented with multiple target registers, make sure
336 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000337 VT = TLI.getTypeToExpandTo(VT);
338 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000339 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000340 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000341 return R;
342}
Chris Lattner7a60d912005-01-07 07:47:53 +0000343
344//===----------------------------------------------------------------------===//
345/// SelectionDAGLowering - This is the common target-independent lowering
346/// implementation that is parameterized by a TargetLowering object.
347/// Also, targets can overload any lowering method.
348///
349namespace llvm {
350class SelectionDAGLowering {
351 MachineBasicBlock *CurMBB;
352
Chris Lattner79084302007-02-04 01:31:47 +0000353 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000354
Chris Lattner4d9651c2005-01-17 22:19:26 +0000355 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
356 /// them up and then emit token factor nodes when possible. This allows us to
357 /// get simple disambiguation between loads without worrying about alias
358 /// analysis.
359 std::vector<SDOperand> PendingLoads;
360
Nate Begemaned728c12006-03-27 01:32:24 +0000361 /// Case - A pair of values to record the Value for a switch case, and the
362 /// case's target basic block.
363 typedef std::pair<Constant*, MachineBasicBlock*> Case;
364 typedef std::vector<Case>::iterator CaseItr;
365 typedef std::pair<CaseItr, CaseItr> CaseRange;
366
367 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
368 /// of conditional branches.
369 struct CaseRec {
370 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
371 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
372
373 /// CaseBB - The MBB in which to emit the compare and branch
374 MachineBasicBlock *CaseBB;
375 /// LT, GE - If nonzero, we know the current case value must be less-than or
376 /// greater-than-or-equal-to these Constants.
377 Constant *LT;
378 Constant *GE;
379 /// Range - A pair of iterators representing the range of case values to be
380 /// processed at this point in the binary search tree.
381 CaseRange Range;
382 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000383
384 typedef std::vector<CaseRec> CaseRecVector;
Nate Begemaned728c12006-03-27 01:32:24 +0000385
386 /// The comparison function for sorting Case values.
387 struct CaseCmp {
388 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000389 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattner2fbff4d2007-02-13 20:09:07 +0000390 return cast<const ConstantInt>(C1.first)->getSExtValue() <
391 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000392 }
393 };
394
Chris Lattner7a60d912005-01-07 07:47:53 +0000395public:
396 // TLI - This is information that describes the available target features we
397 // need for lowering. This indicates when operations are unavailable,
398 // implemented with a libcall, etc.
399 TargetLowering &TLI;
400 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000401 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000402
Nate Begemaned728c12006-03-27 01:32:24 +0000403 /// SwitchCases - Vector of CaseBlock structures used to communicate
404 /// SwitchInst code generation information.
405 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000406 /// JTCases - Vector of JumpTable structures used to communicate
407 /// SwitchInst code generation information.
408 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000409
Chris Lattner7a60d912005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000417 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000418 }
419
Chris Lattner4108bb02005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000425
Chris Lattner4d9651c2005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000439 }
440
Chris Lattnered0110b2006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner4024c002006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner8471b152006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
Chris Lattner79084302007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000475
Chris Lattner6f87d182006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000481
Chris Lattnered0110b2006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000487 void LowerCallTo(Instruction &I,
488 const Type *CalledValueTy, unsigned CallingConv,
489 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000490
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 // Terminator instructions.
492 void visitRet(ReturnInst &I);
493 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000494 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 void visitUnreachable(UnreachableInst &I) { /* noop */ }
496
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000497 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000498 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000499 CaseRecVector& WorkList,
500 Value* SV,
501 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000502 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000503 CaseRecVector& WorkList,
504 Value* SV,
505 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000506 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000507 CaseRecVector& WorkList,
508 Value* SV,
509 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000510 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000511 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000512 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
513 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000514
Chris Lattner7a60d912005-01-07 07:47:53 +0000515 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000516 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000517 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000518 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000519
Reid Spencer2eadb532007-01-21 00:29:26 +0000520 void visitScalarBinary(User &I, unsigned OpCode);
521 void visitVectorBinary(User &I, unsigned OpCode);
522 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000523 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000524 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000525 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000526 visitVectorBinary(I, ISD::VADD);
527 else if (I.getType()->isFloatingPoint())
528 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000529 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000530 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000531 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000532 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000533 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000534 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000535 visitVectorBinary(I, ISD::VMUL);
536 else if (I.getType()->isFloatingPoint())
537 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000538 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000539 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000540 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000541 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
542 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
543 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
544 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
545 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
546 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
547 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
548 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
549 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
550 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000551 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
552 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000553 void visitICmp(User &I);
554 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000555 // Visit the conversion instructions
556 void visitTrunc(User &I);
557 void visitZExt(User &I);
558 void visitSExt(User &I);
559 void visitFPTrunc(User &I);
560 void visitFPExt(User &I);
561 void visitFPToUI(User &I);
562 void visitFPToSI(User &I);
563 void visitUIToFP(User &I);
564 void visitSIToFP(User &I);
565 void visitPtrToInt(User &I);
566 void visitIntToPtr(User &I);
567 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568
Chris Lattner67271862006-03-29 00:11:43 +0000569 void visitExtractElement(User &I);
570 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000571 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000572
Chris Lattner7a60d912005-01-07 07:47:53 +0000573 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000574 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000575
576 void visitMalloc(MallocInst &I);
577 void visitFree(FreeInst &I);
578 void visitAlloca(AllocaInst &I);
579 void visitLoad(LoadInst &I);
580 void visitStore(StoreInst &I);
581 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
582 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000583 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000584 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000585 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000586
Chris Lattner7a60d912005-01-07 07:47:53 +0000587 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000588 void visitVAArg(VAArgInst &I);
589 void visitVAEnd(CallInst &I);
590 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000591
Chris Lattner875def92005-01-11 05:56:49 +0000592 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000593
594 void visitUserOp1(Instruction &I) {
595 assert(0 && "UserOp1 should not exist at instruction selection time!");
596 abort();
597 }
598 void visitUserOp2(Instruction &I) {
599 assert(0 && "UserOp2 should not exist at instruction selection time!");
600 abort();
601 }
602};
603} // end namespace llvm
604
Chris Lattner8471b152006-03-16 19:57:50 +0000605SDOperand SelectionDAGLowering::getValue(const Value *V) {
606 SDOperand &N = NodeMap[V];
607 if (N.Val) return N;
608
609 const Type *VTy = V->getType();
610 MVT::ValueType VT = TLI.getValueType(VTy);
611 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
612 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
613 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000614 SDOperand N1 = NodeMap[V];
615 assert(N1.Val && "visit didn't populate the ValueMap!");
616 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000617 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
618 return N = DAG.getGlobalAddress(GV, VT);
619 } else if (isa<ConstantPointerNull>(C)) {
620 return N = DAG.getConstant(0, TLI.getPointerTy());
621 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000622 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000623 return N = DAG.getNode(ISD::UNDEF, VT);
624
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000625 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000626 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000627 unsigned NumElements = PTy->getNumElements();
628 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
629
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000630 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000631 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
632
633 // Create a VConstant node with generic Vector type.
634 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
635 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000636 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
637 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000638 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
639 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000640 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000641 unsigned NumElements = PTy->getNumElements();
642 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000643
644 // Now that we know the number and type of the elements, push a
645 // Constant or ConstantFP node onto the ops list for each element of
646 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000647 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000648 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000649 for (unsigned i = 0; i != NumElements; ++i)
650 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000651 } else {
652 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
653 SDOperand Op;
654 if (MVT::isFloatingPoint(PVT))
655 Op = DAG.getConstantFP(0, PVT);
656 else
657 Op = DAG.getConstant(0, PVT);
658 Ops.assign(NumElements, Op);
659 }
660
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000661 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000662 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
663 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000664 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
665 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000666 } else {
667 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000668 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000669 }
670 }
671
672 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
673 std::map<const AllocaInst*, int>::iterator SI =
674 FuncInfo.StaticAllocaMap.find(AI);
675 if (SI != FuncInfo.StaticAllocaMap.end())
676 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
677 }
678
Chris Lattner8c504cf2007-02-25 18:40:32 +0000679 unsigned InReg = FuncInfo.ValueMap[V];
680 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000681
682 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000683 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000684 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000685 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000686 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000687 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
688 unsigned NumVals = TLI.getNumElements(VT);
689 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
690 if (NumVals == 1)
691 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
692 else {
693 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
694 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
695 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
696 }
697 } else {
698 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
699 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
700 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
701 N = MVT::isFloatingPoint(VT)
702 ? DAG.getNode(ISD::FP_ROUND, VT, N)
703 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000704 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000705 } else {
706 // Otherwise, if this is a vector, make it available as a generic vector
707 // here.
708 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000709 const VectorType *PTy = cast<VectorType>(VTy);
710 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000711 PTyLegalElementVT);
712
713 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000714 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000715 if (PTyElementVT == PTyLegalElementVT) {
716 // If the value types are legal, just VBUILD the CopyFromReg nodes.
717 for (unsigned i = 0; i != NE; ++i)
718 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
719 PTyElementVT));
720 } else if (PTyElementVT < PTyLegalElementVT) {
721 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
722 for (unsigned i = 0; i != NE; ++i) {
723 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 if (MVT::isFloatingPoint(PTyElementVT))
726 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
727 else
728 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
729 Ops.push_back(Op);
730 }
731 } else {
732 // If the register was expanded, use BUILD_PAIR.
733 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
734 for (unsigned i = 0; i != NE/2; ++i) {
735 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
736 PTyElementVT);
737 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
738 PTyElementVT);
739 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
740 }
741 }
742
743 Ops.push_back(DAG.getConstant(NE, MVT::i32));
744 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000745 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000746
747 // Finally, use a VBIT_CONVERT to make this available as the appropriate
748 // vector type.
749 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
750 DAG.getConstant(PTy->getNumElements(),
751 MVT::i32),
752 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000753 }
754
755 return N;
756}
757
758
Chris Lattner7a60d912005-01-07 07:47:53 +0000759void SelectionDAGLowering::visitRet(ReturnInst &I) {
760 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000761 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000762 return;
763 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000764 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000765 NewValues.push_back(getRoot());
766 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
767 SDOperand RetOp = getValue(I.getOperand(i));
768
769 // If this is an integer return value, we need to promote it ourselves to
770 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
771 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000772 // FIXME: C calling convention requires the return type to be promoted to
773 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000774 if (MVT::isInteger(RetOp.getValueType()) &&
775 RetOp.getValueType() < MVT::i64) {
776 MVT::ValueType TmpVT;
777 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
778 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
779 else
780 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000781 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000782 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000783 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
784 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000785 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
786 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000787 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000788 }
789 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000790 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000791 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000792 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
793 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000794}
795
Chris Lattnered0110b2006-10-27 21:36:01 +0000796/// ExportFromCurrentBlock - If this condition isn't known to be exported from
797/// the current basic block, add it to ValueMap now so that we'll get a
798/// CopyTo/FromReg.
799void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
800 // No need to export constants.
801 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
802
803 // Already exported?
804 if (FuncInfo.isExportedInst(V)) return;
805
806 unsigned Reg = FuncInfo.InitializeRegForValue(V);
807 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
808}
809
Chris Lattner84a03502006-10-27 23:50:33 +0000810bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
811 const BasicBlock *FromBB) {
812 // The operands of the setcc have to be in this block. We don't know
813 // how to export them from some other block.
814 if (Instruction *VI = dyn_cast<Instruction>(V)) {
815 // Can export from current BB.
816 if (VI->getParent() == FromBB)
817 return true;
818
819 // Is already exported, noop.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // If this is an argument, we can export it if the BB is the entry block or
824 // if it is already exported.
825 if (isa<Argument>(V)) {
826 if (FromBB == &FromBB->getParent()->getEntryBlock())
827 return true;
828
829 // Otherwise, can only export this if it is already exported.
830 return FuncInfo.isExportedInst(V);
831 }
832
833 // Otherwise, constants can always be exported.
834 return true;
835}
836
Chris Lattnere60ae822006-10-29 21:01:20 +0000837static bool InBlock(const Value *V, const BasicBlock *BB) {
838 if (const Instruction *I = dyn_cast<Instruction>(V))
839 return I->getParent() == BB;
840 return true;
841}
842
Chris Lattnered0110b2006-10-27 21:36:01 +0000843/// FindMergedConditions - If Cond is an expression like
844void SelectionDAGLowering::FindMergedConditions(Value *Cond,
845 MachineBasicBlock *TBB,
846 MachineBasicBlock *FBB,
847 MachineBasicBlock *CurBB,
848 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000849 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000850 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000851
Reid Spencer266e42b2006-12-23 06:05:41 +0000852 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
853 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000854 BOp->getParent() != CurBB->getBasicBlock() ||
855 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
856 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000857 const BasicBlock *BB = CurBB->getBasicBlock();
858
Reid Spencer266e42b2006-12-23 06:05:41 +0000859 // If the leaf of the tree is a comparison, merge the condition into
860 // the caseblock.
861 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
862 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000863 // how to export them from some other block. If this is the first block
864 // of the sequence, no exporting is needed.
865 (CurBB == CurMBB ||
866 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
867 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000868 BOp = cast<Instruction>(Cond);
869 ISD::CondCode Condition;
870 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
871 switch (IC->getPredicate()) {
872 default: assert(0 && "Unknown icmp predicate opcode!");
873 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
874 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
875 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
876 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
877 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
878 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
879 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
880 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
881 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
882 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
883 }
884 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
885 ISD::CondCode FPC, FOC;
886 switch (FC->getPredicate()) {
887 default: assert(0 && "Unknown fcmp predicate opcode!");
888 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
889 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
890 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
891 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
892 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
893 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
894 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
895 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
896 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
897 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
898 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
899 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
900 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
901 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
902 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
903 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
904 }
905 if (FiniteOnlyFPMath())
906 Condition = FOC;
907 else
908 Condition = FPC;
909 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000910 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000911 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000912 }
913
Chris Lattnered0110b2006-10-27 21:36:01 +0000914 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
915 BOp->getOperand(1), TBB, FBB, CurBB);
916 SwitchCases.push_back(CB);
917 return;
918 }
919
920 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000921 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000922 TBB, FBB, CurBB);
923 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000924 return;
925 }
926
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000927
928 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000929 MachineFunction::iterator BBI = CurBB;
930 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
931 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
932
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000933 if (Opc == Instruction::Or) {
934 // Codegen X | Y as:
935 // jmp_if_X TBB
936 // jmp TmpBB
937 // TmpBB:
938 // jmp_if_Y TBB
939 // jmp FBB
940 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000941
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000942 // Emit the LHS condition.
943 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
944
945 // Emit the RHS condition into TmpBB.
946 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
947 } else {
948 assert(Opc == Instruction::And && "Unknown merge op!");
949 // Codegen X & Y as:
950 // jmp_if_X TmpBB
951 // jmp FBB
952 // TmpBB:
953 // jmp_if_Y TBB
954 // jmp FBB
955 //
956 // This requires creation of TmpBB after CurBB.
957
958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
960
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
963 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000964}
965
Chris Lattner427301f2006-10-31 22:37:42 +0000966/// If the set of cases should be emitted as a series of branches, return true.
967/// If we should emit this as a bunch of and/or'd together conditions, return
968/// false.
969static bool
970ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
971 if (Cases.size() != 2) return true;
972
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000973 // If this is two comparisons of the same values or'd or and'd together, they
974 // will get folded into a single comparison, so don't emit two blocks.
975 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
976 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
977 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
978 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
979 return false;
980 }
981
Chris Lattner427301f2006-10-31 22:37:42 +0000982 return true;
983}
984
Chris Lattner7a60d912005-01-07 07:47:53 +0000985void SelectionDAGLowering::visitBr(BranchInst &I) {
986 // Update machine-CFG edges.
987 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000988
989 // Figure out which block is immediately after the current one.
990 MachineBasicBlock *NextBlock = 0;
991 MachineFunction::iterator BBI = CurMBB;
992 if (++BBI != CurMBB->getParent()->end())
993 NextBlock = BBI;
994
995 if (I.isUnconditional()) {
996 // If this is not a fall-through branch, emit the branch.
997 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000998 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000999 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001000
Chris Lattner963ddad2006-10-24 17:57:59 +00001001 // Update machine-CFG edges.
1002 CurMBB->addSuccessor(Succ0MBB);
1003
1004 return;
1005 }
1006
1007 // If this condition is one of the special cases we handle, do special stuff
1008 // now.
1009 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001010 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001011
1012 // If this is a series of conditions that are or'd or and'd together, emit
1013 // this as a sequence of branches instead of setcc's with and/or operations.
1014 // For example, instead of something like:
1015 // cmp A, B
1016 // C = seteq
1017 // cmp D, E
1018 // F = setle
1019 // or C, F
1020 // jnz foo
1021 // Emit:
1022 // cmp A, B
1023 // je foo
1024 // cmp D, E
1025 // jle foo
1026 //
1027 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1028 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001029 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001030 BOp->getOpcode() == Instruction::Or)) {
1031 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001032 // If the compares in later blocks need to use values not currently
1033 // exported from this block, export them now. This block should always
1034 // be the first entry.
1035 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1036
Chris Lattner427301f2006-10-31 22:37:42 +00001037 // Allow some cases to be rejected.
1038 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001039 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1040 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1041 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1042 }
1043
1044 // Emit the branch for this block.
1045 visitSwitchCase(SwitchCases[0]);
1046 SwitchCases.erase(SwitchCases.begin());
1047 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001048 }
1049
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001050 // Okay, we decided not to do this, remove any inserted MBB's and clear
1051 // SwitchCases.
1052 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1053 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1054
Chris Lattner427301f2006-10-31 22:37:42 +00001055 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001056 }
1057 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001058
1059 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001060 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001061 Succ0MBB, Succ1MBB, CurMBB);
1062 // Use visitSwitchCase to actually insert the fast branch sequence for this
1063 // cond branch.
1064 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001065}
1066
Nate Begemaned728c12006-03-27 01:32:24 +00001067/// visitSwitchCase - Emits the necessary code to represent a single node in
1068/// the binary search tree resulting from lowering a switch instruction.
1069void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001070 SDOperand Cond;
1071 SDOperand CondLHS = getValue(CB.CmpLHS);
1072
Chris Lattnered0110b2006-10-27 21:36:01 +00001073 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1074 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001075 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001076 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001077 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001078 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1079 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1080 } else
1081 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Anton Korobeynikov70378262007-03-25 15:07:15 +00001082
Nate Begemaned728c12006-03-27 01:32:24 +00001083 // Set NextBlock to be the MBB immediately after the current one, if any.
1084 // This is used to avoid emitting unnecessary branches to the next block.
1085 MachineBasicBlock *NextBlock = 0;
1086 MachineFunction::iterator BBI = CurMBB;
1087 if (++BBI != CurMBB->getParent()->end())
1088 NextBlock = BBI;
1089
1090 // If the lhs block is the next block, invert the condition so that we can
1091 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001092 if (CB.TrueBB == NextBlock) {
1093 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001094 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1095 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1096 }
1097 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001098 DAG.getBasicBlock(CB.TrueBB));
1099 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001100 DAG.setRoot(BrCond);
1101 else
1102 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001103 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001104 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001105 CurMBB->addSuccessor(CB.TrueBB);
1106 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001107}
1108
Anton Korobeynikov70378262007-03-25 15:07:15 +00001109/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001110void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001111 // Emit the code for the jump table
Anton Korobeynikov70378262007-03-25 15:07:15 +00001112 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001113 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001114 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1115 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1116 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1117 Table, Index));
1118 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001119}
1120
Anton Korobeynikov70378262007-03-25 15:07:15 +00001121/// visitJumpTableHeader - This function emits necessary code to produce index
1122/// in the JumpTable from switch case.
1123void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1124 SelectionDAGISel::JumpTableHeader &JTH) {
1125 // Subtract the lowest switch case value from the value being switched on
1126 // and conditional branch to default mbb if the result is greater than the
1127 // difference between smallest and largest cases.
1128 SDOperand SwitchOp = getValue(JTH.SValue);
1129 MVT::ValueType VT = SwitchOp.getValueType();
1130 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1131 DAG.getConstant(JTH.First, VT));
1132
1133 // The SDNode we just created, which holds the value being switched on
1134 // minus the the smallest case value, needs to be copied to a virtual
1135 // register so it can be used as an index into the jump table in a
1136 // subsequent basic block. This value may be smaller or larger than the
1137 // target's pointer type, and therefore require extension or truncating.
1138 if (VT > TLI.getPointerTy())
1139 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1140 else
1141 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1142
1143 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1144 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1145 JT.Reg = JumpTableReg;
1146
1147 // Emit the range check for the jump table, and branch to the default
1148 // block for the switch statement if the value being switched on exceeds
1149 // the largest case in the switch.
1150 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1151 DAG.getConstant(JTH.Last-JTH.First,VT),
1152 ISD::SETUGT);
1153
1154 // Set NextBlock to be the MBB immediately after the current one, if any.
1155 // This is used to avoid emitting unnecessary branches to the next block.
1156 MachineBasicBlock *NextBlock = 0;
1157 MachineFunction::iterator BBI = CurMBB;
1158 if (++BBI != CurMBB->getParent()->end())
1159 NextBlock = BBI;
1160
1161 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1162 DAG.getBasicBlock(JT.Default));
1163
1164 if (JT.MBB == NextBlock)
1165 DAG.setRoot(BrCond);
1166 else
1167 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1168 DAG.getBasicBlock(JT.MBB)));
1169}
1170
1171
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001172void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001173 assert(0 && "Should never be visited directly");
1174}
1175void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001176 // Retrieve successors.
1177 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1178 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1179
Jim Laskey14059d92007-02-25 21:43:59 +00001180 if (!AsTerminator) {
1181 // Mark landing pad so that it doesn't get deleted in branch folding.
1182 LandingPad->setIsLandingPad();
1183
1184 // Insert a label before the invoke call to mark the try range.
1185 // This can be used to detect deletion of the invoke via the
1186 // MachineModuleInfo.
1187 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1188 unsigned BeginLabel = MMI->NextLabelID();
1189 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1190 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001191
Jim Laskey14059d92007-02-25 21:43:59 +00001192 LowerCallTo(I, I.getCalledValue()->getType(),
1193 I.getCallingConv(),
1194 false,
1195 getValue(I.getOperand(0)),
1196 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001197
Jim Laskey14059d92007-02-25 21:43:59 +00001198 // Insert a label before the invoke call to mark the try range.
1199 // This can be used to detect deletion of the invoke via the
1200 // MachineModuleInfo.
1201 unsigned EndLabel = MMI->NextLabelID();
1202 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1203 DAG.getConstant(EndLabel, MVT::i32)));
1204
1205 // Inform MachineModuleInfo of range.
1206 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1207
1208 // Update successor info
1209 CurMBB->addSuccessor(Return);
1210 CurMBB->addSuccessor(LandingPad);
1211 } else {
1212 // Drop into normal successor.
1213 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1214 DAG.getBasicBlock(Return)));
1215 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001216}
1217
1218void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1219}
1220
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001221/// handleSmaaSwitchCaseRange - Emit a series of specific tests (suitable for
1222/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001223bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001224 CaseRecVector& WorkList,
1225 Value* SV,
1226 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001227 Case& BackCase = *(CR.Range.second-1);
1228
1229 // Size is the number of Cases represented by this range.
1230 unsigned Size = CR.Range.second - CR.Range.first;
1231 if (Size >=3)
1232 return false;
1233
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001234 // Get the MachineFunction which holds the current MBB. This is used when
1235 // inserting any additional MBBs necessary to represent the switch.
1236 MachineFunction *CurMF = CurMBB->getParent();
1237
1238 // Figure out which block is immediately after the current one.
1239 MachineBasicBlock *NextBlock = 0;
1240 MachineFunction::iterator BBI = CR.CaseBB;
1241
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001242 if (++BBI != CurMBB->getParent()->end())
1243 NextBlock = BBI;
1244
1245 // TODO: If any two of the cases has the same destination, and if one value
1246 // is the same as the other, but has one bit unset that the other has set,
1247 // use bit manipulation to do two compares at once. For example:
1248 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1249
1250 // Rearrange the case blocks so that the last one falls through if possible.
1251 if (NextBlock && Default != NextBlock && BackCase.second != NextBlock) {
1252 // The last case block won't fall through into 'NextBlock' if we emit the
1253 // branches in this order. See if rearranging a case value would help.
1254 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1255 if (I->second == NextBlock) {
1256 std::swap(*I, BackCase);
1257 break;
1258 }
1259 }
1260 }
1261
1262 // Create a CaseBlock record representing a conditional branch to
1263 // the Case's target mbb if the value being switched on SV is equal
1264 // to C.
1265 MachineBasicBlock *CurBlock = CR.CaseBB;
1266 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1267 MachineBasicBlock *FallThrough;
1268 if (I != E-1) {
1269 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1270 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1271 } else {
1272 // If the last case doesn't match, go to the default block.
1273 FallThrough = Default;
1274 }
1275
1276 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, I->first,
1277 I->second, FallThrough, CurBlock);
1278
1279 // If emitting the first comparison, just call visitSwitchCase to emit the
1280 // code into the current block. Otherwise, push the CaseBlock onto the
1281 // vector to be later processed by SDISel, and insert the node's MBB
1282 // before the next MBB.
1283 if (CurBlock == CurMBB)
1284 visitSwitchCase(CB);
1285 else
1286 SwitchCases.push_back(CB);
1287
1288 CurBlock = FallThrough;
1289 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001290
1291 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001292}
1293
1294/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001295bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001296 CaseRecVector& WorkList,
1297 Value* SV,
1298 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001299 Case& FrontCase = *CR.Range.first;
1300 Case& BackCase = *(CR.Range.second-1);
1301
1302 // Size is the number of Cases represented by this range.
1303 unsigned Size = CR.Range.second - CR.Range.first;
1304
1305 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1306 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1307
1308 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1309 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
1310 Size <= 5)
1311 return false;
1312
1313 double Density = (double)Size / (double)((Last - First) + 1ULL);
1314 if (Density < 0.3125)
1315 return false;
1316
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001317 // Get the MachineFunction which holds the current MBB. This is used when
1318 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001319 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001320
1321 // Figure out which block is immediately after the current one.
1322 MachineBasicBlock *NextBlock = 0;
1323 MachineFunction::iterator BBI = CR.CaseBB;
1324
1325 if (++BBI != CurMBB->getParent()->end())
1326 NextBlock = BBI;
1327
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001328 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1329
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001330 // Create a new basic block to hold the code for loading the address
1331 // of the jump table, and jumping to it. Update successor information;
1332 // we will either branch to the default case for the switch, or the jump
1333 // table.
1334 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1335 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1336 CR.CaseBB->addSuccessor(Default);
1337 CR.CaseBB->addSuccessor(JumpTableBB);
1338
1339 // Build a vector of destination BBs, corresponding to each target
1340 // of the jump table. If the value of the jump table slot corresponds to
1341 // a case statement, push the case's BB onto the vector, otherwise, push
1342 // the default BB.
1343 std::vector<MachineBasicBlock*> DestBBs;
1344 int64_t TEI = First;
1345 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI)
1346 if (cast<ConstantInt>(I->first)->getSExtValue() == TEI) {
1347 DestBBs.push_back(I->second);
1348 ++I;
1349 } else {
1350 DestBBs.push_back(Default);
1351 }
1352
1353 // Update successor info. Add one edge to each unique successor.
1354 // Vector bool would be better, but vector<bool> is really slow.
1355 std::vector<unsigned char> SuccsHandled;
1356 SuccsHandled.resize(CR.CaseBB->getParent()->getNumBlockIDs());
1357
1358 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1359 E = DestBBs.end(); I != E; ++I) {
1360 if (!SuccsHandled[(*I)->getNumber()]) {
1361 SuccsHandled[(*I)->getNumber()] = true;
1362 JumpTableBB->addSuccessor(*I);
1363 }
1364 }
1365
1366 // Create a jump table index for this jump table, or return an existing
1367 // one.
1368 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1369
1370 // Set the jump table information so that we can codegen it as a second
1371 // MachineBasicBlock
1372 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1373 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1374 (CR.CaseBB == CurMBB));
1375 if (CR.CaseBB == CurMBB)
1376 visitJumpTableHeader(JT, JTH);
1377
1378 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001379
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001380 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001381}
1382
1383/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1384/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001385bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001386 CaseRecVector& WorkList,
1387 Value* SV,
1388 MachineBasicBlock* Default) {
1389 // Get the MachineFunction which holds the current MBB. This is used when
1390 // inserting any additional MBBs necessary to represent the switch.
1391 MachineFunction *CurMF = CurMBB->getParent();
1392
1393 // Figure out which block is immediately after the current one.
1394 MachineBasicBlock *NextBlock = 0;
1395 MachineFunction::iterator BBI = CR.CaseBB;
1396
1397 if (++BBI != CurMBB->getParent()->end())
1398 NextBlock = BBI;
1399
1400 Case& FrontCase = *CR.Range.first;
1401 Case& BackCase = *(CR.Range.second-1);
1402 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1403
1404 // Size is the number of Cases represented by this range.
1405 unsigned Size = CR.Range.second - CR.Range.first;
1406
1407 uint64_t First = cast<ConstantInt>(FrontCase.first)->getSExtValue();
1408 uint64_t Last = cast<ConstantInt>(BackCase.first)->getSExtValue();
1409 double Density = 0;
1410 CaseItr Pivot;
1411
1412 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1413 // (heuristically) allow us to emit JumpTable's later.
1414 unsigned LSize = 1;
1415 unsigned RSize = Size-1;
1416 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1417 J!=E; ++I, ++J, ++LSize, --RSize) {
1418 uint64_t LEnd = cast<ConstantInt>(I->first)->getSExtValue();
1419 uint64_t RBegin = cast<ConstantInt>(J->first)->getSExtValue();
1420 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1421 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1422 if (Density < (LDensity + RDensity)) {
1423 Pivot = J;
1424 Density = LDensity + RDensity;
1425 }
1426 }
1427
1428 CaseRange LHSR(CR.Range.first, Pivot);
1429 CaseRange RHSR(Pivot, CR.Range.second);
1430 Constant *C = Pivot->first;
1431 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1432
1433 // We know that we branch to the LHS if the Value being switched on is
1434 // less than the Pivot value, C. We use this to optimize our binary
1435 // tree a bit, by recognizing that if SV is greater than or equal to the
1436 // LHS's Case Value, and that Case Value is exactly one less than the
1437 // Pivot's Value, then we can branch directly to the LHS's Target,
1438 // rather than creating a leaf node for it.
1439 if ((LHSR.second - LHSR.first) == 1 &&
1440 LHSR.first->first == CR.GE &&
1441 cast<ConstantInt>(C)->getZExtValue() ==
1442 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
1443 TrueBB = LHSR.first->second;
1444 } else {
1445 TrueBB = new MachineBasicBlock(LLVMBB);
1446 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1447 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1448 }
1449
1450 // Similar to the optimization above, if the Value being switched on is
1451 // known to be less than the Constant CR.LT, and the current Case Value
1452 // is CR.LT - 1, then we can branch directly to the target block for
1453 // the current Case Value, rather than emitting a RHS leaf node for it.
1454 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1455 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1456 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
1457 FalseBB = RHSR.first->second;
1458 } else {
1459 FalseBB = new MachineBasicBlock(LLVMBB);
1460 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1461 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1462 }
1463
1464 // Create a CaseBlock record representing a conditional branch to
1465 // the LHS node if the value being switched on SV is less than C.
1466 // Otherwise, branch to LHS.
1467 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1468 CR.CaseBB);
1469
1470 if (CR.CaseBB == CurMBB)
1471 visitSwitchCase(CB);
1472 else
1473 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001474
1475 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001476}
1477
Anton Korobeynikov70378262007-03-25 15:07:15 +00001478void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
Nate Begemaned728c12006-03-27 01:32:24 +00001479 // Figure out which block is immediately after the current one.
1480 MachineBasicBlock *NextBlock = 0;
1481 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001482
Chris Lattner6d6fc262006-10-22 21:36:53 +00001483 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1484
Nate Begemaned728c12006-03-27 01:32:24 +00001485 // If there is only the default destination, branch to it if it is not the
1486 // next basic block. Otherwise, just fall through.
1487 if (I.getNumOperands() == 2) {
1488 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001489
Nate Begemaned728c12006-03-27 01:32:24 +00001490 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001491 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001492 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001493 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001494
Chris Lattner6d6fc262006-10-22 21:36:53 +00001495 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001496 return;
1497 }
1498
1499 // If there are any non-default case statements, create a vector of Cases
1500 // representing each one, and sort the vector so that we can efficiently
1501 // create a binary search tree from them.
1502 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001503
Nate Begemaned728c12006-03-27 01:32:24 +00001504 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1505 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1506 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1507 }
1508 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1509
1510 // Get the Value to be switched on and default basic blocks, which will be
1511 // inserted into CaseBlock records, representing basic blocks in the binary
1512 // search tree.
1513 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001514
Nate Begemaned728c12006-03-27 01:32:24 +00001515 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001516 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001517 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1518
1519 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001520 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001521 CaseRec CR = WorkList.back();
1522 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001523
1524 // If the range has few cases (two or less) emit a series of specific
1525 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001526 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1527 continue;
1528
Anton Korobeynikov70378262007-03-25 15:07:15 +00001529 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1530 // target supports indirect branches, then emit a jump table rather than
1531 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001532 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1533 continue;
1534
1535 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1536 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1537 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001538 }
1539}
1540
Anton Korobeynikov70378262007-03-25 15:07:15 +00001541
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001542void SelectionDAGLowering::visitSub(User &I) {
1543 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001544 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001545 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001546 visitVectorBinary(I, ISD::VSUB);
1547 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001548 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1549 if (CFP->isExactlyValue(-0.0)) {
1550 SDOperand Op2 = getValue(I.getOperand(1));
1551 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1552 return;
1553 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001554 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001555 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001556 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001557}
1558
Reid Spencer2eadb532007-01-21 00:29:26 +00001559void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001560 SDOperand Op1 = getValue(I.getOperand(0));
1561 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001562
1563 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001564}
1565
Reid Spencer2eadb532007-01-21 00:29:26 +00001566void
1567SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001568 assert(isa<VectorType>(I.getType()));
1569 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001570 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001571
Reid Spencer2eadb532007-01-21 00:29:26 +00001572 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1573 getValue(I.getOperand(0)),
1574 getValue(I.getOperand(1)),
1575 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1576 Typ));
1577}
1578
1579void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1580 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001581 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001582 visitVectorBinary(I, VectorOp);
1583 else
1584 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001585}
Chris Lattner96c26752005-01-19 22:31:21 +00001586
Nate Begeman127321b2005-11-18 07:42:56 +00001587void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1588 SDOperand Op1 = getValue(I.getOperand(0));
1589 SDOperand Op2 = getValue(I.getOperand(1));
1590
Reid Spencer2341c222007-02-02 02:16:23 +00001591 if (TLI.getShiftAmountTy() < Op2.getValueType())
1592 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1593 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1594 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001595
Chris Lattner7a60d912005-01-07 07:47:53 +00001596 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1597}
1598
Reid Spencerd9436b62006-11-20 01:22:35 +00001599void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001600 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1601 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1602 predicate = IC->getPredicate();
1603 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1604 predicate = ICmpInst::Predicate(IC->getPredicate());
1605 SDOperand Op1 = getValue(I.getOperand(0));
1606 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001607 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001608 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001609 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1610 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1611 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1612 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1613 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1614 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1615 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1616 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1617 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1618 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1619 default:
1620 assert(!"Invalid ICmp predicate value");
1621 Opcode = ISD::SETEQ;
1622 break;
1623 }
1624 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1625}
1626
1627void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001628 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1629 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1630 predicate = FC->getPredicate();
1631 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1632 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001633 SDOperand Op1 = getValue(I.getOperand(0));
1634 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001635 ISD::CondCode Condition, FOC, FPC;
1636 switch (predicate) {
1637 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1638 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1639 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1640 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1641 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1642 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1643 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1644 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1645 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1646 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1647 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1648 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1649 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1650 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1651 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1652 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1653 default:
1654 assert(!"Invalid FCmp predicate value");
1655 FOC = FPC = ISD::SETFALSE;
1656 break;
1657 }
1658 if (FiniteOnlyFPMath())
1659 Condition = FOC;
1660 else
1661 Condition = FPC;
1662 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001663}
1664
1665void SelectionDAGLowering::visitSelect(User &I) {
1666 SDOperand Cond = getValue(I.getOperand(0));
1667 SDOperand TrueVal = getValue(I.getOperand(1));
1668 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001669 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001670 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1671 TrueVal, FalseVal));
1672 } else {
1673 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1674 *(TrueVal.Val->op_end()-2),
1675 *(TrueVal.Val->op_end()-1)));
1676 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001677}
1678
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001679
1680void SelectionDAGLowering::visitTrunc(User &I) {
1681 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1682 SDOperand N = getValue(I.getOperand(0));
1683 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1684 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1685}
1686
1687void SelectionDAGLowering::visitZExt(User &I) {
1688 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1689 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1690 SDOperand N = getValue(I.getOperand(0));
1691 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1692 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1693}
1694
1695void SelectionDAGLowering::visitSExt(User &I) {
1696 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1697 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1698 SDOperand N = getValue(I.getOperand(0));
1699 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1700 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1701}
1702
1703void SelectionDAGLowering::visitFPTrunc(User &I) {
1704 // FPTrunc is never a no-op cast, no need to check
1705 SDOperand N = getValue(I.getOperand(0));
1706 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1707 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1708}
1709
1710void SelectionDAGLowering::visitFPExt(User &I){
1711 // FPTrunc is never a no-op cast, no need to check
1712 SDOperand N = getValue(I.getOperand(0));
1713 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1714 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1715}
1716
1717void SelectionDAGLowering::visitFPToUI(User &I) {
1718 // FPToUI is never a no-op cast, no need to check
1719 SDOperand N = getValue(I.getOperand(0));
1720 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1721 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1722}
1723
1724void SelectionDAGLowering::visitFPToSI(User &I) {
1725 // FPToSI is never a no-op cast, no need to check
1726 SDOperand N = getValue(I.getOperand(0));
1727 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1728 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1729}
1730
1731void SelectionDAGLowering::visitUIToFP(User &I) {
1732 // UIToFP is never a no-op cast, no need to check
1733 SDOperand N = getValue(I.getOperand(0));
1734 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1735 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1736}
1737
1738void SelectionDAGLowering::visitSIToFP(User &I){
1739 // UIToFP is never a no-op cast, no need to check
1740 SDOperand N = getValue(I.getOperand(0));
1741 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1742 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1743}
1744
1745void SelectionDAGLowering::visitPtrToInt(User &I) {
1746 // What to do depends on the size of the integer and the size of the pointer.
1747 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001748 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001749 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001750 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001751 SDOperand Result;
1752 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1753 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1754 else
1755 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1756 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1757 setValue(&I, Result);
1758}
Chris Lattner7a60d912005-01-07 07:47:53 +00001759
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001760void SelectionDAGLowering::visitIntToPtr(User &I) {
1761 // What to do depends on the size of the integer and the size of the pointer.
1762 // We can either truncate, zero extend, or no-op, accordingly.
1763 SDOperand N = getValue(I.getOperand(0));
1764 MVT::ValueType SrcVT = N.getValueType();
1765 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1766 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1767 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1768 else
1769 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1770 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1771}
1772
1773void SelectionDAGLowering::visitBitCast(User &I) {
1774 SDOperand N = getValue(I.getOperand(0));
1775 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001776 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001777 // This is a cast to a vector from something else.
1778 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001779 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001780 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1781 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1782 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1783 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001784 return;
1785 }
1786 MVT::ValueType SrcVT = N.getValueType();
1787 if (SrcVT == MVT::Vector) {
1788 // This is a cast from a vctor to something else.
1789 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001790 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001791 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001792 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001793
1794 // BitCast assures us that source and destination are the same size so this
1795 // is either a BIT_CONVERT or a no-op.
1796 if (DestVT != N.getValueType())
1797 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1798 else
1799 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001800}
1801
Chris Lattner67271862006-03-29 00:11:43 +00001802void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001803 SDOperand InVec = getValue(I.getOperand(0));
1804 SDOperand InVal = getValue(I.getOperand(1));
1805 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1806 getValue(I.getOperand(2)));
1807
Chris Lattner29b23012006-03-19 01:17:20 +00001808 SDOperand Num = *(InVec.Val->op_end()-2);
1809 SDOperand Typ = *(InVec.Val->op_end()-1);
1810 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1811 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001812}
1813
Chris Lattner67271862006-03-29 00:11:43 +00001814void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001815 SDOperand InVec = getValue(I.getOperand(0));
1816 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1817 getValue(I.getOperand(1)));
1818 SDOperand Typ = *(InVec.Val->op_end()-1);
1819 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1820 TLI.getValueType(I.getType()), InVec, InIdx));
1821}
Chris Lattner32206f52006-03-18 01:44:44 +00001822
Chris Lattner098c01e2006-04-08 04:15:24 +00001823void SelectionDAGLowering::visitShuffleVector(User &I) {
1824 SDOperand V1 = getValue(I.getOperand(0));
1825 SDOperand V2 = getValue(I.getOperand(1));
1826 SDOperand Mask = getValue(I.getOperand(2));
1827
1828 SDOperand Num = *(V1.Val->op_end()-2);
1829 SDOperand Typ = *(V2.Val->op_end()-1);
1830 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1831 V1, V2, Mask, Num, Typ));
1832}
1833
1834
Chris Lattner7a60d912005-01-07 07:47:53 +00001835void SelectionDAGLowering::visitGetElementPtr(User &I) {
1836 SDOperand N = getValue(I.getOperand(0));
1837 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001838
1839 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1840 OI != E; ++OI) {
1841 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001842 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001843 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001844 if (Field) {
1845 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001846 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001847 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001848 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001849 }
1850 Ty = StTy->getElementType(Field);
1851 } else {
1852 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001853
Chris Lattner43535a12005-11-09 04:45:33 +00001854 // If this is a constant subscript, handle it quickly.
1855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001856 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001857 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001858 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001859 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1860 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001861 }
Chris Lattner43535a12005-11-09 04:45:33 +00001862
1863 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001864 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001865 SDOperand IdxN = getValue(Idx);
1866
1867 // If the index is smaller or larger than intptr_t, truncate or extend
1868 // it.
1869 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001870 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001871 } else if (IdxN.getValueType() > N.getValueType())
1872 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1873
1874 // If this is a multiply by a power of two, turn it into a shl
1875 // immediately. This is a very common case.
1876 if (isPowerOf2_64(ElementSize)) {
1877 unsigned Amt = Log2_64(ElementSize);
1878 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001879 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001880 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1881 continue;
1882 }
1883
1884 SDOperand Scale = getIntPtrConstant(ElementSize);
1885 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1886 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001887 }
1888 }
1889 setValue(&I, N);
1890}
1891
1892void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1893 // If this is a fixed sized alloca in the entry block of the function,
1894 // allocate it statically on the stack.
1895 if (FuncInfo.StaticAllocaMap.count(&I))
1896 return; // getValue will auto-populate this.
1897
1898 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001899 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001900 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00001901 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00001902 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001903
1904 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001905 MVT::ValueType IntPtr = TLI.getPointerTy();
1906 if (IntPtr < AllocSize.getValueType())
1907 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1908 else if (IntPtr > AllocSize.getValueType())
1909 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001910
Chris Lattnereccb73d2005-01-22 23:04:37 +00001911 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001912 getIntPtrConstant(TySize));
1913
1914 // Handle alignment. If the requested alignment is less than or equal to the
1915 // stack alignment, ignore it and round the size of the allocation up to the
1916 // stack alignment size. If the size is greater than the stack alignment, we
1917 // note this in the DYNAMIC_STACKALLOC node.
1918 unsigned StackAlign =
1919 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1920 if (Align <= StackAlign) {
1921 Align = 0;
1922 // Add SA-1 to the size.
1923 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1924 getIntPtrConstant(StackAlign-1));
1925 // Mask out the low bits for alignment purposes.
1926 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1927 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1928 }
1929
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001930 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001931 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1932 MVT::Other);
1933 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00001934 setValue(&I, DSA);
1935 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001936
1937 // Inform the Frame Information that we have just allocated a variable-sized
1938 // object.
1939 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1940}
1941
Chris Lattner7a60d912005-01-07 07:47:53 +00001942void SelectionDAGLowering::visitLoad(LoadInst &I) {
1943 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001944
Chris Lattner4d9651c2005-01-17 22:19:26 +00001945 SDOperand Root;
1946 if (I.isVolatile())
1947 Root = getRoot();
1948 else {
1949 // Do not serialize non-volatile loads against each other.
1950 Root = DAG.getRoot();
1951 }
Chris Lattner4024c002006-03-15 22:19:46 +00001952
Evan Chenge71fe34d2006-10-09 20:57:25 +00001953 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001954 Root, I.isVolatile()));
1955}
1956
1957SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001958 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001959 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001960 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001961 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001962 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001963 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1964 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001965 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001966 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001967 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001968
Chris Lattner4024c002006-03-15 22:19:46 +00001969 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001970 DAG.setRoot(L.getValue(1));
1971 else
1972 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001973
1974 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001975}
1976
1977
1978void SelectionDAGLowering::visitStore(StoreInst &I) {
1979 Value *SrcV = I.getOperand(0);
1980 SDOperand Src = getValue(SrcV);
1981 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001982 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001983 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001984}
1985
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001986/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1987/// access memory and has no other side effects at all.
1988static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1989#define GET_NO_MEMORY_INTRINSICS
1990#include "llvm/Intrinsics.gen"
1991#undef GET_NO_MEMORY_INTRINSICS
1992 return false;
1993}
1994
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001995// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1996// have any side-effects or if it only reads memory.
1997static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1998#define GET_SIDE_EFFECT_INFO
1999#include "llvm/Intrinsics.gen"
2000#undef GET_SIDE_EFFECT_INFO
2001 return false;
2002}
2003
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002004/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2005/// node.
2006void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2007 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002008 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002009 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002010
2011 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002012 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002013 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2014 if (OnlyLoad) {
2015 // We don't need to serialize loads against other loads.
2016 Ops.push_back(DAG.getRoot());
2017 } else {
2018 Ops.push_back(getRoot());
2019 }
2020 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002021
2022 // Add the intrinsic ID as an integer operand.
2023 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2024
2025 // Add all operands of the call to the operand list.
2026 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2027 SDOperand Op = getValue(I.getOperand(i));
2028
Reid Spencer09575ba2007-02-15 03:39:18 +00002029 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002030 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002031 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002032 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2033
2034 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2035 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2036 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2037 }
2038
2039 assert(TLI.isTypeLegal(Op.getValueType()) &&
2040 "Intrinsic uses a non-legal type?");
2041 Ops.push_back(Op);
2042 }
2043
2044 std::vector<MVT::ValueType> VTs;
2045 if (I.getType() != Type::VoidTy) {
2046 MVT::ValueType VT = TLI.getValueType(I.getType());
2047 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002048 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002049 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2050
2051 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2052 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2053 }
2054
2055 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2056 VTs.push_back(VT);
2057 }
2058 if (HasChain)
2059 VTs.push_back(MVT::Other);
2060
Chris Lattnerbd887772006-08-14 23:53:35 +00002061 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2062
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002063 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002064 SDOperand Result;
2065 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002066 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2067 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002068 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002069 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2070 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002071 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002072 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2073 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002074
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002075 if (HasChain) {
2076 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2077 if (OnlyLoad)
2078 PendingLoads.push_back(Chain);
2079 else
2080 DAG.setRoot(Chain);
2081 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002082 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002083 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002084 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2085 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2086 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2087 DAG.getValueType(EVT));
2088 }
2089 setValue(&I, Result);
2090 }
2091}
2092
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002093/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2094/// we want to emit this as a call to a named external function, return the name
2095/// otherwise lower it and return null.
2096const char *
2097SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2098 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002099 default:
2100 // By default, turn this into a target intrinsic node.
2101 visitTargetIntrinsic(I, Intrinsic);
2102 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002103 case Intrinsic::vastart: visitVAStart(I); return 0;
2104 case Intrinsic::vaend: visitVAEnd(I); return 0;
2105 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002106 case Intrinsic::returnaddress:
2107 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2108 getValue(I.getOperand(1))));
2109 return 0;
2110 case Intrinsic::frameaddress:
2111 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2112 getValue(I.getOperand(1))));
2113 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002114 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002115 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002116 break;
2117 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002118 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002119 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002120 case Intrinsic::memcpy_i32:
2121 case Intrinsic::memcpy_i64:
2122 visitMemIntrinsic(I, ISD::MEMCPY);
2123 return 0;
2124 case Intrinsic::memset_i32:
2125 case Intrinsic::memset_i64:
2126 visitMemIntrinsic(I, ISD::MEMSET);
2127 return 0;
2128 case Intrinsic::memmove_i32:
2129 case Intrinsic::memmove_i64:
2130 visitMemIntrinsic(I, ISD::MEMMOVE);
2131 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002132
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002133 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002134 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002135 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002136 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002137 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002138
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002139 Ops[0] = getRoot();
2140 Ops[1] = getValue(SPI.getLineValue());
2141 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002142
Jim Laskeyc56315c2007-01-26 21:22:28 +00002143 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002144 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002145 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2146
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002147 Ops[3] = DAG.getString(CompileUnit->getFileName());
2148 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002149
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002150 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002151 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002152
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002153 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002154 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002155 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002156 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002157 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002158 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2159 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002160 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002161 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002162 }
2163
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002164 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002165 }
2166 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002167 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002168 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002169 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2170 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002171 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002172 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002173 }
2174
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002175 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002176 }
2177 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002178 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002179 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002180 if (MMI && FSI.getSubprogram() &&
2181 MMI->Verify(FSI.getSubprogram())) {
2182 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002183 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002184 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002185 }
2186
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002187 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002188 }
2189 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002190 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002191 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002192 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002193 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002194 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002195 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002196 }
2197
2198 return 0;
2199 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002200
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002201 case Intrinsic::eh_exception: {
2202 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2203
Jim Laskey504e9942007-02-22 15:38:06 +00002204 if (MMI) {
2205 // Add a label to mark the beginning of the landing pad. Deletion of the
2206 // landing pad can thus be detected via the MachineModuleInfo.
2207 unsigned LabelID = MMI->addLandingPad(CurMBB);
2208 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2209 DAG.getConstant(LabelID, MVT::i32)));
2210
2211 // Mark exception register as live in.
2212 unsigned Reg = TLI.getExceptionAddressRegister();
2213 if (Reg) CurMBB->addLiveIn(Reg);
2214
2215 // Insert the EXCEPTIONADDR instruction.
2216 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2217 SDOperand Ops[1];
2218 Ops[0] = DAG.getRoot();
2219 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2220 setValue(&I, Op);
2221 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002222 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002223 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002224 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002225 return 0;
2226 }
2227
Jim Laskeyd5453d72007-03-01 20:24:30 +00002228 case Intrinsic::eh_selector:
2229 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002230 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2231
Jim Laskey504e9942007-02-22 15:38:06 +00002232 if (MMI) {
2233 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002234 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2235 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2236 isa<Function>(CE->getOperand(0)) &&
2237 "Personality should be a function");
2238 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002239 if (Intrinsic == Intrinsic::eh_filter)
2240 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002241
Jim Laskey504e9942007-02-22 15:38:06 +00002242 // Gather all the type infos for this landing pad and pass them along to
2243 // MachineModuleInfo.
2244 std::vector<GlobalVariable *> TyInfo;
2245 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002246 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2247 if (CE && CE->getOpcode() == Instruction::BitCast &&
2248 isa<GlobalVariable>(CE->getOperand(0))) {
2249 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2250 } else {
2251 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2252 assert(CI && CI->getZExtValue() == 0 &&
2253 "TypeInfo must be a global variable typeinfo or NULL");
2254 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002255 }
Jim Laskey504e9942007-02-22 15:38:06 +00002256 }
2257 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2258
2259 // Mark exception selector register as live in.
2260 unsigned Reg = TLI.getExceptionSelectorRegister();
2261 if (Reg) CurMBB->addLiveIn(Reg);
2262
2263 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002264 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002265 SDOperand Ops[2];
2266 Ops[0] = getValue(I.getOperand(1));
2267 Ops[1] = getRoot();
2268 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2269 setValue(&I, Op);
2270 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002271 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002272 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002273 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002274
2275 return 0;
2276 }
2277
2278 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002279 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002280
Jim Laskey504e9942007-02-22 15:38:06 +00002281 if (MMI) {
2282 // Find the type id for the given typeinfo.
2283 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002284 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2285 if (CE && CE->getOpcode() == Instruction::BitCast &&
2286 isa<GlobalVariable>(CE->getOperand(0))) {
2287 GV = cast<GlobalVariable>(CE->getOperand(0));
2288 } else {
2289 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2290 assert(CI && CI->getZExtValue() == 0 &&
2291 "TypeInfo must be a global variable typeinfo or NULL");
2292 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002293 }
2294
2295 unsigned TypeID = MMI->getTypeIDFor(GV);
2296 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002297 } else {
2298 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002299 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002300
2301 return 0;
2302 }
2303
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002304 case Intrinsic::sqrt_f32:
2305 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002306 setValue(&I, DAG.getNode(ISD::FSQRT,
2307 getValue(I.getOperand(1)).getValueType(),
2308 getValue(I.getOperand(1))));
2309 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002310 case Intrinsic::powi_f32:
2311 case Intrinsic::powi_f64:
2312 setValue(&I, DAG.getNode(ISD::FPOWI,
2313 getValue(I.getOperand(1)).getValueType(),
2314 getValue(I.getOperand(1)),
2315 getValue(I.getOperand(2))));
2316 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002317 case Intrinsic::pcmarker: {
2318 SDOperand Tmp = getValue(I.getOperand(1));
2319 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2320 return 0;
2321 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002322 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002323 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002324 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2325 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2326 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002327 setValue(&I, Tmp);
2328 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002329 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002330 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002331 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002332 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002333 case Intrinsic::bswap_i64:
2334 setValue(&I, DAG.getNode(ISD::BSWAP,
2335 getValue(I.getOperand(1)).getValueType(),
2336 getValue(I.getOperand(1))));
2337 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002338 case Intrinsic::cttz_i8:
2339 case Intrinsic::cttz_i16:
2340 case Intrinsic::cttz_i32:
2341 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002342 setValue(&I, DAG.getNode(ISD::CTTZ,
2343 getValue(I.getOperand(1)).getValueType(),
2344 getValue(I.getOperand(1))));
2345 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002346 case Intrinsic::ctlz_i8:
2347 case Intrinsic::ctlz_i16:
2348 case Intrinsic::ctlz_i32:
2349 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002350 setValue(&I, DAG.getNode(ISD::CTLZ,
2351 getValue(I.getOperand(1)).getValueType(),
2352 getValue(I.getOperand(1))));
2353 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002354 case Intrinsic::ctpop_i8:
2355 case Intrinsic::ctpop_i16:
2356 case Intrinsic::ctpop_i32:
2357 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002358 setValue(&I, DAG.getNode(ISD::CTPOP,
2359 getValue(I.getOperand(1)).getValueType(),
2360 getValue(I.getOperand(1))));
2361 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002362 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002363 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002364 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2365 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002366 setValue(&I, Tmp);
2367 DAG.setRoot(Tmp.getValue(1));
2368 return 0;
2369 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002370 case Intrinsic::stackrestore: {
2371 SDOperand Tmp = getValue(I.getOperand(1));
2372 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002373 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002374 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002375 case Intrinsic::prefetch:
2376 // FIXME: Currently discarding prefetches.
2377 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002378 }
2379}
2380
2381
Jim Laskey31fef782007-02-23 21:45:01 +00002382void SelectionDAGLowering::LowerCallTo(Instruction &I,
2383 const Type *CalledValueTy,
2384 unsigned CallingConv,
2385 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002386 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002387 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002388 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2389
2390 TargetLowering::ArgListTy Args;
2391 TargetLowering::ArgListEntry Entry;
2392 Args.reserve(I.getNumOperands());
2393 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2394 Value *Arg = I.getOperand(i);
2395 SDOperand ArgNode = getValue(Arg);
2396 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00002397 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2398 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002399 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2400 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2401 Args.push_back(Entry);
2402 }
2403
2404 std::pair<SDOperand,SDOperand> Result =
2405 TLI.LowerCallTo(getRoot(), I.getType(),
2406 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002407 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002408 Callee, Args, DAG);
2409 if (I.getType() != Type::VoidTy)
2410 setValue(&I, Result.first);
2411 DAG.setRoot(Result.second);
2412}
2413
2414
Chris Lattner7a60d912005-01-07 07:47:53 +00002415void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002416 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002417 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002418 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002419 if (unsigned IID = F->getIntrinsicID()) {
2420 RenameFn = visitIntrinsicCall(I, IID);
2421 if (!RenameFn)
2422 return;
2423 } else { // Not an LLVM intrinsic.
2424 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002425 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2426 if (I.getNumOperands() == 3 && // Basic sanity checks.
2427 I.getOperand(1)->getType()->isFloatingPoint() &&
2428 I.getType() == I.getOperand(1)->getType() &&
2429 I.getType() == I.getOperand(2)->getType()) {
2430 SDOperand LHS = getValue(I.getOperand(1));
2431 SDOperand RHS = getValue(I.getOperand(2));
2432 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2433 LHS, RHS));
2434 return;
2435 }
2436 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002437 if (I.getNumOperands() == 2 && // Basic sanity checks.
2438 I.getOperand(1)->getType()->isFloatingPoint() &&
2439 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002440 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002441 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2442 return;
2443 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002444 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002445 if (I.getNumOperands() == 2 && // Basic sanity checks.
2446 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002447 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002448 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002449 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2450 return;
2451 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002452 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002453 if (I.getNumOperands() == 2 && // Basic sanity checks.
2454 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002455 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002456 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002457 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2458 return;
2459 }
2460 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002461 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002462 } else if (isa<InlineAsm>(I.getOperand(0))) {
2463 visitInlineAsm(I);
2464 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002465 }
Misha Brukman835702a2005-04-21 22:36:52 +00002466
Chris Lattner18d2b342005-01-08 22:48:57 +00002467 SDOperand Callee;
2468 if (!RenameFn)
2469 Callee = getValue(I.getOperand(0));
2470 else
2471 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002472
Jim Laskey31fef782007-02-23 21:45:01 +00002473 LowerCallTo(I, I.getCalledValue()->getType(),
2474 I.getCallingConv(),
2475 I.isTailCall(),
2476 Callee,
2477 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002478}
2479
Jim Laskey504e9942007-02-22 15:38:06 +00002480
Chris Lattner6f87d182006-02-22 22:37:12 +00002481SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002482 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002483 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2484 Chain = Val.getValue(1);
2485 Flag = Val.getValue(2);
2486
2487 // If the result was expanded, copy from the top part.
2488 if (Regs.size() > 1) {
2489 assert(Regs.size() == 2 &&
2490 "Cannot expand to more than 2 elts yet!");
2491 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002492 Chain = Hi.getValue(1);
2493 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002494 if (DAG.getTargetLoweringInfo().isLittleEndian())
2495 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2496 else
2497 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002498 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002499
Chris Lattner705948d2006-06-08 18:22:48 +00002500 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002501 // appropriate type.
2502 if (RegVT == ValueVT)
2503 return Val;
2504
Chris Lattner77f04792007-03-25 05:00:54 +00002505 if (MVT::isVector(RegVT)) {
2506 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2507 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2508 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2509 MVT::i32),
2510 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2511 }
2512
Chris Lattner705948d2006-06-08 18:22:48 +00002513 if (MVT::isInteger(RegVT)) {
2514 if (ValueVT < RegVT)
2515 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2516 else
2517 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002518 }
Chris Lattner77f04792007-03-25 05:00:54 +00002519
2520 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2521 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002522}
2523
Chris Lattner571d9642006-02-23 19:21:04 +00002524/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2525/// specified value into the registers specified by this object. This uses
2526/// Chain/Flag as the input and updates them for the output Chain/Flag.
2527void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002528 SDOperand &Chain, SDOperand &Flag,
2529 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002530 if (Regs.size() == 1) {
2531 // If there is a single register and the types differ, this must be
2532 // a promotion.
2533 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002534 if (MVT::isVector(RegVT)) {
2535 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2536 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2537 } else if (MVT::isInteger(RegVT)) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002538 if (RegVT < ValueVT)
2539 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2540 else
2541 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2542 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002543 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2544 }
2545 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2546 Flag = Chain.getValue(1);
2547 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002548 std::vector<unsigned> R(Regs);
2549 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2550 std::reverse(R.begin(), R.end());
2551
2552 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002553 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002554 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002555 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002556 Flag = Chain.getValue(1);
2557 }
2558 }
2559}
Chris Lattner6f87d182006-02-22 22:37:12 +00002560
Chris Lattner571d9642006-02-23 19:21:04 +00002561/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2562/// operand list. This adds the code marker and includes the number of
2563/// values added into it.
2564void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002565 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002566 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2567 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2568 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2569}
Chris Lattner6f87d182006-02-22 22:37:12 +00002570
2571/// isAllocatableRegister - If the specified register is safe to allocate,
2572/// i.e. it isn't a stack pointer or some other special register, return the
2573/// register class for the register. Otherwise, return null.
2574static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002575isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2576 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002577 MVT::ValueType FoundVT = MVT::Other;
2578 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002579 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2580 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002581 MVT::ValueType ThisVT = MVT::Other;
2582
Chris Lattnerb1124f32006-02-22 23:09:03 +00002583 const TargetRegisterClass *RC = *RCI;
2584 // If none of the the value types for this register class are valid, we
2585 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002586 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2587 I != E; ++I) {
2588 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002589 // If we have already found this register in a different register class,
2590 // choose the one with the largest VT specified. For example, on
2591 // PowerPC, we favor f64 register classes over f32.
2592 if (FoundVT == MVT::Other ||
2593 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2594 ThisVT = *I;
2595 break;
2596 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002597 }
2598 }
2599
Chris Lattnerbec582f2006-04-02 00:24:45 +00002600 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002601
Chris Lattner6f87d182006-02-22 22:37:12 +00002602 // NOTE: This isn't ideal. In particular, this might allocate the
2603 // frame pointer in functions that need it (due to them not being taken
2604 // out of allocation, because a variable sized allocation hasn't been seen
2605 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002606 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2607 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002608 if (*I == Reg) {
2609 // We found a matching register class. Keep looking at others in case
2610 // we find one with larger registers that this physreg is also in.
2611 FoundRC = RC;
2612 FoundVT = ThisVT;
2613 break;
2614 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002615 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002616 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002617}
2618
2619RegsForValue SelectionDAGLowering::
2620GetRegistersForValue(const std::string &ConstrCode,
2621 MVT::ValueType VT, bool isOutReg, bool isInReg,
2622 std::set<unsigned> &OutputRegs,
2623 std::set<unsigned> &InputRegs) {
2624 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2625 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2626 std::vector<unsigned> Regs;
2627
2628 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2629 MVT::ValueType RegVT;
2630 MVT::ValueType ValueVT = VT;
2631
Chris Lattner55402d42006-11-02 01:41:49 +00002632 // If this is a constraint for a specific physical register, like {r17},
2633 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002634 if (PhysReg.first) {
2635 if (VT == MVT::Other)
2636 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002637
2638 // Get the actual register value type. This is important, because the user
2639 // may have asked for (e.g.) the AX register in i32 type. We need to
2640 // remember that AX is actually i16 to get the right extension.
2641 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002642
2643 // This is a explicit reference to a physical register.
2644 Regs.push_back(PhysReg.first);
2645
2646 // If this is an expanded reference, add the rest of the regs to Regs.
2647 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002648 TargetRegisterClass::iterator I = PhysReg.second->begin();
2649 TargetRegisterClass::iterator E = PhysReg.second->end();
2650 for (; *I != PhysReg.first; ++I)
2651 assert(I != E && "Didn't find reg!");
2652
2653 // Already added the first reg.
2654 --NumRegs; ++I;
2655 for (; NumRegs; --NumRegs, ++I) {
2656 assert(I != E && "Ran out of registers to allocate!");
2657 Regs.push_back(*I);
2658 }
2659 }
2660 return RegsForValue(Regs, RegVT, ValueVT);
2661 }
2662
Chris Lattner55402d42006-11-02 01:41:49 +00002663 // Otherwise, if this was a reference to an LLVM register class, create vregs
2664 // for this reference.
2665 std::vector<unsigned> RegClassRegs;
2666 if (PhysReg.second) {
2667 // If this is an early clobber or tied register, our regalloc doesn't know
2668 // how to maintain the constraint. If it isn't, go ahead and create vreg
2669 // and let the regalloc do the right thing.
2670 if (!isOutReg || !isInReg) {
2671 if (VT == MVT::Other)
2672 ValueVT = *PhysReg.second->vt_begin();
2673 RegVT = *PhysReg.second->vt_begin();
2674
2675 // Create the appropriate number of virtual registers.
2676 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2677 for (; NumRegs; --NumRegs)
2678 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2679
2680 return RegsForValue(Regs, RegVT, ValueVT);
2681 }
2682
2683 // Otherwise, we can't allocate it. Let the code below figure out how to
2684 // maintain these constraints.
2685 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2686
2687 } else {
2688 // This is a reference to a register class that doesn't directly correspond
2689 // to an LLVM register class. Allocate NumRegs consecutive, available,
2690 // registers from the class.
2691 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2692 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002693
2694 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2695 MachineFunction &MF = *CurMBB->getParent();
2696 unsigned NumAllocated = 0;
2697 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2698 unsigned Reg = RegClassRegs[i];
2699 // See if this register is available.
2700 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2701 (isInReg && InputRegs.count(Reg))) { // Already used.
2702 // Make sure we find consecutive registers.
2703 NumAllocated = 0;
2704 continue;
2705 }
2706
2707 // Check to see if this register is allocatable (i.e. don't give out the
2708 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002709 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002710 if (!RC) {
2711 // Make sure we find consecutive registers.
2712 NumAllocated = 0;
2713 continue;
2714 }
2715
2716 // Okay, this register is good, we can use it.
2717 ++NumAllocated;
2718
2719 // If we allocated enough consecutive
2720 if (NumAllocated == NumRegs) {
2721 unsigned RegStart = (i-NumAllocated)+1;
2722 unsigned RegEnd = i+1;
2723 // Mark all of the allocated registers used.
2724 for (unsigned i = RegStart; i != RegEnd; ++i) {
2725 unsigned Reg = RegClassRegs[i];
2726 Regs.push_back(Reg);
2727 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2728 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2729 }
2730
2731 return RegsForValue(Regs, *RC->vt_begin(), VT);
2732 }
2733 }
2734
2735 // Otherwise, we couldn't allocate enough registers for this.
2736 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002737}
2738
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002739/// getConstraintGenerality - Return an integer indicating how general CT is.
2740static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2741 switch (CT) {
2742 default: assert(0 && "Unknown constraint type!");
2743 case TargetLowering::C_Other:
2744 case TargetLowering::C_Unknown:
2745 return 0;
2746 case TargetLowering::C_Register:
2747 return 1;
2748 case TargetLowering::C_RegisterClass:
2749 return 2;
2750 case TargetLowering::C_Memory:
2751 return 3;
2752 }
2753}
2754
2755static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2756 const TargetLowering &TLI) {
2757 assert(!C.empty() && "Must have at least one constraint");
2758 if (C.size() == 1) return C[0];
2759
2760 std::string *Current = &C[0];
2761 // If we have multiple constraints, try to pick the most general one ahead
2762 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00002763 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002764 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002765 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002766 if (getConstraintGenerality(ThisFlavor) >
2767 getConstraintGenerality(Flavor)) {
2768 // This constraint letter is more general than the previous one,
2769 // use it.
2770 Flavor = ThisFlavor;
2771 Current = &C[j];
2772 }
2773 }
2774 return *Current;
2775}
2776
Chris Lattner6f87d182006-02-22 22:37:12 +00002777
Chris Lattner476e67b2006-01-26 22:24:51 +00002778/// visitInlineAsm - Handle a call to an InlineAsm object.
2779///
2780void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2781 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2782
2783 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2784 MVT::Other);
2785
Chris Lattner3a5ed552006-02-01 01:28:23 +00002786 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002787 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002788
2789 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2790 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2791 /// if it is a def of that register.
2792 std::vector<SDOperand> AsmNodeOperands;
2793 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2794 AsmNodeOperands.push_back(AsmStr);
2795
2796 SDOperand Chain = getRoot();
2797 SDOperand Flag;
2798
Chris Lattner1558fc62006-02-01 18:59:47 +00002799 // We fully assign registers here at isel time. This is not optimal, but
2800 // should work. For register classes that correspond to LLVM classes, we
2801 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2802 // over the constraints, collecting fixed registers that we know we can't use.
2803 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002804 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002805 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002806 std::string ConstraintCode =
2807 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002808
Chris Lattner7ad77df2006-02-22 00:56:39 +00002809 MVT::ValueType OpVT;
2810
2811 // Compute the value type for each operand and add it to ConstraintVTs.
2812 switch (Constraints[i].Type) {
2813 case InlineAsm::isOutput:
2814 if (!Constraints[i].isIndirectOutput) {
2815 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2816 OpVT = TLI.getValueType(I.getType());
2817 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002818 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002819 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2820 OpNum++; // Consumes a call operand.
2821 }
2822 break;
2823 case InlineAsm::isInput:
2824 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2825 OpNum++; // Consumes a call operand.
2826 break;
2827 case InlineAsm::isClobber:
2828 OpVT = MVT::Other;
2829 break;
2830 }
2831
2832 ConstraintVTs.push_back(OpVT);
2833
Chris Lattner6f87d182006-02-22 22:37:12 +00002834 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2835 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002836
Chris Lattner6f87d182006-02-22 22:37:12 +00002837 // Build a list of regs that this operand uses. This always has a single
2838 // element for promoted/expanded operands.
2839 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2840 false, false,
2841 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002842
2843 switch (Constraints[i].Type) {
2844 case InlineAsm::isOutput:
2845 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002846 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002847 // If this is an early-clobber output, it cannot be assigned to the same
2848 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002849 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002850 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002851 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002852 case InlineAsm::isInput:
2853 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002854 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002855 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002856 case InlineAsm::isClobber:
2857 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002858 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2859 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002860 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002861 }
2862 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002863
Chris Lattner5c79f982006-02-21 23:12:12 +00002864 // Loop over all of the inputs, copying the operand values into the
2865 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002866 RegsForValue RetValRegs;
2867 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002868 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002869
Chris Lattner2e56e892006-01-31 02:03:41 +00002870 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002871 std::string ConstraintCode =
2872 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002873
Chris Lattner3a5ed552006-02-01 01:28:23 +00002874 switch (Constraints[i].Type) {
2875 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002876 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2877 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002878 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00002879
2880 if (CTy == TargetLowering::C_Memory) {
2881 // Memory output.
2882 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2883
2884 // Check that the operand (the address to store to) isn't a float.
2885 if (!MVT::isInteger(InOperandVal.getValueType()))
2886 assert(0 && "MATCH FAIL!");
2887
2888 if (!Constraints[i].isIndirectOutput)
2889 assert(0 && "MATCH FAIL!");
2890
2891 OpNum++; // Consumes a call operand.
2892
2893 // Extend/truncate to the right pointer type if needed.
2894 MVT::ValueType PtrType = TLI.getPointerTy();
2895 if (InOperandVal.getValueType() < PtrType)
2896 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2897 else if (InOperandVal.getValueType() > PtrType)
2898 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2899
2900 // Add information to the INLINEASM node to know about this output.
2901 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2902 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2903 AsmNodeOperands.push_back(InOperandVal);
2904 break;
2905 }
2906
2907 // Otherwise, this is a register output.
2908 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2909
Chris Lattner6f87d182006-02-22 22:37:12 +00002910 // If this is an early-clobber output, or if there is an input
2911 // constraint that matches this, we need to reserve the input register
2912 // so no other inputs allocate to it.
2913 bool UsesInputRegister = false;
2914 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2915 UsesInputRegister = true;
2916
2917 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002918 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002919 RegsForValue Regs =
2920 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2921 true, UsesInputRegister,
2922 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002923 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002924 cerr << "Couldn't allocate output reg for contraint '"
2925 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002926 exit(1);
2927 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002928
Chris Lattner3a5ed552006-02-01 01:28:23 +00002929 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002930 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002931 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002932 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002933 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002934 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002935 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2936 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002937 OpNum++; // Consumes a call operand.
2938 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002939
2940 // Add information to the INLINEASM node to know that this register is
2941 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002942 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002943 break;
2944 }
2945 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002946 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002947 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002948
Chris Lattner7f5880b2006-02-02 00:25:23 +00002949 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2950 // If this is required to match an output register we have already set,
2951 // just use its register.
2952 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002953
Chris Lattner571d9642006-02-23 19:21:04 +00002954 // Scan until we find the definition we already emitted of this operand.
2955 // When we find it, create a RegsForValue operand.
2956 unsigned CurOp = 2; // The first operand.
2957 for (; OperandNo; --OperandNo) {
2958 // Advance to the next operand.
2959 unsigned NumOps =
2960 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002961 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2962 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002963 "Skipped past definitions?");
2964 CurOp += (NumOps>>3)+1;
2965 }
2966
2967 unsigned NumOps =
2968 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00002969 if ((NumOps & 7) == 2 /*REGDEF*/) {
2970 // Add NumOps>>3 registers to MatchedRegs.
2971 RegsForValue MatchedRegs;
2972 MatchedRegs.ValueVT = InOperandVal.getValueType();
2973 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2974 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2975 unsigned Reg =
2976 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2977 MatchedRegs.Regs.push_back(Reg);
2978 }
Chris Lattner571d9642006-02-23 19:21:04 +00002979
Chris Lattnere3eeb242007-02-01 01:21:12 +00002980 // Use the produced MatchedRegs object to
2981 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2982 TLI.getPointerTy());
2983 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2984 break;
2985 } else {
2986 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2987 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00002988 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00002989 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002990
2991 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2992 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00002993 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00002994
2995 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002996 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2997 ConstraintCode[0], DAG);
2998 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002999 cerr << "Invalid operand for inline asm constraint '"
3000 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003001 exit(1);
3002 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003003
3004 // Add information to the INLINEASM node to know about this input.
3005 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3006 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3007 AsmNodeOperands.push_back(InOperandVal);
3008 break;
3009 } else if (CTy == TargetLowering::C_Memory) {
3010 // Memory input.
3011
Chris Lattnerce8aba02007-03-08 22:29:47 +00003012 // If the operand is a float, spill to a constant pool entry to get its
3013 // address.
3014 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3015 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3016
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003017 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00003018 cerr << "Match failed, cannot handle this yet!\n";
3019 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003020 exit(1);
3021 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003022
3023 // Extend/truncate to the right pointer type if needed.
3024 MVT::ValueType PtrType = TLI.getPointerTy();
3025 if (InOperandVal.getValueType() < PtrType)
3026 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3027 else if (InOperandVal.getValueType() > PtrType)
3028 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3029
3030 // Add information to the INLINEASM node to know about this input.
3031 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3032 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3033 AsmNodeOperands.push_back(InOperandVal);
3034 break;
3035 }
3036
3037 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3038
3039 // Copy the input into the appropriate registers.
3040 RegsForValue InRegs =
3041 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3042 false, true, OutputRegs, InputRegs);
3043 // FIXME: should be match fail.
3044 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3045
Evan Chengef9e07d2006-06-15 08:11:54 +00003046 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003047
3048 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003049 break;
3050 }
Chris Lattner571d9642006-02-23 19:21:04 +00003051 case InlineAsm::isClobber: {
3052 RegsForValue ClobberedRegs =
3053 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3054 OutputRegs, InputRegs);
3055 // Add the clobbered value to the operand list, so that the register
3056 // allocator is aware that the physreg got clobbered.
3057 if (!ClobberedRegs.Regs.empty())
3058 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003059 break;
3060 }
Chris Lattner571d9642006-02-23 19:21:04 +00003061 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003062 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003063
3064 // Finish up input operands.
3065 AsmNodeOperands[0] = Chain;
3066 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3067
Chris Lattnerbd887772006-08-14 23:53:35 +00003068 Chain = DAG.getNode(ISD::INLINEASM,
3069 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003070 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003071 Flag = Chain.getValue(1);
3072
Chris Lattner2e56e892006-01-31 02:03:41 +00003073 // If this asm returns a register value, copy the result from that register
3074 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003075 if (!RetValRegs.Regs.empty())
3076 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00003077
Chris Lattner2e56e892006-01-31 02:03:41 +00003078 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3079
3080 // Process indirect outputs, first output all of the flagged copies out of
3081 // physregs.
3082 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003083 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003084 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003085 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3086 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003087 }
3088
3089 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003090 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003091 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00003092 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003093 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003094 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003095 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003096 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3097 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003098 DAG.setRoot(Chain);
3099}
3100
3101
Chris Lattner7a60d912005-01-07 07:47:53 +00003102void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3103 SDOperand Src = getValue(I.getOperand(0));
3104
3105 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003106
3107 if (IntPtr < Src.getValueType())
3108 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3109 else if (IntPtr > Src.getValueType())
3110 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003111
3112 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003113 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003114 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3115 Src, getIntPtrConstant(ElementSize));
3116
Reid Spencere63b6512006-12-31 05:55:36 +00003117 TargetLowering::ArgListTy Args;
3118 TargetLowering::ArgListEntry Entry;
3119 Entry.Node = Src;
3120 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003121 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003122
3123 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003124 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003125 DAG.getExternalSymbol("malloc", IntPtr),
3126 Args, DAG);
3127 setValue(&I, Result.first); // Pointers always fit in registers
3128 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003129}
3130
3131void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003132 TargetLowering::ArgListTy Args;
3133 TargetLowering::ArgListEntry Entry;
3134 Entry.Node = getValue(I.getOperand(0));
3135 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003136 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003137 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003138 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003139 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003140 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3141 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003142}
3143
Chris Lattner13d7c252005-08-26 20:54:47 +00003144// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3145// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3146// instructions are special in various ways, which require special support to
3147// insert. The specified MachineInstr is created but not inserted into any
3148// basic blocks, and the scheduler passes ownership of it to this method.
3149MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3150 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003151 cerr << "If a target marks an instruction with "
3152 << "'usesCustomDAGSchedInserter', it must implement "
3153 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003154 abort();
3155 return 0;
3156}
3157
Chris Lattner58cfd792005-01-09 00:00:49 +00003158void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003159 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3160 getValue(I.getOperand(1)),
3161 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003162}
3163
3164void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003165 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3166 getValue(I.getOperand(0)),
3167 DAG.getSrcValue(I.getOperand(0)));
3168 setValue(&I, V);
3169 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003170}
3171
3172void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003173 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3174 getValue(I.getOperand(1)),
3175 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003176}
3177
3178void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003179 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3180 getValue(I.getOperand(1)),
3181 getValue(I.getOperand(2)),
3182 DAG.getSrcValue(I.getOperand(1)),
3183 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003184}
3185
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003186/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3187/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3188static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3189 unsigned &i, SelectionDAG &DAG,
3190 TargetLowering &TLI) {
3191 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3192 return SDOperand(Arg, i++);
3193
3194 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3195 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3196 if (NumVals == 1) {
3197 return DAG.getNode(ISD::BIT_CONVERT, VT,
3198 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3199 } else if (NumVals == 2) {
3200 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3201 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3202 if (!TLI.isLittleEndian())
3203 std::swap(Lo, Hi);
3204 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3205 } else {
3206 // Value scalarized into many values. Unimp for now.
3207 assert(0 && "Cannot expand i64 -> i16 yet!");
3208 }
3209 return SDOperand();
3210}
3211
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003212/// TargetLowering::LowerArguments - This is the default LowerArguments
3213/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003214/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3215/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003216std::vector<SDOperand>
3217TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003218 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003219 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3220 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003221 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003222 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3223 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3224
3225 // Add one result value for each formal argument.
3226 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003227 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003228 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3229 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003230 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003231 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003232 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003233 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003234
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003235 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3236 // that is zero extended!
3237 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003238 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003239 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003240 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003241 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003242 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003243 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003244 Flags |= ISD::ParamFlags::StructReturn;
3245 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003246
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003247 switch (getTypeAction(VT)) {
3248 default: assert(0 && "Unknown type action!");
3249 case Legal:
3250 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003251 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003252 break;
3253 case Promote:
3254 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003255 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003256 break;
3257 case Expand:
3258 if (VT != MVT::Vector) {
3259 // If this is a large integer, it needs to be broken up into small
3260 // integers. Figure out what the destination type is and how many small
3261 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003262 MVT::ValueType NVT = getTypeToExpandTo(VT);
3263 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003264 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003265 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003266 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003267 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003268 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3269 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003270 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3271 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003272 } else {
3273 // Otherwise, this is a vector type. We only support legal vectors
3274 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003275 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3276 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003277
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003278 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003279 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003280 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3281 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3282 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003283 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003284 } else {
3285 assert(0 && "Don't support illegal by-val vector arguments yet!");
3286 }
3287 }
3288 break;
3289 }
3290 }
Evan Cheng9618df12006-04-25 23:03:35 +00003291
Chris Lattner3d826992006-05-16 06:45:34 +00003292 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003293
3294 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003295 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3296 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003297 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003298
3299 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003300
3301 // Set up the return result vector.
3302 Ops.clear();
3303 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003304 unsigned Idx = 1;
3305 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3306 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003307 MVT::ValueType VT = getValueType(I->getType());
3308
3309 switch (getTypeAction(VT)) {
3310 default: assert(0 && "Unknown type action!");
3311 case Legal:
3312 Ops.push_back(SDOperand(Result, i++));
3313 break;
3314 case Promote: {
3315 SDOperand Op(Result, i++);
3316 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00003317 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3318 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3319 DAG.getValueType(VT));
3320 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3321 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3322 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003323 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3324 } else {
3325 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3326 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3327 }
3328 Ops.push_back(Op);
3329 break;
3330 }
3331 case Expand:
3332 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003333 // If this is a large integer or a floating point node that needs to be
3334 // expanded, it needs to be reassembled from small integers. Figure out
3335 // what the source elt type is and how many small integers it is.
3336 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003337 } else {
3338 // Otherwise, this is a vector type. We only support legal vectors
3339 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003340 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003341 unsigned NumElems = PTy->getNumElements();
3342 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003343
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003344 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003345 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003346 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003347 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003348 SDOperand N = SDOperand(Result, i++);
3349 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003350 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3351 DAG.getConstant(NumElems, MVT::i32),
3352 DAG.getValueType(getValueType(EltTy)));
3353 Ops.push_back(N);
3354 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003355 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003356 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003357 }
3358 }
3359 break;
3360 }
3361 }
3362 return Ops;
3363}
3364
Chris Lattneraaa23d92006-05-16 22:53:20 +00003365
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003366/// ExpandScalarCallArgs - Recursively expand call argument node by
3367/// bit_converting it or extract a pair of elements from the larger node.
3368static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003369 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003370 SmallVector<SDOperand, 32> &Ops,
3371 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003372 TargetLowering &TLI,
3373 bool isFirst = true) {
3374
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003375 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003376 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003377 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003378 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3379 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003380 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003381 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003382 return;
3383 }
3384
3385 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3386 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3387 if (NumVals == 1) {
3388 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003389 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003390 } else if (NumVals == 2) {
3391 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3392 DAG.getConstant(0, TLI.getPointerTy()));
3393 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3394 DAG.getConstant(1, TLI.getPointerTy()));
3395 if (!TLI.isLittleEndian())
3396 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003397 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3398 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003399 } else {
3400 // Value scalarized into many values. Unimp for now.
3401 assert(0 && "Cannot expand i64 -> i16 yet!");
3402 }
3403}
3404
Chris Lattneraaa23d92006-05-16 22:53:20 +00003405/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3406/// implementation, which just inserts an ISD::CALL node, which is later custom
3407/// lowered by the target to something concrete. FIXME: When all targets are
3408/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3409std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003410TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3411 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003412 unsigned CallingConv, bool isTailCall,
3413 SDOperand Callee,
3414 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003415 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003416 Ops.push_back(Chain); // Op#0 - Chain
3417 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3418 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3419 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3420 Ops.push_back(Callee);
3421
3422 // Handle all of the outgoing arguments.
3423 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003424 MVT::ValueType VT = getValueType(Args[i].Ty);
3425 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003426 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003427 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003428 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003429
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003430 if (Args[i].isSExt)
3431 Flags |= ISD::ParamFlags::SExt;
3432 if (Args[i].isZExt)
3433 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003434 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003435 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003436 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003437 Flags |= ISD::ParamFlags::StructReturn;
3438 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003439
Chris Lattneraaa23d92006-05-16 22:53:20 +00003440 switch (getTypeAction(VT)) {
3441 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003442 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003443 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003444 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003445 break;
3446 case Promote:
3447 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003448 unsigned ExtOp;
3449 if (Args[i].isSExt)
3450 ExtOp = ISD::SIGN_EXTEND;
3451 else if (Args[i].isZExt)
3452 ExtOp = ISD::ZERO_EXTEND;
3453 else
3454 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003455 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3456 } else {
3457 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3458 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3459 }
3460 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003461 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003462 break;
3463 case Expand:
3464 if (VT != MVT::Vector) {
3465 // If this is a large integer, it needs to be broken down into small
3466 // integers. Figure out what the source elt type is and how many small
3467 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003468 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003469 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003470 // Otherwise, this is a vector type. We only support legal vectors
3471 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003472 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003473 unsigned NumElems = PTy->getNumElements();
3474 const Type *EltTy = PTy->getElementType();
3475
3476 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003477 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003478 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003479 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003480 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003481 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3482 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003483 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003484 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003485 assert(0 && "Don't support illegal by-val vector call args yet!");
3486 abort();
3487 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003488 }
3489 break;
3490 }
3491 }
3492
3493 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003494 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003495
3496 if (RetTy != Type::VoidTy) {
3497 MVT::ValueType VT = getValueType(RetTy);
3498 switch (getTypeAction(VT)) {
3499 default: assert(0 && "Unknown type action!");
3500 case Legal:
3501 RetTys.push_back(VT);
3502 break;
3503 case Promote:
3504 RetTys.push_back(getTypeToTransformTo(VT));
3505 break;
3506 case Expand:
3507 if (VT != MVT::Vector) {
3508 // If this is a large integer, it needs to be reassembled from small
3509 // integers. Figure out what the source elt type is and how many small
3510 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003511 MVT::ValueType NVT = getTypeToExpandTo(VT);
3512 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003513 for (unsigned i = 0; i != NumVals; ++i)
3514 RetTys.push_back(NVT);
3515 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003516 // Otherwise, this is a vector type. We only support legal vectors
3517 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003518 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003519 unsigned NumElems = PTy->getNumElements();
3520 const Type *EltTy = PTy->getElementType();
3521
3522 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003523 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003524 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3525 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3526 RetTys.push_back(TVT);
3527 } else {
3528 assert(0 && "Don't support illegal by-val vector call results yet!");
3529 abort();
3530 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003531 }
3532 }
3533 }
3534
3535 RetTys.push_back(MVT::Other); // Always has a chain.
3536
3537 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003538 SDOperand Res = DAG.getNode(ISD::CALL,
3539 DAG.getVTList(&RetTys[0], RetTys.size()),
3540 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003541
3542 // This returns a pair of operands. The first element is the
3543 // return value for the function (if RetTy is not VoidTy). The second
3544 // element is the outgoing token chain.
3545 SDOperand ResVal;
3546 if (RetTys.size() != 1) {
3547 MVT::ValueType VT = getValueType(RetTy);
3548 if (RetTys.size() == 2) {
3549 ResVal = Res;
3550
3551 // If this value was promoted, truncate it down.
3552 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003553 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003554 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003555 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003556 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3557 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003558
3559 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003560 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003561 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003562 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003563 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3564 // "N x PTyElementVT" MVT::Vector type.
3565 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003566 DAG.getConstant(NumElems, MVT::i32),
3567 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003568 } else {
3569 abort();
3570 }
3571 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003572 unsigned AssertOp = ISD::AssertSext;
3573 if (!RetTyIsSigned)
3574 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003575 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3576 DAG.getValueType(VT));
3577 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3578 } else {
3579 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003580 if (getTypeAction(VT) == Expand)
3581 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3582 else
3583 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003584 }
3585 }
3586 } else if (RetTys.size() == 3) {
3587 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3588 Res.getValue(0), Res.getValue(1));
3589
3590 } else {
3591 assert(0 && "Case not handled yet!");
3592 }
3593 }
3594
3595 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3596}
3597
Chris Lattner29dcc712005-05-14 05:50:48 +00003598SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003599 assert(0 && "LowerOperation not implemented for this target!");
3600 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003601 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003602}
3603
Nate Begeman595ec732006-01-28 03:14:31 +00003604SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3605 SelectionDAG &DAG) {
3606 assert(0 && "CustomPromoteOperation not implemented for this target!");
3607 abort();
3608 return SDOperand();
3609}
3610
Evan Cheng6781b6e2006-02-15 21:59:04 +00003611/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003612/// operand.
3613static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003614 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003615 MVT::ValueType CurVT = VT;
3616 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3617 uint64_t Val = C->getValue() & 255;
3618 unsigned Shift = 8;
3619 while (CurVT != MVT::i8) {
3620 Val = (Val << Shift) | Val;
3621 Shift <<= 1;
3622 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003623 }
3624 return DAG.getConstant(Val, VT);
3625 } else {
3626 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3627 unsigned Shift = 8;
3628 while (CurVT != MVT::i8) {
3629 Value =
3630 DAG.getNode(ISD::OR, VT,
3631 DAG.getNode(ISD::SHL, VT, Value,
3632 DAG.getConstant(Shift, MVT::i8)), Value);
3633 Shift <<= 1;
3634 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003635 }
3636
3637 return Value;
3638 }
3639}
3640
Evan Cheng6781b6e2006-02-15 21:59:04 +00003641/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3642/// used when a memcpy is turned into a memset when the source is a constant
3643/// string ptr.
3644static SDOperand getMemsetStringVal(MVT::ValueType VT,
3645 SelectionDAG &DAG, TargetLowering &TLI,
3646 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003647 uint64_t Val = 0;
3648 unsigned MSB = getSizeInBits(VT) / 8;
3649 if (TLI.isLittleEndian())
3650 Offset = Offset + MSB - 1;
3651 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003652 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003653 Offset += TLI.isLittleEndian() ? -1 : 1;
3654 }
3655 return DAG.getConstant(Val, VT);
3656}
3657
Evan Cheng81fcea82006-02-14 08:22:34 +00003658/// getMemBasePlusOffset - Returns base and offset node for the
3659static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3660 SelectionDAG &DAG, TargetLowering &TLI) {
3661 MVT::ValueType VT = Base.getValueType();
3662 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3663}
3664
Evan Chengdb2a7a72006-02-14 20:12:38 +00003665/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003666/// to replace the memset / memcpy is below the threshold. It also returns the
3667/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003668static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3669 unsigned Limit, uint64_t Size,
3670 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003671 MVT::ValueType VT;
3672
3673 if (TLI.allowsUnalignedMemoryAccesses()) {
3674 VT = MVT::i64;
3675 } else {
3676 switch (Align & 7) {
3677 case 0:
3678 VT = MVT::i64;
3679 break;
3680 case 4:
3681 VT = MVT::i32;
3682 break;
3683 case 2:
3684 VT = MVT::i16;
3685 break;
3686 default:
3687 VT = MVT::i8;
3688 break;
3689 }
3690 }
3691
Evan Chengd5026102006-02-14 09:11:59 +00003692 MVT::ValueType LVT = MVT::i64;
3693 while (!TLI.isTypeLegal(LVT))
3694 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3695 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003696
Evan Chengd5026102006-02-14 09:11:59 +00003697 if (VT > LVT)
3698 VT = LVT;
3699
Evan Cheng04514992006-02-14 23:05:54 +00003700 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003701 while (Size != 0) {
3702 unsigned VTSize = getSizeInBits(VT) / 8;
3703 while (VTSize > Size) {
3704 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003705 VTSize >>= 1;
3706 }
Evan Chengd5026102006-02-14 09:11:59 +00003707 assert(MVT::isInteger(VT));
3708
3709 if (++NumMemOps > Limit)
3710 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003711 MemOps.push_back(VT);
3712 Size -= VTSize;
3713 }
Evan Chengd5026102006-02-14 09:11:59 +00003714
3715 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003716}
3717
Chris Lattner875def92005-01-11 05:56:49 +00003718void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003719 SDOperand Op1 = getValue(I.getOperand(1));
3720 SDOperand Op2 = getValue(I.getOperand(2));
3721 SDOperand Op3 = getValue(I.getOperand(3));
3722 SDOperand Op4 = getValue(I.getOperand(4));
3723 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3724 if (Align == 0) Align = 1;
3725
3726 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3727 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003728
3729 // Expand memset / memcpy to a series of load / store ops
3730 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003731 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003732 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003733 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003734 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003735 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3736 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003737 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003738 unsigned Offset = 0;
3739 for (unsigned i = 0; i < NumMemOps; i++) {
3740 MVT::ValueType VT = MemOps[i];
3741 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003742 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003743 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003744 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003745 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003746 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003747 Offset += VTSize;
3748 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003749 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003750 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003751 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003752 case ISD::MEMCPY: {
3753 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3754 Size->getValue(), Align, TLI)) {
3755 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003756 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003757 GlobalAddressSDNode *G = NULL;
3758 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003759 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003760
3761 if (Op2.getOpcode() == ISD::GlobalAddress)
3762 G = cast<GlobalAddressSDNode>(Op2);
3763 else if (Op2.getOpcode() == ISD::ADD &&
3764 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3765 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3766 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003767 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003768 }
3769 if (G) {
3770 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003771 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003772 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003773 if (!Str.empty()) {
3774 CopyFromStr = true;
3775 SrcOff += SrcDelta;
3776 }
3777 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003778 }
3779
Evan Chenge2038bd2006-02-15 01:54:51 +00003780 for (unsigned i = 0; i < NumMemOps; i++) {
3781 MVT::ValueType VT = MemOps[i];
3782 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003783 SDOperand Value, Chain, Store;
3784
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003785 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003786 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3787 Chain = getRoot();
3788 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003789 DAG.getStore(Chain, Value,
3790 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003791 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003792 } else {
3793 Value = DAG.getLoad(VT, getRoot(),
3794 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003795 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003796 Chain = Value.getValue(1);
3797 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003798 DAG.getStore(Chain, Value,
3799 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003800 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003801 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003802 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003803 SrcOff += VTSize;
3804 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003805 }
3806 }
3807 break;
3808 }
3809 }
3810
3811 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003812 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3813 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003814 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003815 }
3816 }
3817
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003818 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003819}
3820
Chris Lattner875def92005-01-11 05:56:49 +00003821//===----------------------------------------------------------------------===//
3822// SelectionDAGISel code
3823//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003824
3825unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3826 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3827}
3828
Chris Lattnerc9950c12005-08-17 06:37:43 +00003829void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003830 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00003831 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003832}
Chris Lattner7a60d912005-01-07 07:47:53 +00003833
Chris Lattner35397782005-12-05 07:10:48 +00003834
Chris Lattnerbba52192006-10-28 19:22:10 +00003835
Chris Lattner7a60d912005-01-07 07:47:53 +00003836bool SelectionDAGISel::runOnFunction(Function &Fn) {
3837 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3838 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00003839 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00003840
3841 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3842
3843 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3844 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003845
Evan Cheng276b44b2007-02-10 02:43:39 +00003846 // Add function live-ins to entry block live-in set.
3847 BasicBlock *EntryBB = &Fn.getEntryBlock();
3848 BB = FuncInfo.MBBMap[EntryBB];
3849 if (!MF.livein_empty())
3850 for (MachineFunction::livein_iterator I = MF.livein_begin(),
3851 E = MF.livein_end(); I != E; ++I)
3852 BB->addLiveIn(I->first);
3853
Chris Lattner7a60d912005-01-07 07:47:53 +00003854 return true;
3855}
3856
Chris Lattnered0110b2006-10-27 21:36:01 +00003857SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3858 unsigned Reg) {
3859 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003860 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003861 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003862 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003863
3864 // If this type is not legal, we must make sure to not create an invalid
3865 // register use.
3866 MVT::ValueType SrcVT = Op.getValueType();
3867 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003868 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003869 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003870 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003871 // Handle copies from generic vectors to registers.
3872 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003873 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00003874 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003875
Chris Lattner5fe1f542006-03-31 02:06:56 +00003876 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3877 // MVT::Vector type.
3878 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3879 DAG.getConstant(NE, MVT::i32),
3880 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003881
Chris Lattner5fe1f542006-03-31 02:06:56 +00003882 // Loop over all of the elements of the resultant vector,
3883 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3884 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003885 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003886 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003887 for (unsigned i = 0; i != NE; ++i) {
3888 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003889 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003890 if (PTyElementVT == PTyLegalElementVT) {
3891 // Elements are legal.
3892 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3893 } else if (PTyLegalElementVT > PTyElementVT) {
3894 // Elements are promoted.
3895 if (MVT::isFloatingPoint(PTyLegalElementVT))
3896 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3897 else
3898 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3899 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3900 } else {
3901 // Elements are expanded.
3902 // The src value is expanded into multiple registers.
3903 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003904 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003905 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003906 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003907 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3908 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3909 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003910 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003911 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3912 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00003913 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00003914 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003915 if (MVT::isFloatingPoint(SrcVT))
3916 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3917 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003918 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003919 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003920 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00003921 DestVT = TLI.getTypeToExpandTo(SrcVT);
3922 unsigned NumVals = TLI.getNumElements(SrcVT);
3923 if (NumVals == 1)
3924 return DAG.getCopyToReg(getRoot(), Reg,
3925 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3926 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00003927 // The src value is expanded into multiple registers.
3928 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003929 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003930 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003931 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003932 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003933 return DAG.getCopyToReg(Op, Reg+1, Hi);
3934 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003935}
3936
Chris Lattner16f64df2005-01-17 17:15:02 +00003937void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00003938LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00003939 std::vector<SDOperand> &UnorderedChains) {
3940 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00003941 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003942 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003943 SDOperand OldRoot = SDL.DAG.getRoot();
3944 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003945
Chris Lattner6871b232005-10-30 19:42:35 +00003946 unsigned a = 0;
3947 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3948 AI != E; ++AI, ++a)
3949 if (!AI->use_empty()) {
3950 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003951
Chris Lattner6871b232005-10-30 19:42:35 +00003952 // If this argument is live outside of the entry block, insert a copy from
3953 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00003954 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
3955 if (VMI != FuncInfo.ValueMap.end()) {
3956 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00003957 UnorderedChains.push_back(Copy);
3958 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003959 }
Chris Lattner6871b232005-10-30 19:42:35 +00003960
Chris Lattner6871b232005-10-30 19:42:35 +00003961 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003962 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003963 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003964}
3965
Chris Lattner7a60d912005-01-07 07:47:53 +00003966void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3967 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003968 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003969 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003970
3971 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003972
Chris Lattner6871b232005-10-30 19:42:35 +00003973 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00003974 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00003975 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003976
3977 BB = FuncInfo.MBBMap[LLVMBB];
3978 SDL.setCurrentBasicBlock(BB);
3979
3980 // Lower all of the non-terminator instructions.
3981 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3982 I != E; ++I)
3983 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00003984
3985 // Lower call part of invoke.
3986 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
3987 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003988
Chris Lattner7a60d912005-01-07 07:47:53 +00003989 // Ensure that all instructions which are used outside of their defining
3990 // blocks are available as virtual registers.
3991 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003992 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00003993 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003994 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003995 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003996 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003997 }
3998
3999 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4000 // ensure constants are generated when needed. Remember the virtual registers
4001 // that need to be added to the Machine PHI nodes as input. We cannot just
4002 // directly add them, because expansion might result in multiple MBB's for one
4003 // BB. As such, the start of the BB might correspond to a different MBB than
4004 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004005 //
Chris Lattner84a03502006-10-27 23:50:33 +00004006 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004007
4008 // Emit constants only once even if used by multiple PHI nodes.
4009 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004010
Chris Lattner84a03502006-10-27 23:50:33 +00004011 // Vector bool would be better, but vector<bool> is really slow.
4012 std::vector<unsigned char> SuccsHandled;
4013 if (TI->getNumSuccessors())
4014 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4015
Chris Lattner7a60d912005-01-07 07:47:53 +00004016 // Check successor nodes PHI nodes that expect a constant to be available from
4017 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004018 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4019 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004020 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004021 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004022
Chris Lattner84a03502006-10-27 23:50:33 +00004023 // If this terminator has multiple identical successors (common for
4024 // switches), only handle each succ once.
4025 unsigned SuccMBBNo = SuccMBB->getNumber();
4026 if (SuccsHandled[SuccMBBNo]) continue;
4027 SuccsHandled[SuccMBBNo] = true;
4028
4029 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004030 PHINode *PN;
4031
4032 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4033 // nodes and Machine PHI nodes, but the incoming operands have not been
4034 // emitted yet.
4035 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004036 (PN = dyn_cast<PHINode>(I)); ++I) {
4037 // Ignore dead phi's.
4038 if (PN->use_empty()) continue;
4039
4040 unsigned Reg;
4041 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004042
Chris Lattner84a03502006-10-27 23:50:33 +00004043 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4044 unsigned &RegOut = ConstantsOut[C];
4045 if (RegOut == 0) {
4046 RegOut = FuncInfo.CreateRegForValue(C);
4047 UnorderedChains.push_back(
4048 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004049 }
Chris Lattner84a03502006-10-27 23:50:33 +00004050 Reg = RegOut;
4051 } else {
4052 Reg = FuncInfo.ValueMap[PHIOp];
4053 if (Reg == 0) {
4054 assert(isa<AllocaInst>(PHIOp) &&
4055 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4056 "Didn't codegen value into a register!??");
4057 Reg = FuncInfo.CreateRegForValue(PHIOp);
4058 UnorderedChains.push_back(
4059 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004060 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004061 }
Chris Lattner84a03502006-10-27 23:50:33 +00004062
4063 // Remember that this register needs to added to the machine PHI node as
4064 // the input for this MBB.
4065 MVT::ValueType VT = TLI.getValueType(PN->getType());
4066 unsigned NumElements;
4067 if (VT != MVT::Vector)
4068 NumElements = TLI.getNumElements(VT);
4069 else {
4070 MVT::ValueType VT1,VT2;
4071 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004072 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004073 VT1, VT2);
4074 }
4075 for (unsigned i = 0, e = NumElements; i != e; ++i)
4076 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4077 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004078 }
4079 ConstantsOut.clear();
4080
Chris Lattner718b5c22005-01-13 17:59:43 +00004081 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004082 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004083 SDOperand Root = SDL.getRoot();
4084 if (Root.getOpcode() != ISD::EntryToken) {
4085 unsigned i = 0, e = UnorderedChains.size();
4086 for (; i != e; ++i) {
4087 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4088 if (UnorderedChains[i].Val->getOperand(0) == Root)
4089 break; // Don't add the root if we already indirectly depend on it.
4090 }
4091
4092 if (i == e)
4093 UnorderedChains.push_back(Root);
4094 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004095 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4096 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004097 }
4098
Chris Lattner7a60d912005-01-07 07:47:53 +00004099 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004100 if (Invoke) {
4101 // Just the branch part of invoke.
4102 SDL.visitInvoke(*Invoke, true);
4103 } else {
4104 SDL.visit(*LLVMBB->getTerminator());
4105 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004106
Nate Begemaned728c12006-03-27 01:32:24 +00004107 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004108 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004109 SwitchCases.clear();
4110 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004111 JTCases.clear();
4112 JTCases = SDL.JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +00004113
Chris Lattner4108bb02005-01-17 19:43:36 +00004114 // Make sure the root of the DAG is up-to-date.
4115 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004116}
4117
Nate Begemaned728c12006-03-27 01:32:24 +00004118void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004119 // Get alias analysis for load/store combining.
4120 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4121
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004122 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004123 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004124
Bill Wendling22e978a2006-12-07 20:04:42 +00004125 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004126 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004127
Chris Lattner7a60d912005-01-07 07:47:53 +00004128 // Second step, hack on the DAG until it only uses operations and types that
4129 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004130 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004131
Bill Wendling22e978a2006-12-07 20:04:42 +00004132 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004133 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004134
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004135 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004136 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004137
Evan Cheng739a6a42006-01-21 02:32:06 +00004138 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004139
Chris Lattner5ca31d92005-03-30 01:10:47 +00004140 // Third, instruction select all of the operations to machine code, adding the
4141 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004142 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004143
Bill Wendling22e978a2006-12-07 20:04:42 +00004144 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004145 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004146}
Chris Lattner7a60d912005-01-07 07:47:53 +00004147
Nate Begemaned728c12006-03-27 01:32:24 +00004148void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4149 FunctionLoweringInfo &FuncInfo) {
4150 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4151 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004152 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004153 CurDAG = &DAG;
4154
4155 // First step, lower LLVM code to some DAG. This DAG may use operations and
4156 // types that are not supported by the target.
4157 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4158
4159 // Second step, emit the lowered DAG as machine code.
4160 CodeGenAndEmitDAG(DAG);
4161 }
4162
Chris Lattner5ca31d92005-03-30 01:10:47 +00004163 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004164 // PHI nodes in successors.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004165 if (SwitchCases.empty() && JTCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004166 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4167 MachineInstr *PHI = PHINodesToUpdate[i].first;
4168 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4169 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004170 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004171 PHI->addMachineBasicBlockOperand(BB);
4172 }
4173 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004174 }
Nate Begemaned728c12006-03-27 01:32:24 +00004175
Nate Begeman866b4b42006-04-23 06:26:20 +00004176 // If the JumpTable record is filled in, then we need to emit a jump table.
4177 // Updating the PHI nodes is tricky in this case, since we need to determine
4178 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004179 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4180 // Lower header first, if it wasn't already lowered
4181 if (!JTCases[i].first.Emitted) {
4182 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4183 CurDAG = &HSDAG;
4184 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4185 // Set the current basic block to the mbb we wish to insert the code into
4186 BB = JTCases[i].first.HeaderBB;
4187 HSDL.setCurrentBasicBlock(BB);
4188 // Emit the code
4189 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4190 HSDAG.setRoot(HSDL.getRoot());
4191 CodeGenAndEmitDAG(HSDAG);
4192 }
4193
4194 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4195 CurDAG = &JSDAG;
4196 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004197 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004198 BB = JTCases[i].second.MBB;
4199 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004200 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004201 JSDL.visitJumpTable(JTCases[i].second);
4202 JSDAG.setRoot(JSDL.getRoot());
4203 CodeGenAndEmitDAG(JSDAG);
4204
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004205 // Update PHI Nodes
4206 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4207 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4208 MachineBasicBlock *PHIBB = PHI->getParent();
4209 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4210 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov70378262007-03-25 15:07:15 +00004211 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004212 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004213 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004214 }
4215 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004216 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004217 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004218 }
4219 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004220 }
4221
Chris Lattner76a7bc82006-10-22 23:00:53 +00004222 // If the switch block involved a branch to one of the actual successors, we
4223 // need to update PHI nodes in that block.
4224 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4225 MachineInstr *PHI = PHINodesToUpdate[i].first;
4226 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4227 "This is not a machine PHI node that we are updating!");
4228 if (BB->isSuccessor(PHI->getParent())) {
4229 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4230 PHI->addMachineBasicBlockOperand(BB);
4231 }
4232 }
4233
Nate Begemaned728c12006-03-27 01:32:24 +00004234 // If we generated any switch lowering information, build and codegen any
4235 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004236 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004237 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004238 CurDAG = &SDAG;
4239 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004240
Nate Begemaned728c12006-03-27 01:32:24 +00004241 // Set the current basic block to the mbb we wish to insert the code into
4242 BB = SwitchCases[i].ThisBB;
4243 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004244
Nate Begemaned728c12006-03-27 01:32:24 +00004245 // Emit the code
4246 SDL.visitSwitchCase(SwitchCases[i]);
4247 SDAG.setRoot(SDL.getRoot());
4248 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004249
4250 // Handle any PHI nodes in successors of this chunk, as if we were coming
4251 // from the original BB before switch expansion. Note that PHI nodes can
4252 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4253 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004254 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004255 for (MachineBasicBlock::iterator Phi = BB->begin();
4256 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4257 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4258 for (unsigned pn = 0; ; ++pn) {
4259 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4260 if (PHINodesToUpdate[pn].first == Phi) {
4261 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4262 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4263 break;
4264 }
4265 }
Nate Begemaned728c12006-03-27 01:32:24 +00004266 }
Chris Lattner707339a52006-09-07 01:59:34 +00004267
4268 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004269 if (BB == SwitchCases[i].FalseBB)
4270 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004271
4272 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004273 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004274 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004275 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004276 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004277 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004278}
Evan Cheng739a6a42006-01-21 02:32:06 +00004279
Jim Laskey95eda5b2006-08-01 14:21:23 +00004280
Evan Cheng739a6a42006-01-21 02:32:06 +00004281//===----------------------------------------------------------------------===//
4282/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4283/// target node in the graph.
4284void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4285 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004286
Jim Laskey29e635d2006-08-02 12:30:23 +00004287 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004288
4289 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004290 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004291 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004292 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004293
Jim Laskey03593f72006-08-01 18:29:48 +00004294 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004295 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004296 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004297}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004298
Chris Lattner47639db2006-03-06 00:22:00 +00004299
Jim Laskey03593f72006-08-01 18:29:48 +00004300HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4301 return new HazardRecognizer();
4302}
4303
Chris Lattner6df34962006-10-11 03:58:02 +00004304//===----------------------------------------------------------------------===//
4305// Helper functions used by the generated instruction selector.
4306//===----------------------------------------------------------------------===//
4307// Calls to these methods are generated by tblgen.
4308
4309/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4310/// the dag combiner simplified the 255, we still want to match. RHS is the
4311/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4312/// specified in the .td file (e.g. 255).
4313bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4314 int64_t DesiredMaskS) {
4315 uint64_t ActualMask = RHS->getValue();
4316 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4317
4318 // If the actual mask exactly matches, success!
4319 if (ActualMask == DesiredMask)
4320 return true;
4321
4322 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4323 if (ActualMask & ~DesiredMask)
4324 return false;
4325
4326 // Otherwise, the DAG Combiner may have proven that the value coming in is
4327 // either already zero or is not demanded. Check for known zero input bits.
4328 uint64_t NeededMask = DesiredMask & ~ActualMask;
4329 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4330 return true;
4331
4332 // TODO: check to see if missing bits are just not demanded.
4333
4334 // Otherwise, this pattern doesn't match.
4335 return false;
4336}
4337
4338/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4339/// the dag combiner simplified the 255, we still want to match. RHS is the
4340/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4341/// specified in the .td file (e.g. 255).
4342bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4343 int64_t DesiredMaskS) {
4344 uint64_t ActualMask = RHS->getValue();
4345 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4346
4347 // If the actual mask exactly matches, success!
4348 if (ActualMask == DesiredMask)
4349 return true;
4350
4351 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4352 if (ActualMask & ~DesiredMask)
4353 return false;
4354
4355 // Otherwise, the DAG Combiner may have proven that the value coming in is
4356 // either already zero or is not demanded. Check for known zero input bits.
4357 uint64_t NeededMask = DesiredMask & ~ActualMask;
4358
4359 uint64_t KnownZero, KnownOne;
4360 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4361
4362 // If all the missing bits in the or are already known to be set, match!
4363 if ((NeededMask & KnownOne) == NeededMask)
4364 return true;
4365
4366 // TODO: check to see if missing bits are just not demanded.
4367
4368 // Otherwise, this pattern doesn't match.
4369 return false;
4370}
4371
Jim Laskey03593f72006-08-01 18:29:48 +00004372
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004373/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4374/// by tblgen. Others should not call it.
4375void SelectionDAGISel::
4376SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4377 std::vector<SDOperand> InOps;
4378 std::swap(InOps, Ops);
4379
4380 Ops.push_back(InOps[0]); // input chain.
4381 Ops.push_back(InOps[1]); // input asm string.
4382
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004383 unsigned i = 2, e = InOps.size();
4384 if (InOps[e-1].getValueType() == MVT::Flag)
4385 --e; // Don't process a flag operand if it is here.
4386
4387 while (i != e) {
4388 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4389 if ((Flags & 7) != 4 /*MEM*/) {
4390 // Just skip over this operand, copying the operands verbatim.
4391 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4392 i += (Flags >> 3) + 1;
4393 } else {
4394 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4395 // Otherwise, this is a memory operand. Ask the target to select it.
4396 std::vector<SDOperand> SelOps;
4397 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004398 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004399 exit(1);
4400 }
4401
4402 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004403 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4404 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004405 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4406 i += 2;
4407 }
4408 }
4409
4410 // Add the flag input back if present.
4411 if (e != InOps.size())
4412 Ops.push_back(InOps.back());
4413}