blob: 045e7ab5a6aa2615ba667a610341df92473f7728 [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"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeydcb2b832006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000073namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey03593f72006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner6f87d182006-02-22 22:37:12 +000085namespace {
86 /// RegsForValue - This struct represents the physical registers that a
87 /// particular value is assigned and the type information about the value.
88 /// This is needed because values can be promoted into larger registers and
89 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000090 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000091 /// Regs - This list hold the register (for legal and promoted values)
92 /// or register set (for expanded values) that the value should be assigned
93 /// to.
94 std::vector<unsigned> Regs;
95
96 /// RegVT - The value type of each register.
97 ///
98 MVT::ValueType RegVT;
99
100 /// ValueVT - The value type of the LLVM value, which may be promoted from
101 /// RegVT or made from merging the two expanded parts.
102 MVT::ValueType ValueVT;
103
104 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
105
106 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
107 : RegVT(regvt), ValueVT(valuevt) {
108 Regs.push_back(Reg);
109 }
110 RegsForValue(const std::vector<unsigned> &regs,
111 MVT::ValueType regvt, MVT::ValueType valuevt)
112 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
113 }
114
115 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
116 /// this value and returns the result as a ValueVT value. This uses
117 /// Chain/Flag as the input and updates them for the output Chain/Flag.
118 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000119 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000120
121 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
122 /// specified value into the registers specified by this object. This uses
123 /// Chain/Flag as the input and updates them for the output Chain/Flag.
124 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000125 SDOperand &Chain, SDOperand &Flag,
126 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000127
128 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
129 /// operand list. This adds the code marker and includes the number of
130 /// values added into it.
131 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000132 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000133 };
134}
Evan Chengc1e1d972006-01-23 07:01:07 +0000135
Chris Lattner7a60d912005-01-07 07:47:53 +0000136namespace llvm {
137 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
139 /// for the target.
140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
141 SelectionDAG *DAG,
142 MachineBasicBlock *BB) {
143 TargetLowering &TLI = IS->getTargetLowering();
144
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
146 return createTDListDAGScheduler(IS, DAG, BB);
147 } else {
148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
150 return createBURRListDAGScheduler(IS, DAG, BB);
151 }
152 }
153
154
155 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000156 /// FunctionLoweringInfo - This contains information that is global to a
157 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000158 class FunctionLoweringInfo {
159 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 TargetLowering &TLI;
161 Function &Fn;
162 MachineFunction &MF;
163 SSARegMap *RegMap;
164
165 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
166
167 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
168 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
169
170 /// ValueMap - Since we emit code for the function a basic block at a time,
171 /// we must remember which virtual registers hold the values for
172 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000173 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000174
175 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
176 /// the entry block. This allows the allocas to be efficiently referenced
177 /// anywhere in the function.
178 std::map<const AllocaInst*, int> StaticAllocaMap;
179
180 unsigned MakeReg(MVT::ValueType VT) {
181 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
182 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000183
184 /// isExportedInst - Return true if the specified value is an instruction
185 /// exported from its block.
186 bool isExportedInst(const Value *V) {
187 return ValueMap.count(V);
188 }
Misha Brukman835702a2005-04-21 22:36:52 +0000189
Chris Lattner49409cb2006-03-16 19:51:18 +0000190 unsigned CreateRegForValue(const Value *V);
191
Chris Lattner7a60d912005-01-07 07:47:53 +0000192 unsigned InitializeRegForValue(const Value *V) {
193 unsigned &R = ValueMap[V];
194 assert(R == 0 && "Already initialized this value register!");
195 return R = CreateRegForValue(V);
196 }
197 };
198}
199
200/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000201/// PHI nodes or outside of the basic block that defines it, or used by a
202/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000203static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
204 if (isa<PHINode>(I)) return true;
205 BasicBlock *BB = I->getParent();
206 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000207 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000208 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000209 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000210 return true;
211 return false;
212}
213
Chris Lattner6871b232005-10-30 19:42:35 +0000214/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000215/// entry block, return true. This includes arguments used by switches, since
216/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000220 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner7a60d912005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattner6871b232005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner7a60d912005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000242 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000243 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000244 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000245 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000246 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000247 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000248
Reid Spencere0fc4df2006-10-20 07:07:24 +0000249 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000250 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000251 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000252 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 }
254
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000255 for (; BB != EB; ++BB)
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000257 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
258 if (!isa<AllocaInst>(I) ||
259 !StaticAllocaMap.count(cast<AllocaInst>(I)))
260 InitializeRegForValue(I);
261
262 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
263 // also creates the initial PHI MachineInstrs, though none of the input
264 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000265 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000266 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
267 MBBMap[BB] = MBB;
268 MF.getBasicBlockList().push_back(MBB);
269
270 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
271 // appropriate.
272 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000273 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
274 if (PN->use_empty()) continue;
275
276 MVT::ValueType VT = TLI.getValueType(PN->getType());
277 unsigned NumElements;
278 if (VT != MVT::Vector)
279 NumElements = TLI.getNumElements(VT);
280 else {
281 MVT::ValueType VT1,VT2;
282 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000283 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000284 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000285 }
Chris Lattner84a03502006-10-27 23:50:33 +0000286 unsigned PHIReg = ValueMap[PN];
287 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000288 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000289 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000290 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000291 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000292 }
293}
294
Chris Lattner49409cb2006-03-16 19:51:18 +0000295/// CreateRegForValue - Allocate the appropriate number of virtual registers of
296/// the correctly promoted or expanded types. Assign these registers
297/// consecutive vreg numbers and return the first assigned number.
298unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
299 MVT::ValueType VT = TLI.getValueType(V->getType());
300
301 // The number of multiples of registers that we need, to, e.g., split up
302 // a <2 x int64> -> 4 x i32 registers.
303 unsigned NumVectorRegs = 1;
304
Reid Spencer09575ba2007-02-15 03:39:18 +0000305 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000306 // and how many of the elements it will use.
307 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000308 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000309 unsigned NumElts = PTy->getNumElements();
310 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
311
312 // Divide the input until we get to a supported size. This will always
313 // end with a scalar if the target doesn't support vectors.
314 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
315 NumElts >>= 1;
316 NumVectorRegs <<= 1;
317 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000318 if (NumElts == 1)
319 VT = EltTy;
320 else
321 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000322 }
323
324 // The common case is that we will only create one register for this
325 // value. If we have that case, create and return the virtual register.
326 unsigned NV = TLI.getNumElements(VT);
327 if (NV == 1) {
328 // If we are promoting this value, pick the next largest supported type.
329 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
330 unsigned Reg = MakeReg(PromotedType);
331 // If this is a vector of supported or promoted types (e.g. 4 x i16),
332 // create all of the registers.
333 for (unsigned i = 1; i != NumVectorRegs; ++i)
334 MakeReg(PromotedType);
335 return Reg;
336 }
337
338 // If this value is represented with multiple target registers, make sure
339 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000340 VT = TLI.getTypeToExpandTo(VT);
341 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000342 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000343 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000344 return R;
345}
Chris Lattner7a60d912005-01-07 07:47:53 +0000346
347//===----------------------------------------------------------------------===//
348/// SelectionDAGLowering - This is the common target-independent lowering
349/// implementation that is parameterized by a TargetLowering object.
350/// Also, targets can overload any lowering method.
351///
352namespace llvm {
353class SelectionDAGLowering {
354 MachineBasicBlock *CurMBB;
355
Chris Lattner79084302007-02-04 01:31:47 +0000356 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000357
Chris Lattner4d9651c2005-01-17 22:19:26 +0000358 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
359 /// them up and then emit token factor nodes when possible. This allows us to
360 /// get simple disambiguation between loads without worrying about alias
361 /// analysis.
362 std::vector<SDOperand> PendingLoads;
363
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000364 /// Case - A struct to record the Value for a switch case, and the
365 /// case's target basic block.
366 struct Case {
367 Constant* Low;
368 Constant* High;
369 MachineBasicBlock* BB;
370
371 Case() : Low(0), High(0), BB(0) { }
372 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
373 Low(low), High(high), BB(bb) { }
374 uint64_t size() const {
375 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
376 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
377 return (rHigh - rLow + 1ULL);
378 }
379 };
380
381 typedef std::vector<Case> CaseVector;
382 typedef CaseVector::iterator CaseItr;
383 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000384
385 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
386 /// of conditional branches.
387 struct CaseRec {
388 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
389 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
390
391 /// CaseBB - The MBB in which to emit the compare and branch
392 MachineBasicBlock *CaseBB;
393 /// LT, GE - If nonzero, we know the current case value must be less-than or
394 /// greater-than-or-equal-to these Constants.
395 Constant *LT;
396 Constant *GE;
397 /// Range - A pair of iterators representing the range of case values to be
398 /// processed at this point in the binary search tree.
399 CaseRange Range;
400 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000401
402 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000403
404 /// The comparison function for sorting the switch case values in the vector.
405 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000406 struct CaseCmp {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000407 bool operator () (const Case& C1,
408 const Case& C2) {
409
410 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
411 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
412 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
413 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000414 }
415 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000416
417 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000418
Chris Lattner7a60d912005-01-07 07:47:53 +0000419public:
420 // TLI - This is information that describes the available target features we
421 // need for lowering. This indicates when operations are unavailable,
422 // implemented with a libcall, etc.
423 TargetLowering &TLI;
424 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000425 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000426
Nate Begemaned728c12006-03-27 01:32:24 +0000427 /// SwitchCases - Vector of CaseBlock structures used to communicate
428 /// SwitchInst code generation information.
429 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000430 /// JTCases - Vector of JumpTable structures used to communicate
431 /// SwitchInst code generation information.
432 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000433
Chris Lattner7a60d912005-01-07 07:47:53 +0000434 /// FuncInfo - Information about the function as a whole.
435 ///
436 FunctionLoweringInfo &FuncInfo;
437
438 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000439 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000440 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000441 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000442 }
443
Chris Lattner4108bb02005-01-17 19:43:36 +0000444 /// getRoot - Return the current virtual root of the Selection DAG.
445 ///
446 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000447 if (PendingLoads.empty())
448 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000449
Chris Lattner4d9651c2005-01-17 22:19:26 +0000450 if (PendingLoads.size() == 1) {
451 SDOperand Root = PendingLoads[0];
452 DAG.setRoot(Root);
453 PendingLoads.clear();
454 return Root;
455 }
456
457 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000458 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
459 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000460 PendingLoads.clear();
461 DAG.setRoot(Root);
462 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000463 }
464
Chris Lattnered0110b2006-10-27 21:36:01 +0000465 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
466
Chris Lattner7a60d912005-01-07 07:47:53 +0000467 void visit(Instruction &I) { visit(I.getOpcode(), I); }
468
469 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000470 // Note: this doesn't use InstVisitor, because it has to work with
471 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000472 switch (Opcode) {
473 default: assert(0 && "Unknown instruction type encountered!");
474 abort();
475 // Build the switch statement using the Instruction.def file.
476#define HANDLE_INST(NUM, OPCODE, CLASS) \
477 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
478#include "llvm/Instruction.def"
479 }
480 }
481
482 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
483
Chris Lattner4024c002006-03-15 22:19:46 +0000484 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000485 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000486 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000487
488 SDOperand getIntPtrConstant(uint64_t Val) {
489 return DAG.getConstant(Val, TLI.getPointerTy());
490 }
491
Chris Lattner8471b152006-03-16 19:57:50 +0000492 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000493
Chris Lattner79084302007-02-04 01:31:47 +0000494 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 SDOperand &N = NodeMap[V];
496 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000497 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000499
Chris Lattner6f87d182006-02-22 22:37:12 +0000500 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
501 MVT::ValueType VT,
502 bool OutReg, bool InReg,
503 std::set<unsigned> &OutputRegs,
504 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000505
Chris Lattnered0110b2006-10-27 21:36:01 +0000506 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
507 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
508 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000509 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000510 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000511 void LowerCallTo(Instruction &I,
512 const Type *CalledValueTy, unsigned CallingConv,
513 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000514
Chris Lattner7a60d912005-01-07 07:47:53 +0000515 // Terminator instructions.
516 void visitRet(ReturnInst &I);
517 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000518 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000519 void visitUnreachable(UnreachableInst &I) { /* noop */ }
520
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000521 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000522 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000523 CaseRecVector& WorkList,
524 Value* SV,
525 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000526 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000527 CaseRecVector& WorkList,
528 Value* SV,
529 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000530 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000531 CaseRecVector& WorkList,
532 Value* SV,
533 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000534 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000535 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000536 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
537 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000538
Chris Lattner7a60d912005-01-07 07:47:53 +0000539 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000540 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000541 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000542 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
Reid Spencer2eadb532007-01-21 00:29:26 +0000544 void visitScalarBinary(User &I, unsigned OpCode);
545 void visitVectorBinary(User &I, unsigned OpCode);
546 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000547 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000548 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000549 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000550 visitVectorBinary(I, ISD::VADD);
551 else if (I.getType()->isFloatingPoint())
552 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000553 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000554 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000555 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000556 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000557 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000558 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000559 visitVectorBinary(I, ISD::VMUL);
560 else if (I.getType()->isFloatingPoint())
561 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000562 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000563 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000564 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000565 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
566 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
567 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
568 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
569 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
570 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
571 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
572 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
573 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
574 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000575 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
576 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000577 void visitICmp(User &I);
578 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000579 // Visit the conversion instructions
580 void visitTrunc(User &I);
581 void visitZExt(User &I);
582 void visitSExt(User &I);
583 void visitFPTrunc(User &I);
584 void visitFPExt(User &I);
585 void visitFPToUI(User &I);
586 void visitFPToSI(User &I);
587 void visitUIToFP(User &I);
588 void visitSIToFP(User &I);
589 void visitPtrToInt(User &I);
590 void visitIntToPtr(User &I);
591 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000592
Chris Lattner67271862006-03-29 00:11:43 +0000593 void visitExtractElement(User &I);
594 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000595 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000596
Chris Lattner7a60d912005-01-07 07:47:53 +0000597 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000598 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000599
600 void visitMalloc(MallocInst &I);
601 void visitFree(FreeInst &I);
602 void visitAlloca(AllocaInst &I);
603 void visitLoad(LoadInst &I);
604 void visitStore(StoreInst &I);
605 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
606 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000607 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000608 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000609 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000610
Chris Lattner7a60d912005-01-07 07:47:53 +0000611 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000612 void visitVAArg(VAArgInst &I);
613 void visitVAEnd(CallInst &I);
614 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000615
Chris Lattner875def92005-01-11 05:56:49 +0000616 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000617
618 void visitUserOp1(Instruction &I) {
619 assert(0 && "UserOp1 should not exist at instruction selection time!");
620 abort();
621 }
622 void visitUserOp2(Instruction &I) {
623 assert(0 && "UserOp2 should not exist at instruction selection time!");
624 abort();
625 }
626};
627} // end namespace llvm
628
Chris Lattner8471b152006-03-16 19:57:50 +0000629SDOperand SelectionDAGLowering::getValue(const Value *V) {
630 SDOperand &N = NodeMap[V];
631 if (N.Val) return N;
632
633 const Type *VTy = V->getType();
634 MVT::ValueType VT = TLI.getValueType(VTy);
635 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
636 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
637 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000638 SDOperand N1 = NodeMap[V];
639 assert(N1.Val && "visit didn't populate the ValueMap!");
640 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000641 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
642 return N = DAG.getGlobalAddress(GV, VT);
643 } else if (isa<ConstantPointerNull>(C)) {
644 return N = DAG.getConstant(0, TLI.getPointerTy());
645 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000646 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000647 return N = DAG.getNode(ISD::UNDEF, VT);
648
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000649 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000650 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000651 unsigned NumElements = PTy->getNumElements();
652 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
653
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000654 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000655 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
656
657 // Create a VConstant node with generic Vector type.
658 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
659 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000660 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
661 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000662 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
663 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000664 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000665 unsigned NumElements = PTy->getNumElements();
666 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000667
668 // Now that we know the number and type of the elements, push a
669 // Constant or ConstantFP node onto the ops list for each element of
670 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000671 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000672 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000673 for (unsigned i = 0; i != NumElements; ++i)
674 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000675 } else {
676 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
677 SDOperand Op;
678 if (MVT::isFloatingPoint(PVT))
679 Op = DAG.getConstantFP(0, PVT);
680 else
681 Op = DAG.getConstant(0, PVT);
682 Ops.assign(NumElements, Op);
683 }
684
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000685 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000686 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
687 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000688 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
689 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000690 } else {
691 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000692 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000693 }
694 }
695
696 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
697 std::map<const AllocaInst*, int>::iterator SI =
698 FuncInfo.StaticAllocaMap.find(AI);
699 if (SI != FuncInfo.StaticAllocaMap.end())
700 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
701 }
702
Chris Lattner8c504cf2007-02-25 18:40:32 +0000703 unsigned InReg = FuncInfo.ValueMap[V];
704 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000705
706 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000707 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000708 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000709 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000710 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000711 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
712 unsigned NumVals = TLI.getNumElements(VT);
713 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
714 if (NumVals == 1)
715 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
716 else {
717 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
718 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
719 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
720 }
721 } else {
722 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
723 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
724 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
725 N = MVT::isFloatingPoint(VT)
726 ? DAG.getNode(ISD::FP_ROUND, VT, N)
727 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000728 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000729 } else {
730 // Otherwise, if this is a vector, make it available as a generic vector
731 // here.
732 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000733 const VectorType *PTy = cast<VectorType>(VTy);
734 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000735 PTyLegalElementVT);
736
737 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000738 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000739 if (PTyElementVT == PTyLegalElementVT) {
740 // If the value types are legal, just VBUILD the CopyFromReg nodes.
741 for (unsigned i = 0; i != NE; ++i)
742 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
743 PTyElementVT));
744 } else if (PTyElementVT < PTyLegalElementVT) {
745 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
746 for (unsigned i = 0; i != NE; ++i) {
747 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
748 PTyElementVT);
749 if (MVT::isFloatingPoint(PTyElementVT))
750 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
751 else
752 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
753 Ops.push_back(Op);
754 }
755 } else {
756 // If the register was expanded, use BUILD_PAIR.
757 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
758 for (unsigned i = 0; i != NE/2; ++i) {
759 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
760 PTyElementVT);
761 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
762 PTyElementVT);
763 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
764 }
765 }
766
767 Ops.push_back(DAG.getConstant(NE, MVT::i32));
768 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000769 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000770
771 // Finally, use a VBIT_CONVERT to make this available as the appropriate
772 // vector type.
773 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
774 DAG.getConstant(PTy->getNumElements(),
775 MVT::i32),
776 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000777 }
778
779 return N;
780}
781
782
Chris Lattner7a60d912005-01-07 07:47:53 +0000783void SelectionDAGLowering::visitRet(ReturnInst &I) {
784 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000785 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000786 return;
787 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000788 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000789 NewValues.push_back(getRoot());
790 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
791 SDOperand RetOp = getValue(I.getOperand(i));
792
793 // If this is an integer return value, we need to promote it ourselves to
794 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
795 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000796 // FIXME: C calling convention requires the return type to be promoted to
797 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000798 if (MVT::isInteger(RetOp.getValueType()) &&
799 RetOp.getValueType() < MVT::i64) {
800 MVT::ValueType TmpVT;
801 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
802 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
803 else
804 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000805 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000806 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000807 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer71b79e32007-04-09 06:17:21 +0000808 if (Attrs && Attrs->paramHasAttr(0, SExtAttribute))
Reid Spencer0917adf2007-01-03 04:25:33 +0000809 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer71b79e32007-04-09 06:17:21 +0000810 if (Attrs && Attrs->paramHasAttr(0, ZExtAttribute))
Reid Spencere63b6512006-12-31 05:55:36 +0000811 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000812 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000813 }
814 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000815 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000816 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000817 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
818 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000819}
820
Chris Lattnered0110b2006-10-27 21:36:01 +0000821/// ExportFromCurrentBlock - If this condition isn't known to be exported from
822/// the current basic block, add it to ValueMap now so that we'll get a
823/// CopyTo/FromReg.
824void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
825 // No need to export constants.
826 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
827
828 // Already exported?
829 if (FuncInfo.isExportedInst(V)) return;
830
831 unsigned Reg = FuncInfo.InitializeRegForValue(V);
832 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
833}
834
Chris Lattner84a03502006-10-27 23:50:33 +0000835bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
836 const BasicBlock *FromBB) {
837 // The operands of the setcc have to be in this block. We don't know
838 // how to export them from some other block.
839 if (Instruction *VI = dyn_cast<Instruction>(V)) {
840 // Can export from current BB.
841 if (VI->getParent() == FromBB)
842 return true;
843
844 // Is already exported, noop.
845 return FuncInfo.isExportedInst(V);
846 }
847
848 // If this is an argument, we can export it if the BB is the entry block or
849 // if it is already exported.
850 if (isa<Argument>(V)) {
851 if (FromBB == &FromBB->getParent()->getEntryBlock())
852 return true;
853
854 // Otherwise, can only export this if it is already exported.
855 return FuncInfo.isExportedInst(V);
856 }
857
858 // Otherwise, constants can always be exported.
859 return true;
860}
861
Chris Lattnere60ae822006-10-29 21:01:20 +0000862static bool InBlock(const Value *V, const BasicBlock *BB) {
863 if (const Instruction *I = dyn_cast<Instruction>(V))
864 return I->getParent() == BB;
865 return true;
866}
867
Chris Lattnered0110b2006-10-27 21:36:01 +0000868/// FindMergedConditions - If Cond is an expression like
869void SelectionDAGLowering::FindMergedConditions(Value *Cond,
870 MachineBasicBlock *TBB,
871 MachineBasicBlock *FBB,
872 MachineBasicBlock *CurBB,
873 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000874 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000875 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000876
Reid Spencer266e42b2006-12-23 06:05:41 +0000877 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
878 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000879 BOp->getParent() != CurBB->getBasicBlock() ||
880 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
881 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000882 const BasicBlock *BB = CurBB->getBasicBlock();
883
Reid Spencer266e42b2006-12-23 06:05:41 +0000884 // If the leaf of the tree is a comparison, merge the condition into
885 // the caseblock.
886 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
887 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000888 // how to export them from some other block. If this is the first block
889 // of the sequence, no exporting is needed.
890 (CurBB == CurMBB ||
891 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
892 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000893 BOp = cast<Instruction>(Cond);
894 ISD::CondCode Condition;
895 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
896 switch (IC->getPredicate()) {
897 default: assert(0 && "Unknown icmp predicate opcode!");
898 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
899 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
900 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
901 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
902 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
903 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
904 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
905 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
906 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
907 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
908 }
909 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
910 ISD::CondCode FPC, FOC;
911 switch (FC->getPredicate()) {
912 default: assert(0 && "Unknown fcmp predicate opcode!");
913 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
914 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
915 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
916 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
917 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
918 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
919 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
920 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
921 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
922 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
923 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
924 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
925 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
926 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
927 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
928 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
929 }
930 if (FiniteOnlyFPMath())
931 Condition = FOC;
932 else
933 Condition = FPC;
934 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000935 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000936 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000937 }
938
Chris Lattnered0110b2006-10-27 21:36:01 +0000939 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000940 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000941 SwitchCases.push_back(CB);
942 return;
943 }
944
945 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000946 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000947 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000948 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000949 return;
950 }
951
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000952
953 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000954 MachineFunction::iterator BBI = CurBB;
955 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
956 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
957
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000958 if (Opc == Instruction::Or) {
959 // Codegen X | Y as:
960 // jmp_if_X TBB
961 // jmp TmpBB
962 // TmpBB:
963 // jmp_if_Y TBB
964 // jmp FBB
965 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000966
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000967 // Emit the LHS condition.
968 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
969
970 // Emit the RHS condition into TmpBB.
971 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
972 } else {
973 assert(Opc == Instruction::And && "Unknown merge op!");
974 // Codegen X & Y as:
975 // jmp_if_X TmpBB
976 // jmp FBB
977 // TmpBB:
978 // jmp_if_Y TBB
979 // jmp FBB
980 //
981 // This requires creation of TmpBB after CurBB.
982
983 // Emit the LHS condition.
984 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
985
986 // Emit the RHS condition into TmpBB.
987 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
988 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000989}
990
Chris Lattner427301f2006-10-31 22:37:42 +0000991/// If the set of cases should be emitted as a series of branches, return true.
992/// If we should emit this as a bunch of and/or'd together conditions, return
993/// false.
994static bool
995ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
996 if (Cases.size() != 2) return true;
997
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000998 // If this is two comparisons of the same values or'd or and'd together, they
999 // will get folded into a single comparison, so don't emit two blocks.
1000 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1001 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1002 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1003 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1004 return false;
1005 }
1006
Chris Lattner427301f2006-10-31 22:37:42 +00001007 return true;
1008}
1009
Chris Lattner7a60d912005-01-07 07:47:53 +00001010void SelectionDAGLowering::visitBr(BranchInst &I) {
1011 // Update machine-CFG edges.
1012 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001013
1014 // Figure out which block is immediately after the current one.
1015 MachineBasicBlock *NextBlock = 0;
1016 MachineFunction::iterator BBI = CurMBB;
1017 if (++BBI != CurMBB->getParent()->end())
1018 NextBlock = BBI;
1019
1020 if (I.isUnconditional()) {
1021 // If this is not a fall-through branch, emit the branch.
1022 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001023 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001024 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001025
Chris Lattner963ddad2006-10-24 17:57:59 +00001026 // Update machine-CFG edges.
1027 CurMBB->addSuccessor(Succ0MBB);
1028
1029 return;
1030 }
1031
1032 // If this condition is one of the special cases we handle, do special stuff
1033 // now.
1034 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001035 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001036
1037 // If this is a series of conditions that are or'd or and'd together, emit
1038 // this as a sequence of branches instead of setcc's with and/or operations.
1039 // For example, instead of something like:
1040 // cmp A, B
1041 // C = seteq
1042 // cmp D, E
1043 // F = setle
1044 // or C, F
1045 // jnz foo
1046 // Emit:
1047 // cmp A, B
1048 // je foo
1049 // cmp D, E
1050 // jle foo
1051 //
1052 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1053 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001054 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001055 BOp->getOpcode() == Instruction::Or)) {
1056 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001057 // If the compares in later blocks need to use values not currently
1058 // exported from this block, export them now. This block should always
1059 // be the first entry.
1060 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1061
Chris Lattner427301f2006-10-31 22:37:42 +00001062 // Allow some cases to be rejected.
1063 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001064 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1065 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1066 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1067 }
1068
1069 // Emit the branch for this block.
1070 visitSwitchCase(SwitchCases[0]);
1071 SwitchCases.erase(SwitchCases.begin());
1072 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001073 }
1074
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001075 // Okay, we decided not to do this, remove any inserted MBB's and clear
1076 // SwitchCases.
1077 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1078 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1079
Chris Lattner427301f2006-10-31 22:37:42 +00001080 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001081 }
1082 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001083
1084 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001085 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001086 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001087 // Use visitSwitchCase to actually insert the fast branch sequence for this
1088 // cond branch.
1089 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001090}
1091
Nate Begemaned728c12006-03-27 01:32:24 +00001092/// visitSwitchCase - Emits the necessary code to represent a single node in
1093/// the binary search tree resulting from lowering a switch instruction.
1094void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001095 SDOperand Cond;
1096 SDOperand CondLHS = getValue(CB.CmpLHS);
1097
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001098 // Build the setcc now.
1099 if (CB.CmpMHS == NULL) {
1100 // Fold "(X == true)" to X and "(X == false)" to !X to
1101 // handle common cases produced by branch lowering.
1102 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1103 Cond = CondLHS;
1104 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1105 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1106 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1107 } else
1108 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1109 } else {
1110 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001111
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001112 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1113 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1114
1115 SDOperand CmpOp = getValue(CB.CmpMHS);
1116 MVT::ValueType VT = CmpOp.getValueType();
1117
1118 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1119 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1120 } else {
1121 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1122 Cond = DAG.getSetCC(MVT::i1, SUB,
1123 DAG.getConstant(High-Low, VT), ISD::SETULE);
1124 }
1125
1126 }
1127
Nate Begemaned728c12006-03-27 01:32:24 +00001128 // Set NextBlock to be the MBB immediately after the current one, if any.
1129 // This is used to avoid emitting unnecessary branches to the next block.
1130 MachineBasicBlock *NextBlock = 0;
1131 MachineFunction::iterator BBI = CurMBB;
1132 if (++BBI != CurMBB->getParent()->end())
1133 NextBlock = BBI;
1134
1135 // If the lhs block is the next block, invert the condition so that we can
1136 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001137 if (CB.TrueBB == NextBlock) {
1138 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001139 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1140 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1141 }
1142 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001143 DAG.getBasicBlock(CB.TrueBB));
1144 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001145 DAG.setRoot(BrCond);
1146 else
1147 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001148 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001149 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001150 CurMBB->addSuccessor(CB.TrueBB);
1151 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001152}
1153
Anton Korobeynikov70378262007-03-25 15:07:15 +00001154/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001155void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001156 // Emit the code for the jump table
Anton Korobeynikov70378262007-03-25 15:07:15 +00001157 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001158 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001159 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1160 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1161 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1162 Table, Index));
1163 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001164}
1165
Anton Korobeynikov70378262007-03-25 15:07:15 +00001166/// visitJumpTableHeader - This function emits necessary code to produce index
1167/// in the JumpTable from switch case.
1168void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1169 SelectionDAGISel::JumpTableHeader &JTH) {
1170 // Subtract the lowest switch case value from the value being switched on
1171 // and conditional branch to default mbb if the result is greater than the
1172 // difference between smallest and largest cases.
1173 SDOperand SwitchOp = getValue(JTH.SValue);
1174 MVT::ValueType VT = SwitchOp.getValueType();
1175 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1176 DAG.getConstant(JTH.First, VT));
1177
1178 // The SDNode we just created, which holds the value being switched on
1179 // minus the the smallest case value, needs to be copied to a virtual
1180 // register so it can be used as an index into the jump table in a
1181 // subsequent basic block. This value may be smaller or larger than the
1182 // target's pointer type, and therefore require extension or truncating.
1183 if (VT > TLI.getPointerTy())
1184 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1185 else
1186 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1187
1188 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1189 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1190 JT.Reg = JumpTableReg;
1191
1192 // Emit the range check for the jump table, and branch to the default
1193 // block for the switch statement if the value being switched on exceeds
1194 // the largest case in the switch.
1195 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1196 DAG.getConstant(JTH.Last-JTH.First,VT),
1197 ISD::SETUGT);
1198
1199 // Set NextBlock to be the MBB immediately after the current one, if any.
1200 // This is used to avoid emitting unnecessary branches to the next block.
1201 MachineBasicBlock *NextBlock = 0;
1202 MachineFunction::iterator BBI = CurMBB;
1203 if (++BBI != CurMBB->getParent()->end())
1204 NextBlock = BBI;
1205
1206 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1207 DAG.getBasicBlock(JT.Default));
1208
1209 if (JT.MBB == NextBlock)
1210 DAG.setRoot(BrCond);
1211 else
1212 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1213 DAG.getBasicBlock(JT.MBB)));
1214}
1215
1216
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001217void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001218 assert(0 && "Should never be visited directly");
1219}
1220void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001221 // Retrieve successors.
1222 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1223 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1224
Jim Laskey14059d92007-02-25 21:43:59 +00001225 if (!AsTerminator) {
1226 // Mark landing pad so that it doesn't get deleted in branch folding.
1227 LandingPad->setIsLandingPad();
1228
1229 // Insert a label before the invoke call to mark the try range.
1230 // This can be used to detect deletion of the invoke via the
1231 // MachineModuleInfo.
1232 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1233 unsigned BeginLabel = MMI->NextLabelID();
1234 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1235 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001236
Jim Laskey14059d92007-02-25 21:43:59 +00001237 LowerCallTo(I, I.getCalledValue()->getType(),
1238 I.getCallingConv(),
1239 false,
1240 getValue(I.getOperand(0)),
1241 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001242
Jim Laskey14059d92007-02-25 21:43:59 +00001243 // Insert a label before the invoke call to mark the try range.
1244 // This can be used to detect deletion of the invoke via the
1245 // MachineModuleInfo.
1246 unsigned EndLabel = MMI->NextLabelID();
1247 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1248 DAG.getConstant(EndLabel, MVT::i32)));
1249
1250 // Inform MachineModuleInfo of range.
1251 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1252
1253 // Update successor info
1254 CurMBB->addSuccessor(Return);
1255 CurMBB->addSuccessor(LandingPad);
1256 } else {
1257 // Drop into normal successor.
1258 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1259 DAG.getBasicBlock(Return)));
1260 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001261}
1262
1263void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1264}
1265
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001266/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001267/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001268bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001269 CaseRecVector& WorkList,
1270 Value* SV,
1271 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001272 Case& BackCase = *(CR.Range.second-1);
1273
1274 // Size is the number of Cases represented by this range.
1275 unsigned Size = CR.Range.second - CR.Range.first;
1276 if (Size >=3)
1277 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001278
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001279 // Get the MachineFunction which holds the current MBB. This is used when
1280 // inserting any additional MBBs necessary to represent the switch.
1281 MachineFunction *CurMF = CurMBB->getParent();
1282
1283 // Figure out which block is immediately after the current one.
1284 MachineBasicBlock *NextBlock = 0;
1285 MachineFunction::iterator BBI = CR.CaseBB;
1286
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001287 if (++BBI != CurMBB->getParent()->end())
1288 NextBlock = BBI;
1289
1290 // TODO: If any two of the cases has the same destination, and if one value
1291 // is the same as the other, but has one bit unset that the other has set,
1292 // use bit manipulation to do two compares at once. For example:
1293 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1294
1295 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001296 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001297 // The last case block won't fall through into 'NextBlock' if we emit the
1298 // branches in this order. See if rearranging a case value would help.
1299 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001300 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001301 std::swap(*I, BackCase);
1302 break;
1303 }
1304 }
1305 }
1306
1307 // Create a CaseBlock record representing a conditional branch to
1308 // the Case's target mbb if the value being switched on SV is equal
1309 // to C.
1310 MachineBasicBlock *CurBlock = CR.CaseBB;
1311 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1312 MachineBasicBlock *FallThrough;
1313 if (I != E-1) {
1314 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1315 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1316 } else {
1317 // If the last case doesn't match, go to the default block.
1318 FallThrough = Default;
1319 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001320
1321 Value *RHS, *LHS, *MHS;
1322 ISD::CondCode CC;
1323 if (I->High == I->Low) {
1324 // This is just small small case range :) containing exactly 1 case
1325 CC = ISD::SETEQ;
1326 LHS = SV; RHS = I->High; MHS = NULL;
1327 } else {
1328 CC = ISD::SETLE;
1329 LHS = I->Low; MHS = SV; RHS = I->High;
1330 }
1331 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1332 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001333
1334 // If emitting the first comparison, just call visitSwitchCase to emit the
1335 // code into the current block. Otherwise, push the CaseBlock onto the
1336 // vector to be later processed by SDISel, and insert the node's MBB
1337 // before the next MBB.
1338 if (CurBlock == CurMBB)
1339 visitSwitchCase(CB);
1340 else
1341 SwitchCases.push_back(CB);
1342
1343 CurBlock = FallThrough;
1344 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001345
1346 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001347}
1348
1349/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001350bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001351 CaseRecVector& WorkList,
1352 Value* SV,
1353 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001354 Case& FrontCase = *CR.Range.first;
1355 Case& BackCase = *(CR.Range.second-1);
1356
1357 // Size is the number of Cases represented by this range.
1358 unsigned Size = CR.Range.second - CR.Range.first;
1359
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001360 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1361 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1362
1363 uint64_t TSize = 0;
1364 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1365 I!=E; ++I)
1366 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001367
1368 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1369 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
1370 Size <= 5)
1371 return false;
1372
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001373 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1374 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001375 return false;
1376
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001377 DOUT << "Lowering jump table\n"
1378 << "First entry: " << First << ". Last entry: " << Last << "\n"
1379 << "Size: " << TSize << ". Density: " << Density << "\n";
1380
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001381 // Get the MachineFunction which holds the current MBB. This is used when
1382 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001383 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001384
1385 // Figure out which block is immediately after the current one.
1386 MachineBasicBlock *NextBlock = 0;
1387 MachineFunction::iterator BBI = CR.CaseBB;
1388
1389 if (++BBI != CurMBB->getParent()->end())
1390 NextBlock = BBI;
1391
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001392 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1393
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001394 // Create a new basic block to hold the code for loading the address
1395 // of the jump table, and jumping to it. Update successor information;
1396 // we will either branch to the default case for the switch, or the jump
1397 // table.
1398 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1399 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1400 CR.CaseBB->addSuccessor(Default);
1401 CR.CaseBB->addSuccessor(JumpTableBB);
1402
1403 // Build a vector of destination BBs, corresponding to each target
1404 // of the jump table. If the value of the jump table slot corresponds to
1405 // a case statement, push the case's BB onto the vector, otherwise, push
1406 // the default BB.
1407 std::vector<MachineBasicBlock*> DestBBs;
1408 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001409 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1410 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1411 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1412
1413 if ((Low <= TEI) && (TEI <= High)) {
1414 DestBBs.push_back(I->BB);
1415 if (TEI==High)
1416 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001417 } else {
1418 DestBBs.push_back(Default);
1419 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001420 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001421
1422 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001423 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001424 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1425 E = DestBBs.end(); I != E; ++I) {
1426 if (!SuccsHandled[(*I)->getNumber()]) {
1427 SuccsHandled[(*I)->getNumber()] = true;
1428 JumpTableBB->addSuccessor(*I);
1429 }
1430 }
1431
1432 // Create a jump table index for this jump table, or return an existing
1433 // one.
1434 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1435
1436 // Set the jump table information so that we can codegen it as a second
1437 // MachineBasicBlock
1438 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1439 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1440 (CR.CaseBB == CurMBB));
1441 if (CR.CaseBB == CurMBB)
1442 visitJumpTableHeader(JT, JTH);
1443
1444 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001445
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001446 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001447}
1448
1449/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1450/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001451bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001452 CaseRecVector& WorkList,
1453 Value* SV,
1454 MachineBasicBlock* Default) {
1455 // Get the MachineFunction which holds the current MBB. This is used when
1456 // inserting any additional MBBs necessary to represent the switch.
1457 MachineFunction *CurMF = CurMBB->getParent();
1458
1459 // Figure out which block is immediately after the current one.
1460 MachineBasicBlock *NextBlock = 0;
1461 MachineFunction::iterator BBI = CR.CaseBB;
1462
1463 if (++BBI != CurMBB->getParent()->end())
1464 NextBlock = BBI;
1465
1466 Case& FrontCase = *CR.Range.first;
1467 Case& BackCase = *(CR.Range.second-1);
1468 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1469
1470 // Size is the number of Cases represented by this range.
1471 unsigned Size = CR.Range.second - CR.Range.first;
1472
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001473 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1474 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001475 double Density = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001476 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001477
1478 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1479 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001480 uint64_t TSize = 0;
1481 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1482 I!=E; ++I)
1483 TSize += I->size();
1484
1485 uint64_t LSize = FrontCase.size();
1486 uint64_t RSize = TSize-LSize;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001487 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001488 J!=E; ++I, ++J) {
1489 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1490 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001491 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1492 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1493 if (Density < (LDensity + RDensity)) {
1494 Pivot = J;
1495 Density = LDensity + RDensity;
1496 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001497
1498 LSize += J->size();
1499 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001500 }
1501
1502 CaseRange LHSR(CR.Range.first, Pivot);
1503 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001504 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001505 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1506
1507 // We know that we branch to the LHS if the Value being switched on is
1508 // less than the Pivot value, C. We use this to optimize our binary
1509 // tree a bit, by recognizing that if SV is greater than or equal to the
1510 // LHS's Case Value, and that Case Value is exactly one less than the
1511 // Pivot's Value, then we can branch directly to the LHS's Target,
1512 // rather than creating a leaf node for it.
1513 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001514 LHSR.first->High == CR.GE &&
1515 cast<ConstantInt>(C)->getSExtValue() ==
1516 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1517 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001518 } else {
1519 TrueBB = new MachineBasicBlock(LLVMBB);
1520 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1521 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1522 }
1523
1524 // Similar to the optimization above, if the Value being switched on is
1525 // known to be less than the Constant CR.LT, and the current Case Value
1526 // is CR.LT - 1, then we can branch directly to the target block for
1527 // the current Case Value, rather than emitting a RHS leaf node for it.
1528 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001529 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1530 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1531 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001532 } else {
1533 FalseBB = new MachineBasicBlock(LLVMBB);
1534 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1535 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1536 }
1537
1538 // Create a CaseBlock record representing a conditional branch to
1539 // the LHS node if the value being switched on SV is less than C.
1540 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001541 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1542 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001543
1544 if (CR.CaseBB == CurMBB)
1545 visitSwitchCase(CB);
1546 else
1547 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001548
1549 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001550}
1551
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001552// Clusterify - Transform simple list of Cases into list of CaseRange's
1553unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1554 const SwitchInst& SI) {
1555 unsigned numCmps = 0;
1556
1557 // Start with "simple" cases
1558 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1559 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1560 Cases.push_back(Case(SI.getSuccessorValue(i),
1561 SI.getSuccessorValue(i),
1562 SMBB));
1563 }
1564 sort(Cases.begin(), Cases.end(), CaseCmp());
1565
1566 // Merge case into clusters
1567 if (Cases.size()>=2)
1568 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1569 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1570 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1571 MachineBasicBlock* nextBB = J->BB;
1572 MachineBasicBlock* currentBB = I->BB;
1573
1574 // If the two neighboring cases go to the same destination, merge them
1575 // into a single case.
1576 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1577 I->High = J->High;
1578 J = Cases.erase(J);
1579 } else {
1580 I = J++;
1581 }
1582 }
1583
1584 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1585 if (I->Low != I->High)
1586 // A range counts double, since it requires two compares.
1587 ++numCmps;
1588 }
1589
1590 return numCmps;
1591}
1592
1593void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001594 // Figure out which block is immediately after the current one.
1595 MachineBasicBlock *NextBlock = 0;
1596 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001597
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001598 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001599
Nate Begemaned728c12006-03-27 01:32:24 +00001600 // If there is only the default destination, branch to it if it is not the
1601 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001602 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001603 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001604
Nate Begemaned728c12006-03-27 01:32:24 +00001605 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001606 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001607 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001608 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001609
Chris Lattner6d6fc262006-10-22 21:36:53 +00001610 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001611 return;
1612 }
1613
1614 // If there are any non-default case statements, create a vector of Cases
1615 // representing each one, and sort the vector so that we can efficiently
1616 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001617 CaseVector Cases;
1618 unsigned numCmps = Clusterify(Cases, SI);
1619 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1620 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001621
Nate Begemaned728c12006-03-27 01:32:24 +00001622 // Get the Value to be switched on and default basic blocks, which will be
1623 // inserted into CaseBlock records, representing basic blocks in the binary
1624 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001625 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001626
Nate Begemaned728c12006-03-27 01:32:24 +00001627 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001628 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001629 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1630
1631 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001632 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001633 CaseRec CR = WorkList.back();
1634 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001635
1636 // If the range has few cases (two or less) emit a series of specific
1637 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001638 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1639 continue;
1640
Anton Korobeynikov70378262007-03-25 15:07:15 +00001641 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1642 // target supports indirect branches, then emit a jump table rather than
1643 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001644 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1645 continue;
1646
1647 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1648 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1649 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001650 }
1651}
1652
Anton Korobeynikov70378262007-03-25 15:07:15 +00001653
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001654void SelectionDAGLowering::visitSub(User &I) {
1655 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001656 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001657 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001658 visitVectorBinary(I, ISD::VSUB);
1659 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001660 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1661 if (CFP->isExactlyValue(-0.0)) {
1662 SDOperand Op2 = getValue(I.getOperand(1));
1663 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1664 return;
1665 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001666 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001667 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001668 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001669}
1670
Reid Spencer2eadb532007-01-21 00:29:26 +00001671void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001672 SDOperand Op1 = getValue(I.getOperand(0));
1673 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001674
1675 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001676}
1677
Reid Spencer2eadb532007-01-21 00:29:26 +00001678void
1679SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001680 assert(isa<VectorType>(I.getType()));
1681 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001682 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001683
Reid Spencer2eadb532007-01-21 00:29:26 +00001684 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1685 getValue(I.getOperand(0)),
1686 getValue(I.getOperand(1)),
1687 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1688 Typ));
1689}
1690
1691void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1692 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001693 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001694 visitVectorBinary(I, VectorOp);
1695 else
1696 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001697}
Chris Lattner96c26752005-01-19 22:31:21 +00001698
Nate Begeman127321b2005-11-18 07:42:56 +00001699void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1700 SDOperand Op1 = getValue(I.getOperand(0));
1701 SDOperand Op2 = getValue(I.getOperand(1));
1702
Reid Spencer2341c222007-02-02 02:16:23 +00001703 if (TLI.getShiftAmountTy() < Op2.getValueType())
1704 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1705 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1706 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001707
Chris Lattner7a60d912005-01-07 07:47:53 +00001708 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1709}
1710
Reid Spencerd9436b62006-11-20 01:22:35 +00001711void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001712 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1713 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1714 predicate = IC->getPredicate();
1715 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1716 predicate = ICmpInst::Predicate(IC->getPredicate());
1717 SDOperand Op1 = getValue(I.getOperand(0));
1718 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001719 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001720 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001721 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1722 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1723 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1724 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1725 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1726 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1727 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1728 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1729 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1730 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1731 default:
1732 assert(!"Invalid ICmp predicate value");
1733 Opcode = ISD::SETEQ;
1734 break;
1735 }
1736 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1737}
1738
1739void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001740 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1741 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1742 predicate = FC->getPredicate();
1743 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1744 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001745 SDOperand Op1 = getValue(I.getOperand(0));
1746 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001747 ISD::CondCode Condition, FOC, FPC;
1748 switch (predicate) {
1749 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1750 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1751 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1752 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1753 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1754 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1755 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1756 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1757 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1758 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1759 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1760 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1761 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1762 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1763 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1764 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1765 default:
1766 assert(!"Invalid FCmp predicate value");
1767 FOC = FPC = ISD::SETFALSE;
1768 break;
1769 }
1770 if (FiniteOnlyFPMath())
1771 Condition = FOC;
1772 else
1773 Condition = FPC;
1774 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001775}
1776
1777void SelectionDAGLowering::visitSelect(User &I) {
1778 SDOperand Cond = getValue(I.getOperand(0));
1779 SDOperand TrueVal = getValue(I.getOperand(1));
1780 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001781 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001782 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1783 TrueVal, FalseVal));
1784 } else {
1785 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1786 *(TrueVal.Val->op_end()-2),
1787 *(TrueVal.Val->op_end()-1)));
1788 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001789}
1790
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001791
1792void SelectionDAGLowering::visitTrunc(User &I) {
1793 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1794 SDOperand N = getValue(I.getOperand(0));
1795 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1796 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1797}
1798
1799void SelectionDAGLowering::visitZExt(User &I) {
1800 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1801 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1802 SDOperand N = getValue(I.getOperand(0));
1803 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1804 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1805}
1806
1807void SelectionDAGLowering::visitSExt(User &I) {
1808 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1809 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1810 SDOperand N = getValue(I.getOperand(0));
1811 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1812 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1813}
1814
1815void SelectionDAGLowering::visitFPTrunc(User &I) {
1816 // FPTrunc is never a no-op cast, no need to check
1817 SDOperand N = getValue(I.getOperand(0));
1818 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1819 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1820}
1821
1822void SelectionDAGLowering::visitFPExt(User &I){
1823 // FPTrunc is never a no-op cast, no need to check
1824 SDOperand N = getValue(I.getOperand(0));
1825 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1826 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1827}
1828
1829void SelectionDAGLowering::visitFPToUI(User &I) {
1830 // FPToUI is never a no-op cast, no need to check
1831 SDOperand N = getValue(I.getOperand(0));
1832 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1833 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1834}
1835
1836void SelectionDAGLowering::visitFPToSI(User &I) {
1837 // FPToSI is never a no-op cast, no need to check
1838 SDOperand N = getValue(I.getOperand(0));
1839 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1840 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1841}
1842
1843void SelectionDAGLowering::visitUIToFP(User &I) {
1844 // UIToFP is never a no-op cast, no need to check
1845 SDOperand N = getValue(I.getOperand(0));
1846 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1847 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1848}
1849
1850void SelectionDAGLowering::visitSIToFP(User &I){
1851 // UIToFP is never a no-op cast, no need to check
1852 SDOperand N = getValue(I.getOperand(0));
1853 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1854 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1855}
1856
1857void SelectionDAGLowering::visitPtrToInt(User &I) {
1858 // What to do depends on the size of the integer and the size of the pointer.
1859 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001860 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001861 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001862 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001863 SDOperand Result;
1864 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1865 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1866 else
1867 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1868 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1869 setValue(&I, Result);
1870}
Chris Lattner7a60d912005-01-07 07:47:53 +00001871
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001872void SelectionDAGLowering::visitIntToPtr(User &I) {
1873 // What to do depends on the size of the integer and the size of the pointer.
1874 // We can either truncate, zero extend, or no-op, accordingly.
1875 SDOperand N = getValue(I.getOperand(0));
1876 MVT::ValueType SrcVT = N.getValueType();
1877 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1878 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1879 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1880 else
1881 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1882 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1883}
1884
1885void SelectionDAGLowering::visitBitCast(User &I) {
1886 SDOperand N = getValue(I.getOperand(0));
1887 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001888 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001889 // This is a cast to a vector from something else.
1890 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001891 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001892 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1893 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1894 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1895 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001896 return;
1897 }
1898 MVT::ValueType SrcVT = N.getValueType();
1899 if (SrcVT == MVT::Vector) {
1900 // This is a cast from a vctor to something else.
1901 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001902 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001904 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001905
1906 // BitCast assures us that source and destination are the same size so this
1907 // is either a BIT_CONVERT or a no-op.
1908 if (DestVT != N.getValueType())
1909 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1910 else
1911 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001912}
1913
Chris Lattner67271862006-03-29 00:11:43 +00001914void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001915 SDOperand InVec = getValue(I.getOperand(0));
1916 SDOperand InVal = getValue(I.getOperand(1));
1917 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1918 getValue(I.getOperand(2)));
1919
Chris Lattner29b23012006-03-19 01:17:20 +00001920 SDOperand Num = *(InVec.Val->op_end()-2);
1921 SDOperand Typ = *(InVec.Val->op_end()-1);
1922 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1923 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001924}
1925
Chris Lattner67271862006-03-29 00:11:43 +00001926void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001927 SDOperand InVec = getValue(I.getOperand(0));
1928 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1929 getValue(I.getOperand(1)));
1930 SDOperand Typ = *(InVec.Val->op_end()-1);
1931 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1932 TLI.getValueType(I.getType()), InVec, InIdx));
1933}
Chris Lattner32206f52006-03-18 01:44:44 +00001934
Chris Lattner098c01e2006-04-08 04:15:24 +00001935void SelectionDAGLowering::visitShuffleVector(User &I) {
1936 SDOperand V1 = getValue(I.getOperand(0));
1937 SDOperand V2 = getValue(I.getOperand(1));
1938 SDOperand Mask = getValue(I.getOperand(2));
1939
1940 SDOperand Num = *(V1.Val->op_end()-2);
1941 SDOperand Typ = *(V2.Val->op_end()-1);
1942 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1943 V1, V2, Mask, Num, Typ));
1944}
1945
1946
Chris Lattner7a60d912005-01-07 07:47:53 +00001947void SelectionDAGLowering::visitGetElementPtr(User &I) {
1948 SDOperand N = getValue(I.getOperand(0));
1949 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001950
1951 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1952 OI != E; ++OI) {
1953 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001954 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001955 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001956 if (Field) {
1957 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001958 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001959 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001960 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001961 }
1962 Ty = StTy->getElementType(Field);
1963 } else {
1964 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001965
Chris Lattner43535a12005-11-09 04:45:33 +00001966 // If this is a constant subscript, handle it quickly.
1967 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001968 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001969 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001970 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001971 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1972 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001973 }
Chris Lattner43535a12005-11-09 04:45:33 +00001974
1975 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001976 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001977 SDOperand IdxN = getValue(Idx);
1978
1979 // If the index is smaller or larger than intptr_t, truncate or extend
1980 // it.
1981 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001982 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001983 } else if (IdxN.getValueType() > N.getValueType())
1984 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1985
1986 // If this is a multiply by a power of two, turn it into a shl
1987 // immediately. This is a very common case.
1988 if (isPowerOf2_64(ElementSize)) {
1989 unsigned Amt = Log2_64(ElementSize);
1990 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001991 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001992 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1993 continue;
1994 }
1995
1996 SDOperand Scale = getIntPtrConstant(ElementSize);
1997 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1998 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001999 }
2000 }
2001 setValue(&I, N);
2002}
2003
2004void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2005 // If this is a fixed sized alloca in the entry block of the function,
2006 // allocate it statically on the stack.
2007 if (FuncInfo.StaticAllocaMap.count(&I))
2008 return; // getValue will auto-populate this.
2009
2010 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002011 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002012 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002013 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002014 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002015
2016 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002017 MVT::ValueType IntPtr = TLI.getPointerTy();
2018 if (IntPtr < AllocSize.getValueType())
2019 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2020 else if (IntPtr > AllocSize.getValueType())
2021 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002022
Chris Lattnereccb73d2005-01-22 23:04:37 +00002023 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002024 getIntPtrConstant(TySize));
2025
2026 // Handle alignment. If the requested alignment is less than or equal to the
2027 // stack alignment, ignore it and round the size of the allocation up to the
2028 // stack alignment size. If the size is greater than the stack alignment, we
2029 // note this in the DYNAMIC_STACKALLOC node.
2030 unsigned StackAlign =
2031 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2032 if (Align <= StackAlign) {
2033 Align = 0;
2034 // Add SA-1 to the size.
2035 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2036 getIntPtrConstant(StackAlign-1));
2037 // Mask out the low bits for alignment purposes.
2038 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2039 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2040 }
2041
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002042 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002043 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2044 MVT::Other);
2045 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002046 setValue(&I, DSA);
2047 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002048
2049 // Inform the Frame Information that we have just allocated a variable-sized
2050 // object.
2051 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2052}
2053
Chris Lattner7a60d912005-01-07 07:47:53 +00002054void SelectionDAGLowering::visitLoad(LoadInst &I) {
2055 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002056
Chris Lattner4d9651c2005-01-17 22:19:26 +00002057 SDOperand Root;
2058 if (I.isVolatile())
2059 Root = getRoot();
2060 else {
2061 // Do not serialize non-volatile loads against each other.
2062 Root = DAG.getRoot();
2063 }
Chris Lattner4024c002006-03-15 22:19:46 +00002064
Evan Chenge71fe34d2006-10-09 20:57:25 +00002065 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00002066 Root, I.isVolatile()));
2067}
2068
2069SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002070 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00002071 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002072 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002073 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002074 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002075 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2076 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002077 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00002078 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002079 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002080
Chris Lattner4024c002006-03-15 22:19:46 +00002081 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002082 DAG.setRoot(L.getValue(1));
2083 else
2084 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002085
2086 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002087}
2088
2089
2090void SelectionDAGLowering::visitStore(StoreInst &I) {
2091 Value *SrcV = I.getOperand(0);
2092 SDOperand Src = getValue(SrcV);
2093 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002094 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00002095 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002096}
2097
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002098/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2099/// access memory and has no other side effects at all.
2100static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2101#define GET_NO_MEMORY_INTRINSICS
2102#include "llvm/Intrinsics.gen"
2103#undef GET_NO_MEMORY_INTRINSICS
2104 return false;
2105}
2106
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002107// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2108// have any side-effects or if it only reads memory.
2109static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2110#define GET_SIDE_EFFECT_INFO
2111#include "llvm/Intrinsics.gen"
2112#undef GET_SIDE_EFFECT_INFO
2113 return false;
2114}
2115
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002116/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2117/// node.
2118void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2119 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002120 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002121 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002122
2123 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002124 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002125 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2126 if (OnlyLoad) {
2127 // We don't need to serialize loads against other loads.
2128 Ops.push_back(DAG.getRoot());
2129 } else {
2130 Ops.push_back(getRoot());
2131 }
2132 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002133
2134 // Add the intrinsic ID as an integer operand.
2135 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2136
2137 // Add all operands of the call to the operand list.
2138 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2139 SDOperand Op = getValue(I.getOperand(i));
2140
Reid Spencer09575ba2007-02-15 03:39:18 +00002141 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002142 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002143 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002144 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2145
2146 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2147 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2148 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2149 }
2150
2151 assert(TLI.isTypeLegal(Op.getValueType()) &&
2152 "Intrinsic uses a non-legal type?");
2153 Ops.push_back(Op);
2154 }
2155
2156 std::vector<MVT::ValueType> VTs;
2157 if (I.getType() != Type::VoidTy) {
2158 MVT::ValueType VT = TLI.getValueType(I.getType());
2159 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002160 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002161 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2162
2163 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2164 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2165 }
2166
2167 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2168 VTs.push_back(VT);
2169 }
2170 if (HasChain)
2171 VTs.push_back(MVT::Other);
2172
Chris Lattnerbd887772006-08-14 23:53:35 +00002173 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2174
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002175 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002176 SDOperand Result;
2177 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002178 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2179 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002180 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002181 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2182 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002183 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002184 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2185 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002186
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002187 if (HasChain) {
2188 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2189 if (OnlyLoad)
2190 PendingLoads.push_back(Chain);
2191 else
2192 DAG.setRoot(Chain);
2193 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002194 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002195 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002196 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2197 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2198 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2199 DAG.getValueType(EVT));
2200 }
2201 setValue(&I, Result);
2202 }
2203}
2204
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002205/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2206/// we want to emit this as a call to a named external function, return the name
2207/// otherwise lower it and return null.
2208const char *
2209SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2210 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002211 default:
2212 // By default, turn this into a target intrinsic node.
2213 visitTargetIntrinsic(I, Intrinsic);
2214 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002215 case Intrinsic::vastart: visitVAStart(I); return 0;
2216 case Intrinsic::vaend: visitVAEnd(I); return 0;
2217 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002218 case Intrinsic::returnaddress:
2219 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2220 getValue(I.getOperand(1))));
2221 return 0;
2222 case Intrinsic::frameaddress:
2223 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2224 getValue(I.getOperand(1))));
2225 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002226 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002227 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002228 break;
2229 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002230 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002231 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002232 case Intrinsic::memcpy_i32:
2233 case Intrinsic::memcpy_i64:
2234 visitMemIntrinsic(I, ISD::MEMCPY);
2235 return 0;
2236 case Intrinsic::memset_i32:
2237 case Intrinsic::memset_i64:
2238 visitMemIntrinsic(I, ISD::MEMSET);
2239 return 0;
2240 case Intrinsic::memmove_i32:
2241 case Intrinsic::memmove_i64:
2242 visitMemIntrinsic(I, ISD::MEMMOVE);
2243 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002244
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002245 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002246 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002247 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002248 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002249 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002250
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002251 Ops[0] = getRoot();
2252 Ops[1] = getValue(SPI.getLineValue());
2253 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002254
Jim Laskeyc56315c2007-01-26 21:22:28 +00002255 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002256 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002257 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2258
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002259 Ops[3] = DAG.getString(CompileUnit->getFileName());
2260 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002261
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002262 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002263 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002264
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002265 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002266 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002267 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002268 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002269 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002270 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2271 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002272 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002273 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002274 }
2275
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002276 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002277 }
2278 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002279 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002280 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002281 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2282 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002283 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002284 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002285 }
2286
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002287 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002288 }
2289 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002290 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002291 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002292 if (MMI && FSI.getSubprogram() &&
2293 MMI->Verify(FSI.getSubprogram())) {
2294 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002295 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002296 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002297 }
2298
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002299 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002300 }
2301 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002302 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002303 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002304 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002305 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002306 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002307 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002308 }
2309
2310 return 0;
2311 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002312
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002313 case Intrinsic::eh_exception: {
2314 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2315
Jim Laskey504e9942007-02-22 15:38:06 +00002316 if (MMI) {
2317 // Add a label to mark the beginning of the landing pad. Deletion of the
2318 // landing pad can thus be detected via the MachineModuleInfo.
2319 unsigned LabelID = MMI->addLandingPad(CurMBB);
2320 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2321 DAG.getConstant(LabelID, MVT::i32)));
2322
2323 // Mark exception register as live in.
2324 unsigned Reg = TLI.getExceptionAddressRegister();
2325 if (Reg) CurMBB->addLiveIn(Reg);
2326
2327 // Insert the EXCEPTIONADDR instruction.
2328 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2329 SDOperand Ops[1];
2330 Ops[0] = DAG.getRoot();
2331 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2332 setValue(&I, Op);
2333 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002334 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002335 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002336 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002337 return 0;
2338 }
2339
Jim Laskeyd5453d72007-03-01 20:24:30 +00002340 case Intrinsic::eh_selector:
2341 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002342 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2343
Jim Laskey504e9942007-02-22 15:38:06 +00002344 if (MMI) {
2345 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002346 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2347 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2348 isa<Function>(CE->getOperand(0)) &&
2349 "Personality should be a function");
2350 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002351 if (Intrinsic == Intrinsic::eh_filter)
2352 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002353
Jim Laskey504e9942007-02-22 15:38:06 +00002354 // Gather all the type infos for this landing pad and pass them along to
2355 // MachineModuleInfo.
2356 std::vector<GlobalVariable *> TyInfo;
2357 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002358 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2359 if (CE && CE->getOpcode() == Instruction::BitCast &&
2360 isa<GlobalVariable>(CE->getOperand(0))) {
2361 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2362 } else {
2363 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2364 assert(CI && CI->getZExtValue() == 0 &&
2365 "TypeInfo must be a global variable typeinfo or NULL");
2366 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002367 }
Jim Laskey504e9942007-02-22 15:38:06 +00002368 }
2369 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2370
2371 // Mark exception selector register as live in.
2372 unsigned Reg = TLI.getExceptionSelectorRegister();
2373 if (Reg) CurMBB->addLiveIn(Reg);
2374
2375 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002376 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002377 SDOperand Ops[2];
2378 Ops[0] = getValue(I.getOperand(1));
2379 Ops[1] = getRoot();
2380 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2381 setValue(&I, Op);
2382 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002383 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002384 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002385 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002386
2387 return 0;
2388 }
2389
2390 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002391 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002392
Jim Laskey504e9942007-02-22 15:38:06 +00002393 if (MMI) {
2394 // Find the type id for the given typeinfo.
2395 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002396 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2397 if (CE && CE->getOpcode() == Instruction::BitCast &&
2398 isa<GlobalVariable>(CE->getOperand(0))) {
2399 GV = cast<GlobalVariable>(CE->getOperand(0));
2400 } else {
2401 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2402 assert(CI && CI->getZExtValue() == 0 &&
2403 "TypeInfo must be a global variable typeinfo or NULL");
2404 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002405 }
2406
2407 unsigned TypeID = MMI->getTypeIDFor(GV);
2408 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002409 } else {
2410 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002411 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002412
2413 return 0;
2414 }
2415
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002416 case Intrinsic::sqrt_f32:
2417 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002418 setValue(&I, DAG.getNode(ISD::FSQRT,
2419 getValue(I.getOperand(1)).getValueType(),
2420 getValue(I.getOperand(1))));
2421 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002422 case Intrinsic::powi_f32:
2423 case Intrinsic::powi_f64:
2424 setValue(&I, DAG.getNode(ISD::FPOWI,
2425 getValue(I.getOperand(1)).getValueType(),
2426 getValue(I.getOperand(1)),
2427 getValue(I.getOperand(2))));
2428 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002429 case Intrinsic::pcmarker: {
2430 SDOperand Tmp = getValue(I.getOperand(1));
2431 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2432 return 0;
2433 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002434 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002435 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002436 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2437 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2438 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002439 setValue(&I, Tmp);
2440 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002441 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002442 }
Reid Spencercce90f52007-04-04 23:48:25 +00002443 case Intrinsic::bit_part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002444 // Currently not implemented: just abort
2445 assert(0 && "bit_part_select intrinsic not implemented");
2446 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002447 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002448 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002449 setValue(&I, DAG.getNode(ISD::BSWAP,
2450 getValue(I.getOperand(1)).getValueType(),
2451 getValue(I.getOperand(1))));
2452 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002453 case Intrinsic::cttz: {
2454 SDOperand Arg = getValue(I.getOperand(1));
2455 MVT::ValueType Ty = Arg.getValueType();
2456 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2457 if (Ty < MVT::i32)
2458 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2459 else if (Ty > MVT::i32)
2460 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2461 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002462 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002463 }
2464 case Intrinsic::ctlz: {
2465 SDOperand Arg = getValue(I.getOperand(1));
2466 MVT::ValueType Ty = Arg.getValueType();
2467 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2468 if (Ty < MVT::i32)
2469 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2470 else if (Ty > MVT::i32)
2471 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2472 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002473 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002474 }
2475 case Intrinsic::ctpop: {
2476 SDOperand Arg = getValue(I.getOperand(1));
2477 MVT::ValueType Ty = Arg.getValueType();
2478 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2479 if (Ty < MVT::i32)
2480 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2481 else if (Ty > MVT::i32)
2482 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2483 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002484 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002485 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002486 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002487 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002488 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2489 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002490 setValue(&I, Tmp);
2491 DAG.setRoot(Tmp.getValue(1));
2492 return 0;
2493 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002494 case Intrinsic::stackrestore: {
2495 SDOperand Tmp = getValue(I.getOperand(1));
2496 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002497 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002498 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002499 case Intrinsic::prefetch:
2500 // FIXME: Currently discarding prefetches.
2501 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002502 }
2503}
2504
2505
Jim Laskey31fef782007-02-23 21:45:01 +00002506void SelectionDAGLowering::LowerCallTo(Instruction &I,
2507 const Type *CalledValueTy,
2508 unsigned CallingConv,
2509 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002510 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002511 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002512 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002513 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey504e9942007-02-22 15:38:06 +00002514
2515 TargetLowering::ArgListTy Args;
2516 TargetLowering::ArgListEntry Entry;
2517 Args.reserve(I.getNumOperands());
2518 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2519 Value *Arg = I.getOperand(i);
2520 SDOperand ArgNode = getValue(Arg);
2521 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencer71b79e32007-04-09 06:17:21 +00002522 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, SExtAttribute);
2523 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ZExtAttribute);
2524 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, InRegAttribute);
2525 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, StructRetAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002526 Args.push_back(Entry);
2527 }
2528
2529 std::pair<SDOperand,SDOperand> Result =
2530 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer71b79e32007-04-09 06:17:21 +00002531 Attrs && Attrs->paramHasAttr(0, SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002532 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002533 Callee, Args, DAG);
2534 if (I.getType() != Type::VoidTy)
2535 setValue(&I, Result.first);
2536 DAG.setRoot(Result.second);
2537}
2538
2539
Chris Lattner7a60d912005-01-07 07:47:53 +00002540void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002541 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002542 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002543 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002544 if (unsigned IID = F->getIntrinsicID()) {
2545 RenameFn = visitIntrinsicCall(I, IID);
2546 if (!RenameFn)
2547 return;
2548 } else { // Not an LLVM intrinsic.
2549 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002550 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2551 if (I.getNumOperands() == 3 && // Basic sanity checks.
2552 I.getOperand(1)->getType()->isFloatingPoint() &&
2553 I.getType() == I.getOperand(1)->getType() &&
2554 I.getType() == I.getOperand(2)->getType()) {
2555 SDOperand LHS = getValue(I.getOperand(1));
2556 SDOperand RHS = getValue(I.getOperand(2));
2557 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2558 LHS, RHS));
2559 return;
2560 }
2561 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002562 if (I.getNumOperands() == 2 && // Basic sanity checks.
2563 I.getOperand(1)->getType()->isFloatingPoint() &&
2564 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002565 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002566 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2567 return;
2568 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002569 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002570 if (I.getNumOperands() == 2 && // Basic sanity checks.
2571 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002572 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002573 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002574 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2575 return;
2576 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002577 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002578 if (I.getNumOperands() == 2 && // Basic sanity checks.
2579 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002580 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002581 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002582 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2583 return;
2584 }
2585 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002586 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002587 } else if (isa<InlineAsm>(I.getOperand(0))) {
2588 visitInlineAsm(I);
2589 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002590 }
Misha Brukman835702a2005-04-21 22:36:52 +00002591
Chris Lattner18d2b342005-01-08 22:48:57 +00002592 SDOperand Callee;
2593 if (!RenameFn)
2594 Callee = getValue(I.getOperand(0));
2595 else
2596 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002597
Jim Laskey31fef782007-02-23 21:45:01 +00002598 LowerCallTo(I, I.getCalledValue()->getType(),
2599 I.getCallingConv(),
2600 I.isTailCall(),
2601 Callee,
2602 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002603}
2604
Jim Laskey504e9942007-02-22 15:38:06 +00002605
Chris Lattner6f87d182006-02-22 22:37:12 +00002606SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002607 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002608 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2609 Chain = Val.getValue(1);
2610 Flag = Val.getValue(2);
2611
2612 // If the result was expanded, copy from the top part.
2613 if (Regs.size() > 1) {
2614 assert(Regs.size() == 2 &&
2615 "Cannot expand to more than 2 elts yet!");
2616 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002617 Chain = Hi.getValue(1);
2618 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002619 if (DAG.getTargetLoweringInfo().isLittleEndian())
2620 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2621 else
2622 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002623 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002624
Chris Lattner705948d2006-06-08 18:22:48 +00002625 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002626 // appropriate type.
2627 if (RegVT == ValueVT)
2628 return Val;
2629
Chris Lattner77f04792007-03-25 05:00:54 +00002630 if (MVT::isVector(RegVT)) {
2631 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2632 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2633 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2634 MVT::i32),
2635 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2636 }
2637
Chris Lattner705948d2006-06-08 18:22:48 +00002638 if (MVT::isInteger(RegVT)) {
2639 if (ValueVT < RegVT)
2640 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2641 else
2642 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002643 }
Chris Lattner77f04792007-03-25 05:00:54 +00002644
2645 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2646 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002647}
2648
Chris Lattner571d9642006-02-23 19:21:04 +00002649/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2650/// specified value into the registers specified by this object. This uses
2651/// Chain/Flag as the input and updates them for the output Chain/Flag.
2652void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002653 SDOperand &Chain, SDOperand &Flag,
2654 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002655 if (Regs.size() == 1) {
2656 // If there is a single register and the types differ, this must be
2657 // a promotion.
2658 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002659 if (MVT::isVector(RegVT)) {
2660 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2661 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002662 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002663 if (RegVT < ValueVT)
2664 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2665 else
2666 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002667 } else if (MVT::isFloatingPoint(RegVT) &&
2668 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002669 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002670 } else if (MVT::getSizeInBits(RegVT) ==
2671 MVT::getSizeInBits(Val.getValueType())) {
2672 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2673 } else {
2674 assert(0 && "Unknown mismatch!");
2675 }
Chris Lattner571d9642006-02-23 19:21:04 +00002676 }
2677 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2678 Flag = Chain.getValue(1);
2679 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002680 std::vector<unsigned> R(Regs);
2681 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2682 std::reverse(R.begin(), R.end());
2683
2684 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002685 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002686 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002687 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002688 Flag = Chain.getValue(1);
2689 }
2690 }
2691}
Chris Lattner6f87d182006-02-22 22:37:12 +00002692
Chris Lattner571d9642006-02-23 19:21:04 +00002693/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2694/// operand list. This adds the code marker and includes the number of
2695/// values added into it.
2696void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002697 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002698 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2699 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002700 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2701 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2702}
Chris Lattner6f87d182006-02-22 22:37:12 +00002703
2704/// isAllocatableRegister - If the specified register is safe to allocate,
2705/// i.e. it isn't a stack pointer or some other special register, return the
2706/// register class for the register. Otherwise, return null.
2707static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002708isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2709 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002710 MVT::ValueType FoundVT = MVT::Other;
2711 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002712 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2713 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002714 MVT::ValueType ThisVT = MVT::Other;
2715
Chris Lattnerb1124f32006-02-22 23:09:03 +00002716 const TargetRegisterClass *RC = *RCI;
2717 // If none of the the value types for this register class are valid, we
2718 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002719 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2720 I != E; ++I) {
2721 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002722 // If we have already found this register in a different register class,
2723 // choose the one with the largest VT specified. For example, on
2724 // PowerPC, we favor f64 register classes over f32.
2725 if (FoundVT == MVT::Other ||
2726 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2727 ThisVT = *I;
2728 break;
2729 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002730 }
2731 }
2732
Chris Lattnerbec582f2006-04-02 00:24:45 +00002733 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002734
Chris Lattner6f87d182006-02-22 22:37:12 +00002735 // NOTE: This isn't ideal. In particular, this might allocate the
2736 // frame pointer in functions that need it (due to them not being taken
2737 // out of allocation, because a variable sized allocation hasn't been seen
2738 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002739 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2740 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002741 if (*I == Reg) {
2742 // We found a matching register class. Keep looking at others in case
2743 // we find one with larger registers that this physreg is also in.
2744 FoundRC = RC;
2745 FoundVT = ThisVT;
2746 break;
2747 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002748 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002749 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002750}
2751
2752RegsForValue SelectionDAGLowering::
2753GetRegistersForValue(const std::string &ConstrCode,
2754 MVT::ValueType VT, bool isOutReg, bool isInReg,
2755 std::set<unsigned> &OutputRegs,
2756 std::set<unsigned> &InputRegs) {
2757 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2758 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2759 std::vector<unsigned> Regs;
2760
2761 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2762 MVT::ValueType RegVT;
2763 MVT::ValueType ValueVT = VT;
2764
Chris Lattner55402d42006-11-02 01:41:49 +00002765 // If this is a constraint for a specific physical register, like {r17},
2766 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002767 if (PhysReg.first) {
2768 if (VT == MVT::Other)
2769 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002770
2771 // Get the actual register value type. This is important, because the user
2772 // may have asked for (e.g.) the AX register in i32 type. We need to
2773 // remember that AX is actually i16 to get the right extension.
2774 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002775
2776 // This is a explicit reference to a physical register.
2777 Regs.push_back(PhysReg.first);
2778
2779 // If this is an expanded reference, add the rest of the regs to Regs.
2780 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002781 TargetRegisterClass::iterator I = PhysReg.second->begin();
2782 TargetRegisterClass::iterator E = PhysReg.second->end();
2783 for (; *I != PhysReg.first; ++I)
2784 assert(I != E && "Didn't find reg!");
2785
2786 // Already added the first reg.
2787 --NumRegs; ++I;
2788 for (; NumRegs; --NumRegs, ++I) {
2789 assert(I != E && "Ran out of registers to allocate!");
2790 Regs.push_back(*I);
2791 }
2792 }
2793 return RegsForValue(Regs, RegVT, ValueVT);
2794 }
2795
Chris Lattner55402d42006-11-02 01:41:49 +00002796 // Otherwise, if this was a reference to an LLVM register class, create vregs
2797 // for this reference.
2798 std::vector<unsigned> RegClassRegs;
2799 if (PhysReg.second) {
2800 // If this is an early clobber or tied register, our regalloc doesn't know
2801 // how to maintain the constraint. If it isn't, go ahead and create vreg
2802 // and let the regalloc do the right thing.
2803 if (!isOutReg || !isInReg) {
2804 if (VT == MVT::Other)
2805 ValueVT = *PhysReg.second->vt_begin();
2806 RegVT = *PhysReg.second->vt_begin();
2807
2808 // Create the appropriate number of virtual registers.
2809 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2810 for (; NumRegs; --NumRegs)
2811 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2812
2813 return RegsForValue(Regs, RegVT, ValueVT);
2814 }
2815
2816 // Otherwise, we can't allocate it. Let the code below figure out how to
2817 // maintain these constraints.
2818 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2819
2820 } else {
2821 // This is a reference to a register class that doesn't directly correspond
2822 // to an LLVM register class. Allocate NumRegs consecutive, available,
2823 // registers from the class.
2824 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2825 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002826
2827 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2828 MachineFunction &MF = *CurMBB->getParent();
2829 unsigned NumAllocated = 0;
2830 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2831 unsigned Reg = RegClassRegs[i];
2832 // See if this register is available.
2833 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2834 (isInReg && InputRegs.count(Reg))) { // Already used.
2835 // Make sure we find consecutive registers.
2836 NumAllocated = 0;
2837 continue;
2838 }
2839
2840 // Check to see if this register is allocatable (i.e. don't give out the
2841 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002842 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002843 if (!RC) {
2844 // Make sure we find consecutive registers.
2845 NumAllocated = 0;
2846 continue;
2847 }
2848
2849 // Okay, this register is good, we can use it.
2850 ++NumAllocated;
2851
Chris Lattner1c741e92007-04-06 17:47:14 +00002852 // If we allocated enough consecutive registers, succeed.
Chris Lattner6f87d182006-02-22 22:37:12 +00002853 if (NumAllocated == NumRegs) {
2854 unsigned RegStart = (i-NumAllocated)+1;
2855 unsigned RegEnd = i+1;
2856 // Mark all of the allocated registers used.
2857 for (unsigned i = RegStart; i != RegEnd; ++i) {
2858 unsigned Reg = RegClassRegs[i];
2859 Regs.push_back(Reg);
2860 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2861 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2862 }
2863
2864 return RegsForValue(Regs, *RC->vt_begin(), VT);
2865 }
2866 }
2867
2868 // Otherwise, we couldn't allocate enough registers for this.
2869 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002870}
2871
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002872/// getConstraintGenerality - Return an integer indicating how general CT is.
2873static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2874 switch (CT) {
2875 default: assert(0 && "Unknown constraint type!");
2876 case TargetLowering::C_Other:
2877 case TargetLowering::C_Unknown:
2878 return 0;
2879 case TargetLowering::C_Register:
2880 return 1;
2881 case TargetLowering::C_RegisterClass:
2882 return 2;
2883 case TargetLowering::C_Memory:
2884 return 3;
2885 }
2886}
2887
2888static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2889 const TargetLowering &TLI) {
2890 assert(!C.empty() && "Must have at least one constraint");
2891 if (C.size() == 1) return C[0];
2892
2893 std::string *Current = &C[0];
2894 // If we have multiple constraints, try to pick the most general one ahead
2895 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00002896 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002897 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002898 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002899 if (getConstraintGenerality(ThisFlavor) >
2900 getConstraintGenerality(Flavor)) {
2901 // This constraint letter is more general than the previous one,
2902 // use it.
2903 Flavor = ThisFlavor;
2904 Current = &C[j];
2905 }
2906 }
2907 return *Current;
2908}
2909
Chris Lattner6f87d182006-02-22 22:37:12 +00002910
Chris Lattner476e67b2006-01-26 22:24:51 +00002911/// visitInlineAsm - Handle a call to an InlineAsm object.
2912///
2913void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2914 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2915
2916 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2917 MVT::Other);
2918
Chris Lattner3a5ed552006-02-01 01:28:23 +00002919 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002920 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002921
2922 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2923 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2924 /// if it is a def of that register.
2925 std::vector<SDOperand> AsmNodeOperands;
2926 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2927 AsmNodeOperands.push_back(AsmStr);
2928
2929 SDOperand Chain = getRoot();
2930 SDOperand Flag;
2931
Chris Lattner1558fc62006-02-01 18:59:47 +00002932 // We fully assign registers here at isel time. This is not optimal, but
2933 // should work. For register classes that correspond to LLVM classes, we
2934 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2935 // over the constraints, collecting fixed registers that we know we can't use.
2936 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002937 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002938 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002939 std::string ConstraintCode =
2940 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002941
Chris Lattner7ad77df2006-02-22 00:56:39 +00002942 MVT::ValueType OpVT;
2943
2944 // Compute the value type for each operand and add it to ConstraintVTs.
2945 switch (Constraints[i].Type) {
2946 case InlineAsm::isOutput:
2947 if (!Constraints[i].isIndirectOutput) {
2948 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2949 OpVT = TLI.getValueType(I.getType());
2950 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002951 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002952 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2953 OpNum++; // Consumes a call operand.
2954 }
2955 break;
2956 case InlineAsm::isInput:
2957 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2958 OpNum++; // Consumes a call operand.
2959 break;
2960 case InlineAsm::isClobber:
2961 OpVT = MVT::Other;
2962 break;
2963 }
2964
2965 ConstraintVTs.push_back(OpVT);
2966
Chris Lattner6f87d182006-02-22 22:37:12 +00002967 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2968 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002969
Chris Lattner6f87d182006-02-22 22:37:12 +00002970 // Build a list of regs that this operand uses. This always has a single
2971 // element for promoted/expanded operands.
2972 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2973 false, false,
2974 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002975
2976 switch (Constraints[i].Type) {
2977 case InlineAsm::isOutput:
2978 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002979 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002980 // If this is an early-clobber output, it cannot be assigned to the same
2981 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002982 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002983 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002984 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002985 case InlineAsm::isInput:
2986 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002987 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002988 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002989 case InlineAsm::isClobber:
2990 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002991 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2992 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002993 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002994 }
2995 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002996
Chris Lattner5c79f982006-02-21 23:12:12 +00002997 // Loop over all of the inputs, copying the operand values into the
2998 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002999 RegsForValue RetValRegs;
3000 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003001 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00003002
Chris Lattner2e56e892006-01-31 02:03:41 +00003003 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003004 std::string ConstraintCode =
3005 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003006
Chris Lattner3a5ed552006-02-01 01:28:23 +00003007 switch (Constraints[i].Type) {
3008 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003009 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3010 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00003011 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003012
3013 if (CTy == TargetLowering::C_Memory) {
3014 // Memory output.
3015 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3016
3017 // Check that the operand (the address to store to) isn't a float.
3018 if (!MVT::isInteger(InOperandVal.getValueType()))
3019 assert(0 && "MATCH FAIL!");
3020
3021 if (!Constraints[i].isIndirectOutput)
3022 assert(0 && "MATCH FAIL!");
3023
3024 OpNum++; // Consumes a call operand.
3025
3026 // Extend/truncate to the right pointer type if needed.
3027 MVT::ValueType PtrType = TLI.getPointerTy();
3028 if (InOperandVal.getValueType() < PtrType)
3029 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3030 else if (InOperandVal.getValueType() > PtrType)
3031 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3032
3033 // Add information to the INLINEASM node to know about this output.
3034 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3035 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3036 AsmNodeOperands.push_back(InOperandVal);
3037 break;
3038 }
3039
3040 // Otherwise, this is a register output.
3041 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3042
Chris Lattner6f87d182006-02-22 22:37:12 +00003043 // If this is an early-clobber output, or if there is an input
3044 // constraint that matches this, we need to reserve the input register
3045 // so no other inputs allocate to it.
3046 bool UsesInputRegister = false;
3047 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3048 UsesInputRegister = true;
3049
3050 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003051 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00003052 RegsForValue Regs =
3053 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3054 true, UsesInputRegister,
3055 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00003056 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003057 cerr << "Couldn't allocate output reg for contraint '"
3058 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003059 exit(1);
3060 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003061
Chris Lattner3a5ed552006-02-01 01:28:23 +00003062 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003063 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003064 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003065 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00003066 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003067 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003068 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3069 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003070 OpNum++; // Consumes a call operand.
3071 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003072
3073 // Add information to the INLINEASM node to know that this register is
3074 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00003075 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003076 break;
3077 }
3078 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003079 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00003080 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00003081
Chris Lattner7f5880b2006-02-02 00:25:23 +00003082 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3083 // If this is required to match an output register we have already set,
3084 // just use its register.
3085 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003086
Chris Lattner571d9642006-02-23 19:21:04 +00003087 // Scan until we find the definition we already emitted of this operand.
3088 // When we find it, create a RegsForValue operand.
3089 unsigned CurOp = 2; // The first operand.
3090 for (; OperandNo; --OperandNo) {
3091 // Advance to the next operand.
3092 unsigned NumOps =
3093 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003094 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3095 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003096 "Skipped past definitions?");
3097 CurOp += (NumOps>>3)+1;
3098 }
3099
3100 unsigned NumOps =
3101 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003102 if ((NumOps & 7) == 2 /*REGDEF*/) {
3103 // Add NumOps>>3 registers to MatchedRegs.
3104 RegsForValue MatchedRegs;
3105 MatchedRegs.ValueVT = InOperandVal.getValueType();
3106 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3107 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3108 unsigned Reg =
3109 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3110 MatchedRegs.Regs.push_back(Reg);
3111 }
Chris Lattner571d9642006-02-23 19:21:04 +00003112
Chris Lattnere3eeb242007-02-01 01:21:12 +00003113 // Use the produced MatchedRegs object to
3114 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3115 TLI.getPointerTy());
3116 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3117 break;
3118 } else {
3119 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3120 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003121 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003122 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003123
3124 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3125 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00003126 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00003127
3128 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00003129 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3130 ConstraintCode[0], DAG);
3131 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003132 cerr << "Invalid operand for inline asm constraint '"
3133 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003134 exit(1);
3135 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003136
3137 // Add information to the INLINEASM node to know about this input.
3138 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3139 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3140 AsmNodeOperands.push_back(InOperandVal);
3141 break;
3142 } else if (CTy == TargetLowering::C_Memory) {
3143 // Memory input.
3144
Chris Lattnerce8aba02007-03-08 22:29:47 +00003145 // If the operand is a float, spill to a constant pool entry to get its
3146 // address.
3147 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3148 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3149
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003150 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00003151 cerr << "Match failed, cannot handle this yet!\n";
3152 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003153 exit(1);
3154 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003155
3156 // Extend/truncate to the right pointer type if needed.
3157 MVT::ValueType PtrType = TLI.getPointerTy();
3158 if (InOperandVal.getValueType() < PtrType)
3159 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3160 else if (InOperandVal.getValueType() > PtrType)
3161 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3162
3163 // Add information to the INLINEASM node to know about this input.
3164 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3165 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3166 AsmNodeOperands.push_back(InOperandVal);
3167 break;
3168 }
3169
3170 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3171
3172 // Copy the input into the appropriate registers.
3173 RegsForValue InRegs =
3174 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3175 false, true, OutputRegs, InputRegs);
3176 // FIXME: should be match fail.
3177 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3178
Evan Chengef9e07d2006-06-15 08:11:54 +00003179 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003180
3181 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003182 break;
3183 }
Chris Lattner571d9642006-02-23 19:21:04 +00003184 case InlineAsm::isClobber: {
3185 RegsForValue ClobberedRegs =
3186 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3187 OutputRegs, InputRegs);
3188 // Add the clobbered value to the operand list, so that the register
3189 // allocator is aware that the physreg got clobbered.
3190 if (!ClobberedRegs.Regs.empty())
3191 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003192 break;
3193 }
Chris Lattner571d9642006-02-23 19:21:04 +00003194 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003195 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003196
3197 // Finish up input operands.
3198 AsmNodeOperands[0] = Chain;
3199 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3200
Chris Lattnerbd887772006-08-14 23:53:35 +00003201 Chain = DAG.getNode(ISD::INLINEASM,
3202 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003203 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003204 Flag = Chain.getValue(1);
3205
Chris Lattner2e56e892006-01-31 02:03:41 +00003206 // If this asm returns a register value, copy the result from that register
3207 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003208 if (!RetValRegs.Regs.empty())
3209 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00003210
Chris Lattner2e56e892006-01-31 02:03:41 +00003211 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3212
3213 // Process indirect outputs, first output all of the flagged copies out of
3214 // physregs.
3215 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003216 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003217 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003218 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3219 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003220 }
3221
3222 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003223 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003224 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00003225 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003226 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003227 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003228 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003229 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3230 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003231 DAG.setRoot(Chain);
3232}
3233
3234
Chris Lattner7a60d912005-01-07 07:47:53 +00003235void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3236 SDOperand Src = getValue(I.getOperand(0));
3237
3238 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003239
3240 if (IntPtr < Src.getValueType())
3241 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3242 else if (IntPtr > Src.getValueType())
3243 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003244
3245 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003246 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003247 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3248 Src, getIntPtrConstant(ElementSize));
3249
Reid Spencere63b6512006-12-31 05:55:36 +00003250 TargetLowering::ArgListTy Args;
3251 TargetLowering::ArgListEntry Entry;
3252 Entry.Node = Src;
3253 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003254 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003255
3256 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003257 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003258 DAG.getExternalSymbol("malloc", IntPtr),
3259 Args, DAG);
3260 setValue(&I, Result.first); // Pointers always fit in registers
3261 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003262}
3263
3264void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003265 TargetLowering::ArgListTy Args;
3266 TargetLowering::ArgListEntry Entry;
3267 Entry.Node = getValue(I.getOperand(0));
3268 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003269 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003270 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003271 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003272 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003273 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3274 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003275}
3276
Chris Lattner13d7c252005-08-26 20:54:47 +00003277// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3278// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3279// instructions are special in various ways, which require special support to
3280// insert. The specified MachineInstr is created but not inserted into any
3281// basic blocks, and the scheduler passes ownership of it to this method.
3282MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3283 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003284 cerr << "If a target marks an instruction with "
3285 << "'usesCustomDAGSchedInserter', it must implement "
3286 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003287 abort();
3288 return 0;
3289}
3290
Chris Lattner58cfd792005-01-09 00:00:49 +00003291void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003292 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3293 getValue(I.getOperand(1)),
3294 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003295}
3296
3297void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003298 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3299 getValue(I.getOperand(0)),
3300 DAG.getSrcValue(I.getOperand(0)));
3301 setValue(&I, V);
3302 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003303}
3304
3305void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003306 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3307 getValue(I.getOperand(1)),
3308 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003309}
3310
3311void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003312 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3313 getValue(I.getOperand(1)),
3314 getValue(I.getOperand(2)),
3315 DAG.getSrcValue(I.getOperand(1)),
3316 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003317}
3318
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003319/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3320/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3321static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3322 unsigned &i, SelectionDAG &DAG,
3323 TargetLowering &TLI) {
3324 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3325 return SDOperand(Arg, i++);
3326
3327 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3328 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3329 if (NumVals == 1) {
3330 return DAG.getNode(ISD::BIT_CONVERT, VT,
3331 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3332 } else if (NumVals == 2) {
3333 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3334 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3335 if (!TLI.isLittleEndian())
3336 std::swap(Lo, Hi);
3337 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3338 } else {
3339 // Value scalarized into many values. Unimp for now.
3340 assert(0 && "Cannot expand i64 -> i16 yet!");
3341 }
3342 return SDOperand();
3343}
3344
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003345/// TargetLowering::LowerArguments - This is the default LowerArguments
3346/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003347/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3348/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003349std::vector<SDOperand>
3350TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003351 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003352 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003353 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3354 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003355 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003356 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3357 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3358
3359 // Add one result value for each formal argument.
3360 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003361 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003362 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3363 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003364 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003365 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003366 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003367 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003368
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003369 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3370 // that is zero extended!
Reid Spencer71b79e32007-04-09 06:17:21 +00003371 if (Attrs && Attrs->paramHasAttr(j, ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003372 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer71b79e32007-04-09 06:17:21 +00003373 if (Attrs && Attrs->paramHasAttr(j, SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003374 Flags |= ISD::ParamFlags::SExt;
Reid Spencer71b79e32007-04-09 06:17:21 +00003375 if (Attrs && Attrs->paramHasAttr(j, InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003376 Flags |= ISD::ParamFlags::InReg;
Reid Spencer71b79e32007-04-09 06:17:21 +00003377 if (Attrs && Attrs->paramHasAttr(j, StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003378 Flags |= ISD::ParamFlags::StructReturn;
3379 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003380
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003381 switch (getTypeAction(VT)) {
3382 default: assert(0 && "Unknown type action!");
3383 case Legal:
3384 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003385 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003386 break;
3387 case Promote:
3388 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003389 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003390 break;
3391 case Expand:
3392 if (VT != MVT::Vector) {
3393 // If this is a large integer, it needs to be broken up into small
3394 // integers. Figure out what the destination type is and how many small
3395 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003396 MVT::ValueType NVT = getTypeToExpandTo(VT);
3397 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003398 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003399 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003400 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003401 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003402 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3403 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003404 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3405 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003406 } else {
3407 // Otherwise, this is a vector type. We only support legal vectors
3408 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003409 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3410 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003411
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003412 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003413 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003414 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3415 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3416 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003417 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003418 } else {
3419 assert(0 && "Don't support illegal by-val vector arguments yet!");
3420 }
3421 }
3422 break;
3423 }
3424 }
Evan Cheng9618df12006-04-25 23:03:35 +00003425
Chris Lattner3d826992006-05-16 06:45:34 +00003426 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003427
3428 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003429 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3430 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003431 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003432
3433 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003434
3435 // Set up the return result vector.
3436 Ops.clear();
3437 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003438 unsigned Idx = 1;
3439 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3440 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003441 MVT::ValueType VT = getValueType(I->getType());
3442
3443 switch (getTypeAction(VT)) {
3444 default: assert(0 && "Unknown type action!");
3445 case Legal:
3446 Ops.push_back(SDOperand(Result, i++));
3447 break;
3448 case Promote: {
3449 SDOperand Op(Result, i++);
3450 if (MVT::isInteger(VT)) {
Reid Spencer71b79e32007-04-09 06:17:21 +00003451 if (Attrs && Attrs->paramHasAttr(Idx, SExtAttribute))
Chris Lattner96035be2007-01-04 22:22:37 +00003452 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3453 DAG.getValueType(VT));
Reid Spencer71b79e32007-04-09 06:17:21 +00003454 else if (Attrs && Attrs->paramHasAttr(Idx, ZExtAttribute))
Chris Lattner96035be2007-01-04 22:22:37 +00003455 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3456 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003457 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3458 } else {
3459 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3460 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3461 }
3462 Ops.push_back(Op);
3463 break;
3464 }
3465 case Expand:
3466 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003467 // If this is a large integer or a floating point node that needs to be
3468 // expanded, it needs to be reassembled from small integers. Figure out
3469 // what the source elt type is and how many small integers it is.
3470 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003471 } else {
3472 // Otherwise, this is a vector type. We only support legal vectors
3473 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003474 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003475 unsigned NumElems = PTy->getNumElements();
3476 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003477
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003478 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003479 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003480 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003481 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003482 SDOperand N = SDOperand(Result, i++);
3483 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003484 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3485 DAG.getConstant(NumElems, MVT::i32),
3486 DAG.getValueType(getValueType(EltTy)));
3487 Ops.push_back(N);
3488 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003489 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003490 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003491 }
3492 }
3493 break;
3494 }
3495 }
3496 return Ops;
3497}
3498
Chris Lattneraaa23d92006-05-16 22:53:20 +00003499
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003500/// ExpandScalarCallArgs - Recursively expand call argument node by
3501/// bit_converting it or extract a pair of elements from the larger node.
3502static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003503 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003504 SmallVector<SDOperand, 32> &Ops,
3505 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003506 TargetLowering &TLI,
3507 bool isFirst = true) {
3508
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003509 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003510 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003511 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003512 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3513 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003514 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003515 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003516 return;
3517 }
3518
3519 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3520 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3521 if (NumVals == 1) {
3522 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003523 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003524 } else if (NumVals == 2) {
3525 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3526 DAG.getConstant(0, TLI.getPointerTy()));
3527 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3528 DAG.getConstant(1, TLI.getPointerTy()));
3529 if (!TLI.isLittleEndian())
3530 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003531 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3532 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003533 } else {
3534 // Value scalarized into many values. Unimp for now.
3535 assert(0 && "Cannot expand i64 -> i16 yet!");
3536 }
3537}
3538
Chris Lattneraaa23d92006-05-16 22:53:20 +00003539/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3540/// implementation, which just inserts an ISD::CALL node, which is later custom
3541/// lowered by the target to something concrete. FIXME: When all targets are
3542/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3543std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003544TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3545 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003546 unsigned CallingConv, bool isTailCall,
3547 SDOperand Callee,
3548 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003549 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003550 Ops.push_back(Chain); // Op#0 - Chain
3551 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3552 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3553 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3554 Ops.push_back(Callee);
3555
3556 // Handle all of the outgoing arguments.
3557 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003558 MVT::ValueType VT = getValueType(Args[i].Ty);
3559 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003560 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003561 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003562 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003563
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003564 if (Args[i].isSExt)
3565 Flags |= ISD::ParamFlags::SExt;
3566 if (Args[i].isZExt)
3567 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003568 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003569 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003570 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003571 Flags |= ISD::ParamFlags::StructReturn;
3572 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003573
Chris Lattneraaa23d92006-05-16 22:53:20 +00003574 switch (getTypeAction(VT)) {
3575 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003576 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003577 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003578 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003579 break;
3580 case Promote:
3581 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003582 unsigned ExtOp;
3583 if (Args[i].isSExt)
3584 ExtOp = ISD::SIGN_EXTEND;
3585 else if (Args[i].isZExt)
3586 ExtOp = ISD::ZERO_EXTEND;
3587 else
3588 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003589 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3590 } else {
3591 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3592 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3593 }
3594 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003595 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003596 break;
3597 case Expand:
3598 if (VT != MVT::Vector) {
3599 // If this is a large integer, it needs to be broken down into small
3600 // integers. Figure out what the source elt type is and how many small
3601 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003602 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003603 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003604 // Otherwise, this is a vector type. We only support legal vectors
3605 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003606 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003607 unsigned NumElems = PTy->getNumElements();
3608 const Type *EltTy = PTy->getElementType();
3609
3610 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003611 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003612 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003613 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003614 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003615 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3616 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003617 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003618 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003619 assert(0 && "Don't support illegal by-val vector call args yet!");
3620 abort();
3621 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003622 }
3623 break;
3624 }
3625 }
3626
3627 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003628 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003629
3630 if (RetTy != Type::VoidTy) {
3631 MVT::ValueType VT = getValueType(RetTy);
3632 switch (getTypeAction(VT)) {
3633 default: assert(0 && "Unknown type action!");
3634 case Legal:
3635 RetTys.push_back(VT);
3636 break;
3637 case Promote:
3638 RetTys.push_back(getTypeToTransformTo(VT));
3639 break;
3640 case Expand:
3641 if (VT != MVT::Vector) {
3642 // If this is a large integer, it needs to be reassembled from small
3643 // integers. Figure out what the source elt type is and how many small
3644 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003645 MVT::ValueType NVT = getTypeToExpandTo(VT);
3646 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003647 for (unsigned i = 0; i != NumVals; ++i)
3648 RetTys.push_back(NVT);
3649 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003650 // Otherwise, this is a vector type. We only support legal vectors
3651 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003652 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003653 unsigned NumElems = PTy->getNumElements();
3654 const Type *EltTy = PTy->getElementType();
3655
3656 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003657 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003658 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3659 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3660 RetTys.push_back(TVT);
3661 } else {
3662 assert(0 && "Don't support illegal by-val vector call results yet!");
3663 abort();
3664 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003665 }
3666 }
3667 }
3668
3669 RetTys.push_back(MVT::Other); // Always has a chain.
3670
3671 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003672 SDOperand Res = DAG.getNode(ISD::CALL,
3673 DAG.getVTList(&RetTys[0], RetTys.size()),
3674 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003675
3676 // This returns a pair of operands. The first element is the
3677 // return value for the function (if RetTy is not VoidTy). The second
3678 // element is the outgoing token chain.
3679 SDOperand ResVal;
3680 if (RetTys.size() != 1) {
3681 MVT::ValueType VT = getValueType(RetTy);
3682 if (RetTys.size() == 2) {
3683 ResVal = Res;
3684
3685 // If this value was promoted, truncate it down.
3686 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003687 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003688 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003689 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003690 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3691 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003692
3693 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003694 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003695 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003696 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003697 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3698 // "N x PTyElementVT" MVT::Vector type.
3699 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003700 DAG.getConstant(NumElems, MVT::i32),
3701 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003702 } else {
3703 abort();
3704 }
3705 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003706 unsigned AssertOp = ISD::AssertSext;
3707 if (!RetTyIsSigned)
3708 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003709 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3710 DAG.getValueType(VT));
3711 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3712 } else {
3713 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003714 if (getTypeAction(VT) == Expand)
3715 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3716 else
3717 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003718 }
3719 }
3720 } else if (RetTys.size() == 3) {
3721 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3722 Res.getValue(0), Res.getValue(1));
3723
3724 } else {
3725 assert(0 && "Case not handled yet!");
3726 }
3727 }
3728
3729 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3730}
3731
Chris Lattner29dcc712005-05-14 05:50:48 +00003732SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003733 assert(0 && "LowerOperation not implemented for this target!");
3734 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003735 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003736}
3737
Nate Begeman595ec732006-01-28 03:14:31 +00003738SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3739 SelectionDAG &DAG) {
3740 assert(0 && "CustomPromoteOperation not implemented for this target!");
3741 abort();
3742 return SDOperand();
3743}
3744
Evan Cheng6781b6e2006-02-15 21:59:04 +00003745/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003746/// operand.
3747static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003748 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003749 MVT::ValueType CurVT = VT;
3750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3751 uint64_t Val = C->getValue() & 255;
3752 unsigned Shift = 8;
3753 while (CurVT != MVT::i8) {
3754 Val = (Val << Shift) | Val;
3755 Shift <<= 1;
3756 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003757 }
3758 return DAG.getConstant(Val, VT);
3759 } else {
3760 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3761 unsigned Shift = 8;
3762 while (CurVT != MVT::i8) {
3763 Value =
3764 DAG.getNode(ISD::OR, VT,
3765 DAG.getNode(ISD::SHL, VT, Value,
3766 DAG.getConstant(Shift, MVT::i8)), Value);
3767 Shift <<= 1;
3768 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003769 }
3770
3771 return Value;
3772 }
3773}
3774
Evan Cheng6781b6e2006-02-15 21:59:04 +00003775/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3776/// used when a memcpy is turned into a memset when the source is a constant
3777/// string ptr.
3778static SDOperand getMemsetStringVal(MVT::ValueType VT,
3779 SelectionDAG &DAG, TargetLowering &TLI,
3780 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003781 uint64_t Val = 0;
3782 unsigned MSB = getSizeInBits(VT) / 8;
3783 if (TLI.isLittleEndian())
3784 Offset = Offset + MSB - 1;
3785 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003786 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003787 Offset += TLI.isLittleEndian() ? -1 : 1;
3788 }
3789 return DAG.getConstant(Val, VT);
3790}
3791
Evan Cheng81fcea82006-02-14 08:22:34 +00003792/// getMemBasePlusOffset - Returns base and offset node for the
3793static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3794 SelectionDAG &DAG, TargetLowering &TLI) {
3795 MVT::ValueType VT = Base.getValueType();
3796 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3797}
3798
Evan Chengdb2a7a72006-02-14 20:12:38 +00003799/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003800/// to replace the memset / memcpy is below the threshold. It also returns the
3801/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003802static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3803 unsigned Limit, uint64_t Size,
3804 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003805 MVT::ValueType VT;
3806
3807 if (TLI.allowsUnalignedMemoryAccesses()) {
3808 VT = MVT::i64;
3809 } else {
3810 switch (Align & 7) {
3811 case 0:
3812 VT = MVT::i64;
3813 break;
3814 case 4:
3815 VT = MVT::i32;
3816 break;
3817 case 2:
3818 VT = MVT::i16;
3819 break;
3820 default:
3821 VT = MVT::i8;
3822 break;
3823 }
3824 }
3825
Evan Chengd5026102006-02-14 09:11:59 +00003826 MVT::ValueType LVT = MVT::i64;
3827 while (!TLI.isTypeLegal(LVT))
3828 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3829 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003830
Evan Chengd5026102006-02-14 09:11:59 +00003831 if (VT > LVT)
3832 VT = LVT;
3833
Evan Cheng04514992006-02-14 23:05:54 +00003834 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003835 while (Size != 0) {
3836 unsigned VTSize = getSizeInBits(VT) / 8;
3837 while (VTSize > Size) {
3838 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003839 VTSize >>= 1;
3840 }
Evan Chengd5026102006-02-14 09:11:59 +00003841 assert(MVT::isInteger(VT));
3842
3843 if (++NumMemOps > Limit)
3844 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003845 MemOps.push_back(VT);
3846 Size -= VTSize;
3847 }
Evan Chengd5026102006-02-14 09:11:59 +00003848
3849 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003850}
3851
Chris Lattner875def92005-01-11 05:56:49 +00003852void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003853 SDOperand Op1 = getValue(I.getOperand(1));
3854 SDOperand Op2 = getValue(I.getOperand(2));
3855 SDOperand Op3 = getValue(I.getOperand(3));
3856 SDOperand Op4 = getValue(I.getOperand(4));
3857 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3858 if (Align == 0) Align = 1;
3859
3860 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3861 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003862
3863 // Expand memset / memcpy to a series of load / store ops
3864 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003865 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003866 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003867 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003868 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003869 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3870 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003871 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003872 unsigned Offset = 0;
3873 for (unsigned i = 0; i < NumMemOps; i++) {
3874 MVT::ValueType VT = MemOps[i];
3875 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003876 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003877 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003878 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003879 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003880 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003881 Offset += VTSize;
3882 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003883 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003884 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003885 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003886 case ISD::MEMCPY: {
3887 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3888 Size->getValue(), Align, TLI)) {
3889 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003890 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003891 GlobalAddressSDNode *G = NULL;
3892 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003893 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003894
3895 if (Op2.getOpcode() == ISD::GlobalAddress)
3896 G = cast<GlobalAddressSDNode>(Op2);
3897 else if (Op2.getOpcode() == ISD::ADD &&
3898 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3899 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3900 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003901 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003902 }
3903 if (G) {
3904 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003905 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003906 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003907 if (!Str.empty()) {
3908 CopyFromStr = true;
3909 SrcOff += SrcDelta;
3910 }
3911 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003912 }
3913
Evan Chenge2038bd2006-02-15 01:54:51 +00003914 for (unsigned i = 0; i < NumMemOps; i++) {
3915 MVT::ValueType VT = MemOps[i];
3916 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003917 SDOperand Value, Chain, Store;
3918
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003919 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003920 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3921 Chain = getRoot();
3922 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003923 DAG.getStore(Chain, Value,
3924 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003925 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003926 } else {
3927 Value = DAG.getLoad(VT, getRoot(),
3928 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003929 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003930 Chain = Value.getValue(1);
3931 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003932 DAG.getStore(Chain, Value,
3933 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003934 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003935 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003936 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003937 SrcOff += VTSize;
3938 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003939 }
3940 }
3941 break;
3942 }
3943 }
3944
3945 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003946 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3947 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003948 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003949 }
3950 }
3951
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003952 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003953}
3954
Chris Lattner875def92005-01-11 05:56:49 +00003955//===----------------------------------------------------------------------===//
3956// SelectionDAGISel code
3957//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003958
3959unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3960 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3961}
3962
Chris Lattnerc9950c12005-08-17 06:37:43 +00003963void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003964 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00003965 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003966}
Chris Lattner7a60d912005-01-07 07:47:53 +00003967
Chris Lattner35397782005-12-05 07:10:48 +00003968
Chris Lattnerbba52192006-10-28 19:22:10 +00003969
Chris Lattner7a60d912005-01-07 07:47:53 +00003970bool SelectionDAGISel::runOnFunction(Function &Fn) {
3971 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3972 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00003973 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00003974
3975 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3976
3977 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3978 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003979
Evan Cheng276b44b2007-02-10 02:43:39 +00003980 // Add function live-ins to entry block live-in set.
3981 BasicBlock *EntryBB = &Fn.getEntryBlock();
3982 BB = FuncInfo.MBBMap[EntryBB];
3983 if (!MF.livein_empty())
3984 for (MachineFunction::livein_iterator I = MF.livein_begin(),
3985 E = MF.livein_end(); I != E; ++I)
3986 BB->addLiveIn(I->first);
3987
Chris Lattner7a60d912005-01-07 07:47:53 +00003988 return true;
3989}
3990
Chris Lattnered0110b2006-10-27 21:36:01 +00003991SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3992 unsigned Reg) {
3993 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003994 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003995 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003996 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003997
3998 // If this type is not legal, we must make sure to not create an invalid
3999 // register use.
4000 MVT::ValueType SrcVT = Op.getValueType();
4001 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004002 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004003 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004004 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004005 // Handle copies from generic vectors to registers.
4006 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004007 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004008 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004009
Chris Lattner5fe1f542006-03-31 02:06:56 +00004010 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4011 // MVT::Vector type.
4012 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4013 DAG.getConstant(NE, MVT::i32),
4014 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004015
Chris Lattner5fe1f542006-03-31 02:06:56 +00004016 // Loop over all of the elements of the resultant vector,
4017 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4018 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004019 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004020 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004021 for (unsigned i = 0; i != NE; ++i) {
4022 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004023 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004024 if (PTyElementVT == PTyLegalElementVT) {
4025 // Elements are legal.
4026 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4027 } else if (PTyLegalElementVT > PTyElementVT) {
4028 // Elements are promoted.
4029 if (MVT::isFloatingPoint(PTyLegalElementVT))
4030 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4031 else
4032 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4033 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4034 } else {
4035 // Elements are expanded.
4036 // The src value is expanded into multiple registers.
4037 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004038 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004039 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004040 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004041 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4042 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4043 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004044 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004045 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4046 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004047 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004048 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004049 if (MVT::isFloatingPoint(SrcVT))
4050 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4051 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004052 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004053 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004054 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004055 DestVT = TLI.getTypeToExpandTo(SrcVT);
4056 unsigned NumVals = TLI.getNumElements(SrcVT);
4057 if (NumVals == 1)
4058 return DAG.getCopyToReg(getRoot(), Reg,
4059 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4060 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004061 // The src value is expanded into multiple registers.
4062 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004063 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004064 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004065 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004066 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004067 return DAG.getCopyToReg(Op, Reg+1, Hi);
4068 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004069}
4070
Chris Lattner16f64df2005-01-17 17:15:02 +00004071void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004072LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004073 std::vector<SDOperand> &UnorderedChains) {
4074 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004075 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004076 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004077 SDOperand OldRoot = SDL.DAG.getRoot();
4078 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004079
Chris Lattner6871b232005-10-30 19:42:35 +00004080 unsigned a = 0;
4081 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4082 AI != E; ++AI, ++a)
4083 if (!AI->use_empty()) {
4084 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004085
Chris Lattner6871b232005-10-30 19:42:35 +00004086 // If this argument is live outside of the entry block, insert a copy from
4087 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004088 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4089 if (VMI != FuncInfo.ValueMap.end()) {
4090 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004091 UnorderedChains.push_back(Copy);
4092 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004093 }
Chris Lattner6871b232005-10-30 19:42:35 +00004094
Chris Lattner6871b232005-10-30 19:42:35 +00004095 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004096 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004097 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004098}
4099
Chris Lattner7a60d912005-01-07 07:47:53 +00004100void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4101 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004102 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004103 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004104
4105 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004106
Chris Lattner6871b232005-10-30 19:42:35 +00004107 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004108 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004109 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004110
4111 BB = FuncInfo.MBBMap[LLVMBB];
4112 SDL.setCurrentBasicBlock(BB);
4113
4114 // Lower all of the non-terminator instructions.
4115 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4116 I != E; ++I)
4117 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004118
4119 // Lower call part of invoke.
4120 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4121 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004122
Chris Lattner7a60d912005-01-07 07:47:53 +00004123 // Ensure that all instructions which are used outside of their defining
4124 // blocks are available as virtual registers.
4125 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004126 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004127 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004128 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004129 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004130 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004131 }
4132
4133 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4134 // ensure constants are generated when needed. Remember the virtual registers
4135 // that need to be added to the Machine PHI nodes as input. We cannot just
4136 // directly add them, because expansion might result in multiple MBB's for one
4137 // BB. As such, the start of the BB might correspond to a different MBB than
4138 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004139 //
Chris Lattner84a03502006-10-27 23:50:33 +00004140 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004141
4142 // Emit constants only once even if used by multiple PHI nodes.
4143 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004144
Chris Lattner84a03502006-10-27 23:50:33 +00004145 // Vector bool would be better, but vector<bool> is really slow.
4146 std::vector<unsigned char> SuccsHandled;
4147 if (TI->getNumSuccessors())
4148 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4149
Chris Lattner7a60d912005-01-07 07:47:53 +00004150 // Check successor nodes PHI nodes that expect a constant to be available from
4151 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004152 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4153 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004154 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004155 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004156
Chris Lattner84a03502006-10-27 23:50:33 +00004157 // If this terminator has multiple identical successors (common for
4158 // switches), only handle each succ once.
4159 unsigned SuccMBBNo = SuccMBB->getNumber();
4160 if (SuccsHandled[SuccMBBNo]) continue;
4161 SuccsHandled[SuccMBBNo] = true;
4162
4163 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004164 PHINode *PN;
4165
4166 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4167 // nodes and Machine PHI nodes, but the incoming operands have not been
4168 // emitted yet.
4169 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004170 (PN = dyn_cast<PHINode>(I)); ++I) {
4171 // Ignore dead phi's.
4172 if (PN->use_empty()) continue;
4173
4174 unsigned Reg;
4175 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004176
Chris Lattner84a03502006-10-27 23:50:33 +00004177 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4178 unsigned &RegOut = ConstantsOut[C];
4179 if (RegOut == 0) {
4180 RegOut = FuncInfo.CreateRegForValue(C);
4181 UnorderedChains.push_back(
4182 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004183 }
Chris Lattner84a03502006-10-27 23:50:33 +00004184 Reg = RegOut;
4185 } else {
4186 Reg = FuncInfo.ValueMap[PHIOp];
4187 if (Reg == 0) {
4188 assert(isa<AllocaInst>(PHIOp) &&
4189 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4190 "Didn't codegen value into a register!??");
4191 Reg = FuncInfo.CreateRegForValue(PHIOp);
4192 UnorderedChains.push_back(
4193 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004194 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004195 }
Chris Lattner84a03502006-10-27 23:50:33 +00004196
4197 // Remember that this register needs to added to the machine PHI node as
4198 // the input for this MBB.
4199 MVT::ValueType VT = TLI.getValueType(PN->getType());
4200 unsigned NumElements;
4201 if (VT != MVT::Vector)
4202 NumElements = TLI.getNumElements(VT);
4203 else {
4204 MVT::ValueType VT1,VT2;
4205 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004206 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004207 VT1, VT2);
4208 }
4209 for (unsigned i = 0, e = NumElements; i != e; ++i)
4210 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4211 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004212 }
4213 ConstantsOut.clear();
4214
Chris Lattner718b5c22005-01-13 17:59:43 +00004215 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004216 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004217 SDOperand Root = SDL.getRoot();
4218 if (Root.getOpcode() != ISD::EntryToken) {
4219 unsigned i = 0, e = UnorderedChains.size();
4220 for (; i != e; ++i) {
4221 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4222 if (UnorderedChains[i].Val->getOperand(0) == Root)
4223 break; // Don't add the root if we already indirectly depend on it.
4224 }
4225
4226 if (i == e)
4227 UnorderedChains.push_back(Root);
4228 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004229 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4230 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004231 }
4232
Chris Lattner7a60d912005-01-07 07:47:53 +00004233 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004234 if (Invoke) {
4235 // Just the branch part of invoke.
4236 SDL.visitInvoke(*Invoke, true);
4237 } else {
4238 SDL.visit(*LLVMBB->getTerminator());
4239 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004240
Nate Begemaned728c12006-03-27 01:32:24 +00004241 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004242 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004243 SwitchCases.clear();
4244 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004245 JTCases.clear();
4246 JTCases = SDL.JTCases;
Nate Begemaned728c12006-03-27 01:32:24 +00004247
Chris Lattner4108bb02005-01-17 19:43:36 +00004248 // Make sure the root of the DAG is up-to-date.
4249 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004250}
4251
Nate Begemaned728c12006-03-27 01:32:24 +00004252void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004253 // Get alias analysis for load/store combining.
4254 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4255
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004256 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004257 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004258
Bill Wendling22e978a2006-12-07 20:04:42 +00004259 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004260 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004261
Chris Lattner7a60d912005-01-07 07:47:53 +00004262 // Second step, hack on the DAG until it only uses operations and types that
4263 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004264 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004265
Bill Wendling22e978a2006-12-07 20:04:42 +00004266 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004267 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004268
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004269 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004270 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004271
Evan Cheng739a6a42006-01-21 02:32:06 +00004272 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004273
Chris Lattner5ca31d92005-03-30 01:10:47 +00004274 // Third, instruction select all of the operations to machine code, adding the
4275 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004276 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004277
Bill Wendling22e978a2006-12-07 20:04:42 +00004278 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004279 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004280}
Chris Lattner7a60d912005-01-07 07:47:53 +00004281
Nate Begemaned728c12006-03-27 01:32:24 +00004282void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4283 FunctionLoweringInfo &FuncInfo) {
4284 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4285 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004286 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004287 CurDAG = &DAG;
4288
4289 // First step, lower LLVM code to some DAG. This DAG may use operations and
4290 // types that are not supported by the target.
4291 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4292
4293 // Second step, emit the lowered DAG as machine code.
4294 CodeGenAndEmitDAG(DAG);
4295 }
4296
Chris Lattner5ca31d92005-03-30 01:10:47 +00004297 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004298 // PHI nodes in successors.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004299 if (SwitchCases.empty() && JTCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004300 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4301 MachineInstr *PHI = PHINodesToUpdate[i].first;
4302 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4303 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004304 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004305 PHI->addMachineBasicBlockOperand(BB);
4306 }
4307 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004308 }
Nate Begemaned728c12006-03-27 01:32:24 +00004309
Nate Begeman866b4b42006-04-23 06:26:20 +00004310 // If the JumpTable record is filled in, then we need to emit a jump table.
4311 // Updating the PHI nodes is tricky in this case, since we need to determine
4312 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004313 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4314 // Lower header first, if it wasn't already lowered
4315 if (!JTCases[i].first.Emitted) {
4316 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4317 CurDAG = &HSDAG;
4318 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4319 // Set the current basic block to the mbb we wish to insert the code into
4320 BB = JTCases[i].first.HeaderBB;
4321 HSDL.setCurrentBasicBlock(BB);
4322 // Emit the code
4323 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4324 HSDAG.setRoot(HSDL.getRoot());
4325 CodeGenAndEmitDAG(HSDAG);
4326 }
4327
4328 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4329 CurDAG = &JSDAG;
4330 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004331 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004332 BB = JTCases[i].second.MBB;
4333 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004334 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004335 JSDL.visitJumpTable(JTCases[i].second);
4336 JSDAG.setRoot(JSDL.getRoot());
4337 CodeGenAndEmitDAG(JSDAG);
4338
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004339 // Update PHI Nodes
4340 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4341 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4342 MachineBasicBlock *PHIBB = PHI->getParent();
4343 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4344 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov70378262007-03-25 15:07:15 +00004345 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004346 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004347 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004348 }
4349 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004350 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004351 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004352 }
4353 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004354 }
4355
Chris Lattner76a7bc82006-10-22 23:00:53 +00004356 // If the switch block involved a branch to one of the actual successors, we
4357 // need to update PHI nodes in that block.
4358 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4359 MachineInstr *PHI = PHINodesToUpdate[i].first;
4360 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4361 "This is not a machine PHI node that we are updating!");
4362 if (BB->isSuccessor(PHI->getParent())) {
4363 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4364 PHI->addMachineBasicBlockOperand(BB);
4365 }
4366 }
4367
Nate Begemaned728c12006-03-27 01:32:24 +00004368 // If we generated any switch lowering information, build and codegen any
4369 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004370 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004371 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004372 CurDAG = &SDAG;
4373 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004374
Nate Begemaned728c12006-03-27 01:32:24 +00004375 // Set the current basic block to the mbb we wish to insert the code into
4376 BB = SwitchCases[i].ThisBB;
4377 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004378
Nate Begemaned728c12006-03-27 01:32:24 +00004379 // Emit the code
4380 SDL.visitSwitchCase(SwitchCases[i]);
4381 SDAG.setRoot(SDL.getRoot());
4382 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004383
4384 // Handle any PHI nodes in successors of this chunk, as if we were coming
4385 // from the original BB before switch expansion. Note that PHI nodes can
4386 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4387 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004388 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004389 for (MachineBasicBlock::iterator Phi = BB->begin();
4390 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4391 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4392 for (unsigned pn = 0; ; ++pn) {
4393 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4394 if (PHINodesToUpdate[pn].first == Phi) {
4395 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4396 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4397 break;
4398 }
4399 }
Nate Begemaned728c12006-03-27 01:32:24 +00004400 }
Chris Lattner707339a52006-09-07 01:59:34 +00004401
4402 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004403 if (BB == SwitchCases[i].FalseBB)
4404 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004405
4406 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004407 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004408 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004409 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004410 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004411 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004412}
Evan Cheng739a6a42006-01-21 02:32:06 +00004413
Jim Laskey95eda5b2006-08-01 14:21:23 +00004414
Evan Cheng739a6a42006-01-21 02:32:06 +00004415//===----------------------------------------------------------------------===//
4416/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4417/// target node in the graph.
4418void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4419 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004420
Jim Laskey29e635d2006-08-02 12:30:23 +00004421 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004422
4423 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004424 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004425 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004426 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004427
Jim Laskey03593f72006-08-01 18:29:48 +00004428 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004429 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004430 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004431}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004432
Chris Lattner47639db2006-03-06 00:22:00 +00004433
Jim Laskey03593f72006-08-01 18:29:48 +00004434HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4435 return new HazardRecognizer();
4436}
4437
Chris Lattner6df34962006-10-11 03:58:02 +00004438//===----------------------------------------------------------------------===//
4439// Helper functions used by the generated instruction selector.
4440//===----------------------------------------------------------------------===//
4441// Calls to these methods are generated by tblgen.
4442
4443/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4444/// the dag combiner simplified the 255, we still want to match. RHS is the
4445/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4446/// specified in the .td file (e.g. 255).
4447bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4448 int64_t DesiredMaskS) {
4449 uint64_t ActualMask = RHS->getValue();
4450 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4451
4452 // If the actual mask exactly matches, success!
4453 if (ActualMask == DesiredMask)
4454 return true;
4455
4456 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4457 if (ActualMask & ~DesiredMask)
4458 return false;
4459
4460 // Otherwise, the DAG Combiner may have proven that the value coming in is
4461 // either already zero or is not demanded. Check for known zero input bits.
4462 uint64_t NeededMask = DesiredMask & ~ActualMask;
4463 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4464 return true;
4465
4466 // TODO: check to see if missing bits are just not demanded.
4467
4468 // Otherwise, this pattern doesn't match.
4469 return false;
4470}
4471
4472/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4473/// the dag combiner simplified the 255, we still want to match. RHS is the
4474/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4475/// specified in the .td file (e.g. 255).
4476bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4477 int64_t DesiredMaskS) {
4478 uint64_t ActualMask = RHS->getValue();
4479 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4480
4481 // If the actual mask exactly matches, success!
4482 if (ActualMask == DesiredMask)
4483 return true;
4484
4485 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4486 if (ActualMask & ~DesiredMask)
4487 return false;
4488
4489 // Otherwise, the DAG Combiner may have proven that the value coming in is
4490 // either already zero or is not demanded. Check for known zero input bits.
4491 uint64_t NeededMask = DesiredMask & ~ActualMask;
4492
4493 uint64_t KnownZero, KnownOne;
4494 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4495
4496 // If all the missing bits in the or are already known to be set, match!
4497 if ((NeededMask & KnownOne) == NeededMask)
4498 return true;
4499
4500 // TODO: check to see if missing bits are just not demanded.
4501
4502 // Otherwise, this pattern doesn't match.
4503 return false;
4504}
4505
Jim Laskey03593f72006-08-01 18:29:48 +00004506
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004507/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4508/// by tblgen. Others should not call it.
4509void SelectionDAGISel::
4510SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4511 std::vector<SDOperand> InOps;
4512 std::swap(InOps, Ops);
4513
4514 Ops.push_back(InOps[0]); // input chain.
4515 Ops.push_back(InOps[1]); // input asm string.
4516
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004517 unsigned i = 2, e = InOps.size();
4518 if (InOps[e-1].getValueType() == MVT::Flag)
4519 --e; // Don't process a flag operand if it is here.
4520
4521 while (i != e) {
4522 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4523 if ((Flags & 7) != 4 /*MEM*/) {
4524 // Just skip over this operand, copying the operands verbatim.
4525 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4526 i += (Flags >> 3) + 1;
4527 } else {
4528 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4529 // Otherwise, this is a memory operand. Ask the target to select it.
4530 std::vector<SDOperand> SelOps;
4531 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004532 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004533 exit(1);
4534 }
4535
4536 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00004537 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004538 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00004539 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004540 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4541 i += 2;
4542 }
4543 }
4544
4545 // Add the flag input back if present.
4546 if (e != InOps.size())
4547 Ops.push_back(InOps.back());
4548}