blob: e1a8c296b66a86550d315cdf7433507c2e4fc209 [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>
Jeff Cohen0475f3b2007-04-09 14:32:59 +000048#include <math.h>
Chris Lattner7a60d912005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattner975f5c92005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000058#else
Chris Lattneref598052006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000060#endif
61
Jim Laskey29e635d2006-08-02 12:30:23 +000062//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 }
255
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 }
Chris Lattner84a03502006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000292 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner49409cb2006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencer09575ba2007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner7a60d912005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner79084302007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000358
Chris Lattner4d9651c2005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000365 /// Case - A struct to record the Value for a switch case, and the
366 /// case's target basic block.
367 struct Case {
368 Constant* Low;
369 Constant* High;
370 MachineBasicBlock* BB;
371
372 Case() : Low(0), High(0), BB(0) { }
373 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
374 Low(low), High(high), BB(bb) { }
375 uint64_t size() const {
376 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
377 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
378 return (rHigh - rLow + 1ULL);
379 }
380 };
381
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000382 struct CaseBits {
383 uint64_t Mask;
384 MachineBasicBlock* BB;
385 unsigned Bits;
386
387 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
388 Mask(mask), BB(bb), Bits(bits) { }
389 };
390
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000391 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000392 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000393 typedef CaseVector::iterator CaseItr;
394 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000395
396 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
397 /// of conditional branches.
398 struct CaseRec {
399 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
400 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
401
402 /// CaseBB - The MBB in which to emit the compare and branch
403 MachineBasicBlock *CaseBB;
404 /// LT, GE - If nonzero, we know the current case value must be less-than or
405 /// greater-than-or-equal-to these Constants.
406 Constant *LT;
407 Constant *GE;
408 /// Range - A pair of iterators representing the range of case values to be
409 /// processed at this point in the binary search tree.
410 CaseRange Range;
411 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000412
413 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000414
415 /// The comparison function for sorting the switch case values in the vector.
416 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000417 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000418 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000419 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
420 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
421 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
422 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000423 }
424 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000425
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000426 struct CaseBitsCmp {
427 bool operator () (const CaseBits& C1, const CaseBits& C2) {
428 return C1.Bits > C2.Bits;
429 }
430 };
431
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000432 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000433
Chris Lattner7a60d912005-01-07 07:47:53 +0000434public:
435 // TLI - This is information that describes the available target features we
436 // need for lowering. This indicates when operations are unavailable,
437 // implemented with a libcall, etc.
438 TargetLowering &TLI;
439 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000440 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000441
Nate Begemaned728c12006-03-27 01:32:24 +0000442 /// SwitchCases - Vector of CaseBlock structures used to communicate
443 /// SwitchInst code generation information.
444 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000445 /// JTCases - Vector of JumpTable structures used to communicate
446 /// SwitchInst code generation information.
447 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000448 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000449
Chris Lattner7a60d912005-01-07 07:47:53 +0000450 /// FuncInfo - Information about the function as a whole.
451 ///
452 FunctionLoweringInfo &FuncInfo;
453
454 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000455 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000457 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000458 }
459
Chris Lattner4108bb02005-01-17 19:43:36 +0000460 /// getRoot - Return the current virtual root of the Selection DAG.
461 ///
462 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000463 if (PendingLoads.empty())
464 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000465
Chris Lattner4d9651c2005-01-17 22:19:26 +0000466 if (PendingLoads.size() == 1) {
467 SDOperand Root = PendingLoads[0];
468 DAG.setRoot(Root);
469 PendingLoads.clear();
470 return Root;
471 }
472
473 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000474 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
475 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000476 PendingLoads.clear();
477 DAG.setRoot(Root);
478 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000479 }
480
Chris Lattnered0110b2006-10-27 21:36:01 +0000481 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
482
Chris Lattner7a60d912005-01-07 07:47:53 +0000483 void visit(Instruction &I) { visit(I.getOpcode(), I); }
484
485 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000486 // Note: this doesn't use InstVisitor, because it has to work with
487 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 switch (Opcode) {
489 default: assert(0 && "Unknown instruction type encountered!");
490 abort();
491 // Build the switch statement using the Instruction.def file.
492#define HANDLE_INST(NUM, OPCODE, CLASS) \
493 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
494#include "llvm/Instruction.def"
495 }
496 }
497
498 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
499
Chris Lattner4024c002006-03-15 22:19:46 +0000500 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000501 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000502 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000503
504 SDOperand getIntPtrConstant(uint64_t Val) {
505 return DAG.getConstant(Val, TLI.getPointerTy());
506 }
507
Chris Lattner8471b152006-03-16 19:57:50 +0000508 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000509
Chris Lattner79084302007-02-04 01:31:47 +0000510 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 SDOperand &N = NodeMap[V];
512 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000513 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000514 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000515
Chris Lattner6f87d182006-02-22 22:37:12 +0000516 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
517 MVT::ValueType VT,
518 bool OutReg, bool InReg,
519 std::set<unsigned> &OutputRegs,
520 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000521
Chris Lattnered0110b2006-10-27 21:36:01 +0000522 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
523 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
524 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000525 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000526 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000527 void LowerCallTo(Instruction &I,
528 const Type *CalledValueTy, unsigned CallingConv,
529 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000530
Chris Lattner7a60d912005-01-07 07:47:53 +0000531 // Terminator instructions.
532 void visitRet(ReturnInst &I);
533 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000534 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 void visitUnreachable(UnreachableInst &I) { /* noop */ }
536
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000537 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000538 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000539 CaseRecVector& WorkList,
540 Value* SV,
541 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000542 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000543 CaseRecVector& WorkList,
544 Value* SV,
545 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000546 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000547 CaseRecVector& WorkList,
548 Value* SV,
549 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000550 bool handleBitTestsSwitchCase(CaseRec& CR,
551 CaseRecVector& WorkList,
552 Value* SV,
553 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000554 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000555 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
556 void visitBitTestCase(MachineBasicBlock* NextMBB,
557 unsigned Reg,
558 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000559 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000560 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
561 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000562
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000564 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000565 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000566 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000567
Reid Spencer2eadb532007-01-21 00:29:26 +0000568 void visitScalarBinary(User &I, unsigned OpCode);
569 void visitVectorBinary(User &I, unsigned OpCode);
570 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000571 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000572 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000573 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000574 visitVectorBinary(I, ISD::VADD);
575 else if (I.getType()->isFloatingPoint())
576 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000577 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000578 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000579 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000580 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000581 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000582 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000583 visitVectorBinary(I, ISD::VMUL);
584 else if (I.getType()->isFloatingPoint())
585 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000586 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000587 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000588 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000589 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
590 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
591 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
592 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
593 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
594 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
595 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
596 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
597 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
598 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000599 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
600 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000601 void visitICmp(User &I);
602 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000603 // Visit the conversion instructions
604 void visitTrunc(User &I);
605 void visitZExt(User &I);
606 void visitSExt(User &I);
607 void visitFPTrunc(User &I);
608 void visitFPExt(User &I);
609 void visitFPToUI(User &I);
610 void visitFPToSI(User &I);
611 void visitUIToFP(User &I);
612 void visitSIToFP(User &I);
613 void visitPtrToInt(User &I);
614 void visitIntToPtr(User &I);
615 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000616
Chris Lattner67271862006-03-29 00:11:43 +0000617 void visitExtractElement(User &I);
618 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000619 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000620
Chris Lattner7a60d912005-01-07 07:47:53 +0000621 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000622 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000623
624 void visitMalloc(MallocInst &I);
625 void visitFree(FreeInst &I);
626 void visitAlloca(AllocaInst &I);
627 void visitLoad(LoadInst &I);
628 void visitStore(StoreInst &I);
629 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
630 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000631 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000632 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000633 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000634
Chris Lattner7a60d912005-01-07 07:47:53 +0000635 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000636 void visitVAArg(VAArgInst &I);
637 void visitVAEnd(CallInst &I);
638 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000639
Chris Lattner875def92005-01-11 05:56:49 +0000640 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000641
642 void visitUserOp1(Instruction &I) {
643 assert(0 && "UserOp1 should not exist at instruction selection time!");
644 abort();
645 }
646 void visitUserOp2(Instruction &I) {
647 assert(0 && "UserOp2 should not exist at instruction selection time!");
648 abort();
649 }
650};
651} // end namespace llvm
652
Chris Lattner8471b152006-03-16 19:57:50 +0000653SDOperand SelectionDAGLowering::getValue(const Value *V) {
654 SDOperand &N = NodeMap[V];
655 if (N.Val) return N;
656
657 const Type *VTy = V->getType();
658 MVT::ValueType VT = TLI.getValueType(VTy);
659 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
660 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
661 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000662 SDOperand N1 = NodeMap[V];
663 assert(N1.Val && "visit didn't populate the ValueMap!");
664 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000665 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
666 return N = DAG.getGlobalAddress(GV, VT);
667 } else if (isa<ConstantPointerNull>(C)) {
668 return N = DAG.getConstant(0, TLI.getPointerTy());
669 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000670 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000671 return N = DAG.getNode(ISD::UNDEF, VT);
672
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000673 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000674 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000675 unsigned NumElements = PTy->getNumElements();
676 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
677
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000678 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000679 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
680
681 // Create a VConstant node with generic Vector type.
682 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
683 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000684 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
685 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000686 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
687 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000688 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000689 unsigned NumElements = PTy->getNumElements();
690 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000691
692 // Now that we know the number and type of the elements, push a
693 // Constant or ConstantFP node onto the ops list for each element of
694 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000695 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000696 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000697 for (unsigned i = 0; i != NumElements; ++i)
698 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000699 } else {
700 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
701 SDOperand Op;
702 if (MVT::isFloatingPoint(PVT))
703 Op = DAG.getConstantFP(0, PVT);
704 else
705 Op = DAG.getConstant(0, PVT);
706 Ops.assign(NumElements, Op);
707 }
708
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000709 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000710 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
711 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000712 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
713 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000714 } else {
715 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000716 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000717 }
718 }
719
720 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
721 std::map<const AllocaInst*, int>::iterator SI =
722 FuncInfo.StaticAllocaMap.find(AI);
723 if (SI != FuncInfo.StaticAllocaMap.end())
724 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
725 }
726
Chris Lattner8c504cf2007-02-25 18:40:32 +0000727 unsigned InReg = FuncInfo.ValueMap[V];
728 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000729
730 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000731 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000732 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000733 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000734 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000735 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
736 unsigned NumVals = TLI.getNumElements(VT);
737 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
738 if (NumVals == 1)
739 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
740 else {
741 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
742 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
743 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
744 }
745 } else {
746 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
747 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
748 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
749 N = MVT::isFloatingPoint(VT)
750 ? DAG.getNode(ISD::FP_ROUND, VT, N)
751 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000752 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000753 } else {
754 // Otherwise, if this is a vector, make it available as a generic vector
755 // here.
756 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000757 const VectorType *PTy = cast<VectorType>(VTy);
758 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000759 PTyLegalElementVT);
760
761 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000762 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000763 if (PTyElementVT == PTyLegalElementVT) {
764 // If the value types are legal, just VBUILD the CopyFromReg nodes.
765 for (unsigned i = 0; i != NE; ++i)
766 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
767 PTyElementVT));
768 } else if (PTyElementVT < PTyLegalElementVT) {
769 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
770 for (unsigned i = 0; i != NE; ++i) {
771 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
772 PTyElementVT);
773 if (MVT::isFloatingPoint(PTyElementVT))
774 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
775 else
776 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
777 Ops.push_back(Op);
778 }
779 } else {
780 // If the register was expanded, use BUILD_PAIR.
781 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
782 for (unsigned i = 0; i != NE/2; ++i) {
783 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
784 PTyElementVT);
785 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
786 PTyElementVT);
787 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
788 }
789 }
790
791 Ops.push_back(DAG.getConstant(NE, MVT::i32));
792 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000793 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000794
795 // Finally, use a VBIT_CONVERT to make this available as the appropriate
796 // vector type.
797 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
798 DAG.getConstant(PTy->getNumElements(),
799 MVT::i32),
800 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000801 }
802
803 return N;
804}
805
806
Chris Lattner7a60d912005-01-07 07:47:53 +0000807void SelectionDAGLowering::visitRet(ReturnInst &I) {
808 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000809 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000810 return;
811 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000812 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000813 NewValues.push_back(getRoot());
814 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
815 SDOperand RetOp = getValue(I.getOperand(i));
816
817 // If this is an integer return value, we need to promote it ourselves to
818 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
819 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000820 // FIXME: C calling convention requires the return type to be promoted to
821 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000822 if (MVT::isInteger(RetOp.getValueType()) &&
823 RetOp.getValueType() < MVT::i64) {
824 MVT::ValueType TmpVT;
825 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
826 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
827 else
828 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000829 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000830 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000831 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer71b79e32007-04-09 06:17:21 +0000832 if (Attrs && Attrs->paramHasAttr(0, SExtAttribute))
Reid Spencer0917adf2007-01-03 04:25:33 +0000833 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer71b79e32007-04-09 06:17:21 +0000834 if (Attrs && Attrs->paramHasAttr(0, ZExtAttribute))
Reid Spencere63b6512006-12-31 05:55:36 +0000835 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000836 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000837 }
838 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000839 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000840 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000841 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
842 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000843}
844
Chris Lattnered0110b2006-10-27 21:36:01 +0000845/// ExportFromCurrentBlock - If this condition isn't known to be exported from
846/// the current basic block, add it to ValueMap now so that we'll get a
847/// CopyTo/FromReg.
848void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
849 // No need to export constants.
850 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
851
852 // Already exported?
853 if (FuncInfo.isExportedInst(V)) return;
854
855 unsigned Reg = FuncInfo.InitializeRegForValue(V);
856 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
857}
858
Chris Lattner84a03502006-10-27 23:50:33 +0000859bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
860 const BasicBlock *FromBB) {
861 // The operands of the setcc have to be in this block. We don't know
862 // how to export them from some other block.
863 if (Instruction *VI = dyn_cast<Instruction>(V)) {
864 // Can export from current BB.
865 if (VI->getParent() == FromBB)
866 return true;
867
868 // Is already exported, noop.
869 return FuncInfo.isExportedInst(V);
870 }
871
872 // If this is an argument, we can export it if the BB is the entry block or
873 // if it is already exported.
874 if (isa<Argument>(V)) {
875 if (FromBB == &FromBB->getParent()->getEntryBlock())
876 return true;
877
878 // Otherwise, can only export this if it is already exported.
879 return FuncInfo.isExportedInst(V);
880 }
881
882 // Otherwise, constants can always be exported.
883 return true;
884}
885
Chris Lattnere60ae822006-10-29 21:01:20 +0000886static bool InBlock(const Value *V, const BasicBlock *BB) {
887 if (const Instruction *I = dyn_cast<Instruction>(V))
888 return I->getParent() == BB;
889 return true;
890}
891
Chris Lattnered0110b2006-10-27 21:36:01 +0000892/// FindMergedConditions - If Cond is an expression like
893void SelectionDAGLowering::FindMergedConditions(Value *Cond,
894 MachineBasicBlock *TBB,
895 MachineBasicBlock *FBB,
896 MachineBasicBlock *CurBB,
897 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000898 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000899 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000900
Reid Spencer266e42b2006-12-23 06:05:41 +0000901 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
902 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000903 BOp->getParent() != CurBB->getBasicBlock() ||
904 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
905 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000906 const BasicBlock *BB = CurBB->getBasicBlock();
907
Reid Spencer266e42b2006-12-23 06:05:41 +0000908 // If the leaf of the tree is a comparison, merge the condition into
909 // the caseblock.
910 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
911 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000912 // how to export them from some other block. If this is the first block
913 // of the sequence, no exporting is needed.
914 (CurBB == CurMBB ||
915 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
916 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000917 BOp = cast<Instruction>(Cond);
918 ISD::CondCode Condition;
919 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
920 switch (IC->getPredicate()) {
921 default: assert(0 && "Unknown icmp predicate opcode!");
922 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
923 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
924 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
925 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
926 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
927 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
928 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
929 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
930 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
931 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
932 }
933 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
934 ISD::CondCode FPC, FOC;
935 switch (FC->getPredicate()) {
936 default: assert(0 && "Unknown fcmp predicate opcode!");
937 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
938 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
939 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
940 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
941 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
942 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
943 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
944 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
945 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
946 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
947 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
948 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
949 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
950 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
951 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
952 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
953 }
954 if (FiniteOnlyFPMath())
955 Condition = FOC;
956 else
957 Condition = FPC;
958 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000959 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000960 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000961 }
962
Chris Lattnered0110b2006-10-27 21:36:01 +0000963 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000964 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000965 SwitchCases.push_back(CB);
966 return;
967 }
968
969 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000970 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000971 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000972 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000973 return;
974 }
975
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000976
977 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000978 MachineFunction::iterator BBI = CurBB;
979 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
980 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
981
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000982 if (Opc == Instruction::Or) {
983 // Codegen X | Y as:
984 // jmp_if_X TBB
985 // jmp TmpBB
986 // TmpBB:
987 // jmp_if_Y TBB
988 // jmp FBB
989 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000990
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000991 // Emit the LHS condition.
992 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
993
994 // Emit the RHS condition into TmpBB.
995 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
996 } else {
997 assert(Opc == Instruction::And && "Unknown merge op!");
998 // Codegen X & Y as:
999 // jmp_if_X TmpBB
1000 // jmp FBB
1001 // TmpBB:
1002 // jmp_if_Y TBB
1003 // jmp FBB
1004 //
1005 // This requires creation of TmpBB after CurBB.
1006
1007 // Emit the LHS condition.
1008 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1009
1010 // Emit the RHS condition into TmpBB.
1011 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1012 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001013}
1014
Chris Lattner427301f2006-10-31 22:37:42 +00001015/// If the set of cases should be emitted as a series of branches, return true.
1016/// If we should emit this as a bunch of and/or'd together conditions, return
1017/// false.
1018static bool
1019ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1020 if (Cases.size() != 2) return true;
1021
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001022 // If this is two comparisons of the same values or'd or and'd together, they
1023 // will get folded into a single comparison, so don't emit two blocks.
1024 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1025 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1026 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1027 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1028 return false;
1029 }
1030
Chris Lattner427301f2006-10-31 22:37:42 +00001031 return true;
1032}
1033
Chris Lattner7a60d912005-01-07 07:47:53 +00001034void SelectionDAGLowering::visitBr(BranchInst &I) {
1035 // Update machine-CFG edges.
1036 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001037
1038 // Figure out which block is immediately after the current one.
1039 MachineBasicBlock *NextBlock = 0;
1040 MachineFunction::iterator BBI = CurMBB;
1041 if (++BBI != CurMBB->getParent()->end())
1042 NextBlock = BBI;
1043
1044 if (I.isUnconditional()) {
1045 // If this is not a fall-through branch, emit the branch.
1046 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001047 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001048 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001049
Chris Lattner963ddad2006-10-24 17:57:59 +00001050 // Update machine-CFG edges.
1051 CurMBB->addSuccessor(Succ0MBB);
1052
1053 return;
1054 }
1055
1056 // If this condition is one of the special cases we handle, do special stuff
1057 // now.
1058 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001059 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001060
1061 // If this is a series of conditions that are or'd or and'd together, emit
1062 // this as a sequence of branches instead of setcc's with and/or operations.
1063 // For example, instead of something like:
1064 // cmp A, B
1065 // C = seteq
1066 // cmp D, E
1067 // F = setle
1068 // or C, F
1069 // jnz foo
1070 // Emit:
1071 // cmp A, B
1072 // je foo
1073 // cmp D, E
1074 // jle foo
1075 //
1076 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1077 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001078 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001079 BOp->getOpcode() == Instruction::Or)) {
1080 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001081 // If the compares in later blocks need to use values not currently
1082 // exported from this block, export them now. This block should always
1083 // be the first entry.
1084 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1085
Chris Lattner427301f2006-10-31 22:37:42 +00001086 // Allow some cases to be rejected.
1087 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001088 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1089 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1090 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1091 }
1092
1093 // Emit the branch for this block.
1094 visitSwitchCase(SwitchCases[0]);
1095 SwitchCases.erase(SwitchCases.begin());
1096 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001097 }
1098
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001099 // Okay, we decided not to do this, remove any inserted MBB's and clear
1100 // SwitchCases.
1101 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1102 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1103
Chris Lattner427301f2006-10-31 22:37:42 +00001104 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001105 }
1106 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001107
1108 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001109 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001110 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001111 // Use visitSwitchCase to actually insert the fast branch sequence for this
1112 // cond branch.
1113 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001114}
1115
Nate Begemaned728c12006-03-27 01:32:24 +00001116/// visitSwitchCase - Emits the necessary code to represent a single node in
1117/// the binary search tree resulting from lowering a switch instruction.
1118void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001119 SDOperand Cond;
1120 SDOperand CondLHS = getValue(CB.CmpLHS);
1121
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001122 // Build the setcc now.
1123 if (CB.CmpMHS == NULL) {
1124 // Fold "(X == true)" to X and "(X == false)" to !X to
1125 // handle common cases produced by branch lowering.
1126 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1127 Cond = CondLHS;
1128 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1129 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1130 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1131 } else
1132 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1133 } else {
1134 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001135
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001136 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1137 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1138
1139 SDOperand CmpOp = getValue(CB.CmpMHS);
1140 MVT::ValueType VT = CmpOp.getValueType();
1141
1142 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1143 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1144 } else {
1145 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1146 Cond = DAG.getSetCC(MVT::i1, SUB,
1147 DAG.getConstant(High-Low, VT), ISD::SETULE);
1148 }
1149
1150 }
1151
Nate Begemaned728c12006-03-27 01:32:24 +00001152 // Set NextBlock to be the MBB immediately after the current one, if any.
1153 // This is used to avoid emitting unnecessary branches to the next block.
1154 MachineBasicBlock *NextBlock = 0;
1155 MachineFunction::iterator BBI = CurMBB;
1156 if (++BBI != CurMBB->getParent()->end())
1157 NextBlock = BBI;
1158
1159 // If the lhs block is the next block, invert the condition so that we can
1160 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001161 if (CB.TrueBB == NextBlock) {
1162 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001163 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1164 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1165 }
1166 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001167 DAG.getBasicBlock(CB.TrueBB));
1168 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001169 DAG.setRoot(BrCond);
1170 else
1171 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001172 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001173 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001174 CurMBB->addSuccessor(CB.TrueBB);
1175 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001176}
1177
Anton Korobeynikov70378262007-03-25 15:07:15 +00001178/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001179void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001180 // Emit the code for the jump table
Anton Korobeynikov70378262007-03-25 15:07:15 +00001181 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001182 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001183 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1184 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1185 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1186 Table, Index));
1187 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001188}
1189
Anton Korobeynikov70378262007-03-25 15:07:15 +00001190/// visitJumpTableHeader - This function emits necessary code to produce index
1191/// in the JumpTable from switch case.
1192void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1193 SelectionDAGISel::JumpTableHeader &JTH) {
1194 // Subtract the lowest switch case value from the value being switched on
1195 // and conditional branch to default mbb if the result is greater than the
1196 // difference between smallest and largest cases.
1197 SDOperand SwitchOp = getValue(JTH.SValue);
1198 MVT::ValueType VT = SwitchOp.getValueType();
1199 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1200 DAG.getConstant(JTH.First, VT));
1201
1202 // The SDNode we just created, which holds the value being switched on
1203 // minus the the smallest case value, needs to be copied to a virtual
1204 // register so it can be used as an index into the jump table in a
1205 // subsequent basic block. This value may be smaller or larger than the
1206 // target's pointer type, and therefore require extension or truncating.
1207 if (VT > TLI.getPointerTy())
1208 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1209 else
1210 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1211
1212 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1213 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1214 JT.Reg = JumpTableReg;
1215
1216 // Emit the range check for the jump table, and branch to the default
1217 // block for the switch statement if the value being switched on exceeds
1218 // the largest case in the switch.
1219 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1220 DAG.getConstant(JTH.Last-JTH.First,VT),
1221 ISD::SETUGT);
1222
1223 // Set NextBlock to be the MBB immediately after the current one, if any.
1224 // This is used to avoid emitting unnecessary branches to the next block.
1225 MachineBasicBlock *NextBlock = 0;
1226 MachineFunction::iterator BBI = CurMBB;
1227 if (++BBI != CurMBB->getParent()->end())
1228 NextBlock = BBI;
1229
1230 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1231 DAG.getBasicBlock(JT.Default));
1232
1233 if (JT.MBB == NextBlock)
1234 DAG.setRoot(BrCond);
1235 else
1236 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001237 DAG.getBasicBlock(JT.MBB)));
1238
1239 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001240}
1241
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001242/// visitBitTestHeader - This function emits necessary code to produce value
1243/// suitable for "bit tests"
1244void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1245 // Subtract the minimum value
1246 SDOperand SwitchOp = getValue(B.SValue);
1247 MVT::ValueType VT = SwitchOp.getValueType();
1248 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1249 DAG.getConstant(B.First, VT));
1250
1251 // Check range
1252 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1253 DAG.getConstant(B.Range, VT),
1254 ISD::SETUGT);
1255
1256 SDOperand ShiftOp;
1257 if (VT > TLI.getShiftAmountTy())
1258 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1259 else
1260 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1261
1262 // Make desired shift
1263 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1264 DAG.getConstant(1, TLI.getPointerTy()),
1265 ShiftOp);
1266
1267 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1268 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1269 B.Reg = SwitchReg;
1270
1271 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1272 DAG.getBasicBlock(B.Default));
1273
1274 // Set NextBlock to be the MBB immediately after the current one, if any.
1275 // This is used to avoid emitting unnecessary branches to the next block.
1276 MachineBasicBlock *NextBlock = 0;
1277 MachineFunction::iterator BBI = CurMBB;
1278 if (++BBI != CurMBB->getParent()->end())
1279 NextBlock = BBI;
1280
1281 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1282 if (MBB == NextBlock)
1283 DAG.setRoot(BrRange);
1284 else
1285 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1286 DAG.getBasicBlock(MBB)));
1287
1288 CurMBB->addSuccessor(B.Default);
1289 CurMBB->addSuccessor(MBB);
1290
1291 return;
1292}
1293
1294/// visitBitTestCase - this function produces one "bit test"
1295void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1296 unsigned Reg,
1297 SelectionDAGISel::BitTestCase &B) {
1298 // Emit bit tests and jumps
1299 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1300
1301 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1302 SwitchVal,
1303 DAG.getConstant(B.Mask,
1304 TLI.getPointerTy()));
1305 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1306 DAG.getConstant(0, TLI.getPointerTy()),
1307 ISD::SETNE);
1308 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1309 AndCmp, DAG.getBasicBlock(B.TargetBB));
1310
1311 // Set NextBlock to be the MBB immediately after the current one, if any.
1312 // This is used to avoid emitting unnecessary branches to the next block.
1313 MachineBasicBlock *NextBlock = 0;
1314 MachineFunction::iterator BBI = CurMBB;
1315 if (++BBI != CurMBB->getParent()->end())
1316 NextBlock = BBI;
1317
1318 if (NextMBB == NextBlock)
1319 DAG.setRoot(BrAnd);
1320 else
1321 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1322 DAG.getBasicBlock(NextMBB)));
1323
1324 CurMBB->addSuccessor(B.TargetBB);
1325 CurMBB->addSuccessor(NextMBB);
1326
1327 return;
1328}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001329
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001330void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001331 assert(0 && "Should never be visited directly");
1332}
1333void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001334 // Retrieve successors.
1335 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1336 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1337
Jim Laskey14059d92007-02-25 21:43:59 +00001338 if (!AsTerminator) {
1339 // Mark landing pad so that it doesn't get deleted in branch folding.
1340 LandingPad->setIsLandingPad();
1341
1342 // Insert a label before the invoke call to mark the try range.
1343 // This can be used to detect deletion of the invoke via the
1344 // MachineModuleInfo.
1345 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1346 unsigned BeginLabel = MMI->NextLabelID();
1347 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1348 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001349
Jim Laskey14059d92007-02-25 21:43:59 +00001350 LowerCallTo(I, I.getCalledValue()->getType(),
1351 I.getCallingConv(),
1352 false,
1353 getValue(I.getOperand(0)),
1354 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001355
Jim Laskey14059d92007-02-25 21:43:59 +00001356 // Insert a label before the invoke call to mark the try range.
1357 // This can be used to detect deletion of the invoke via the
1358 // MachineModuleInfo.
1359 unsigned EndLabel = MMI->NextLabelID();
1360 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1361 DAG.getConstant(EndLabel, MVT::i32)));
1362
1363 // Inform MachineModuleInfo of range.
1364 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1365
1366 // Update successor info
1367 CurMBB->addSuccessor(Return);
1368 CurMBB->addSuccessor(LandingPad);
1369 } else {
1370 // Drop into normal successor.
1371 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1372 DAG.getBasicBlock(Return)));
1373 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001374}
1375
1376void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1377}
1378
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001379/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001380/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001381bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001382 CaseRecVector& WorkList,
1383 Value* SV,
1384 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001385 Case& BackCase = *(CR.Range.second-1);
1386
1387 // Size is the number of Cases represented by this range.
1388 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001389 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001390 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001391
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001392 // Get the MachineFunction which holds the current MBB. This is used when
1393 // inserting any additional MBBs necessary to represent the switch.
1394 MachineFunction *CurMF = CurMBB->getParent();
1395
1396 // Figure out which block is immediately after the current one.
1397 MachineBasicBlock *NextBlock = 0;
1398 MachineFunction::iterator BBI = CR.CaseBB;
1399
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001400 if (++BBI != CurMBB->getParent()->end())
1401 NextBlock = BBI;
1402
1403 // TODO: If any two of the cases has the same destination, and if one value
1404 // is the same as the other, but has one bit unset that the other has set,
1405 // use bit manipulation to do two compares at once. For example:
1406 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1407
1408 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001409 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001410 // The last case block won't fall through into 'NextBlock' if we emit the
1411 // branches in this order. See if rearranging a case value would help.
1412 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001413 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001414 std::swap(*I, BackCase);
1415 break;
1416 }
1417 }
1418 }
1419
1420 // Create a CaseBlock record representing a conditional branch to
1421 // the Case's target mbb if the value being switched on SV is equal
1422 // to C.
1423 MachineBasicBlock *CurBlock = CR.CaseBB;
1424 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1425 MachineBasicBlock *FallThrough;
1426 if (I != E-1) {
1427 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1428 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1429 } else {
1430 // If the last case doesn't match, go to the default block.
1431 FallThrough = Default;
1432 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001433
1434 Value *RHS, *LHS, *MHS;
1435 ISD::CondCode CC;
1436 if (I->High == I->Low) {
1437 // This is just small small case range :) containing exactly 1 case
1438 CC = ISD::SETEQ;
1439 LHS = SV; RHS = I->High; MHS = NULL;
1440 } else {
1441 CC = ISD::SETLE;
1442 LHS = I->Low; MHS = SV; RHS = I->High;
1443 }
1444 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1445 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001446
1447 // If emitting the first comparison, just call visitSwitchCase to emit the
1448 // code into the current block. Otherwise, push the CaseBlock onto the
1449 // vector to be later processed by SDISel, and insert the node's MBB
1450 // before the next MBB.
1451 if (CurBlock == CurMBB)
1452 visitSwitchCase(CB);
1453 else
1454 SwitchCases.push_back(CB);
1455
1456 CurBlock = FallThrough;
1457 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001458
1459 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001460}
1461
1462/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001463bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001464 CaseRecVector& WorkList,
1465 Value* SV,
1466 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001467 Case& FrontCase = *CR.Range.first;
1468 Case& BackCase = *(CR.Range.second-1);
1469
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001470 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1471 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1472
1473 uint64_t TSize = 0;
1474 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1475 I!=E; ++I)
1476 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001477
1478 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1479 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001480 TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001481 return false;
1482
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001483 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1484 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001485 return false;
1486
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001487 DOUT << "Lowering jump table\n"
1488 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001489 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001490
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001491 // Get the MachineFunction which holds the current MBB. This is used when
1492 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001493 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001494
1495 // Figure out which block is immediately after the current one.
1496 MachineBasicBlock *NextBlock = 0;
1497 MachineFunction::iterator BBI = CR.CaseBB;
1498
1499 if (++BBI != CurMBB->getParent()->end())
1500 NextBlock = BBI;
1501
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001502 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1503
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001504 // Create a new basic block to hold the code for loading the address
1505 // of the jump table, and jumping to it. Update successor information;
1506 // we will either branch to the default case for the switch, or the jump
1507 // table.
1508 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1509 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1510 CR.CaseBB->addSuccessor(Default);
1511 CR.CaseBB->addSuccessor(JumpTableBB);
1512
1513 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001514 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001515 // a case statement, push the case's BB onto the vector, otherwise, push
1516 // the default BB.
1517 std::vector<MachineBasicBlock*> DestBBs;
1518 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001519 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1520 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1521 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1522
1523 if ((Low <= TEI) && (TEI <= High)) {
1524 DestBBs.push_back(I->BB);
1525 if (TEI==High)
1526 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001527 } else {
1528 DestBBs.push_back(Default);
1529 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001530 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001531
1532 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001533 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001534 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1535 E = DestBBs.end(); I != E; ++I) {
1536 if (!SuccsHandled[(*I)->getNumber()]) {
1537 SuccsHandled[(*I)->getNumber()] = true;
1538 JumpTableBB->addSuccessor(*I);
1539 }
1540 }
1541
1542 // Create a jump table index for this jump table, or return an existing
1543 // one.
1544 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1545
1546 // Set the jump table information so that we can codegen it as a second
1547 // MachineBasicBlock
1548 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1549 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1550 (CR.CaseBB == CurMBB));
1551 if (CR.CaseBB == CurMBB)
1552 visitJumpTableHeader(JT, JTH);
1553
1554 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001555
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001556 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001557}
1558
1559/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1560/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001561bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001562 CaseRecVector& WorkList,
1563 Value* SV,
1564 MachineBasicBlock* Default) {
1565 // Get the MachineFunction which holds the current MBB. This is used when
1566 // inserting any additional MBBs necessary to represent the switch.
1567 MachineFunction *CurMF = CurMBB->getParent();
1568
1569 // Figure out which block is immediately after the current one.
1570 MachineBasicBlock *NextBlock = 0;
1571 MachineFunction::iterator BBI = CR.CaseBB;
1572
1573 if (++BBI != CurMBB->getParent()->end())
1574 NextBlock = BBI;
1575
1576 Case& FrontCase = *CR.Range.first;
1577 Case& BackCase = *(CR.Range.second-1);
1578 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1579
1580 // Size is the number of Cases represented by this range.
1581 unsigned Size = CR.Range.second - CR.Range.first;
1582
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001583 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1584 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001585 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001586 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001587
1588 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1589 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001590 uint64_t TSize = 0;
1591 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1592 I!=E; ++I)
1593 TSize += I->size();
1594
1595 uint64_t LSize = FrontCase.size();
1596 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001597 DOUT << "Selecting best pivot: \n"
1598 << "First: " << First << ", Last: " << Last <<"\n"
1599 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001600 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001601 J!=E; ++I, ++J) {
1602 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1603 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001604 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001605 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1606 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001607 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001608 // Should always split in some non-trivial place
1609 DOUT <<"=>Step\n"
1610 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1611 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1612 << "Metric: " << Metric << "\n";
1613 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001614 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001615 FMetric = Metric;
1616 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001617 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001618
1619 LSize += J->size();
1620 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001621 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001622 // If our case is dense we *really* should handle it earlier!
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001623 assert((FMetric > 0) && "Should handle dense range earlier!");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001624
1625 CaseRange LHSR(CR.Range.first, Pivot);
1626 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001627 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001628 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1629
1630 // We know that we branch to the LHS if the Value being switched on is
1631 // less than the Pivot value, C. We use this to optimize our binary
1632 // tree a bit, by recognizing that if SV is greater than or equal to the
1633 // LHS's Case Value, and that Case Value is exactly one less than the
1634 // Pivot's Value, then we can branch directly to the LHS's Target,
1635 // rather than creating a leaf node for it.
1636 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001637 LHSR.first->High == CR.GE &&
1638 cast<ConstantInt>(C)->getSExtValue() ==
1639 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1640 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001641 } else {
1642 TrueBB = new MachineBasicBlock(LLVMBB);
1643 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1644 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1645 }
1646
1647 // Similar to the optimization above, if the Value being switched on is
1648 // known to be less than the Constant CR.LT, and the current Case Value
1649 // is CR.LT - 1, then we can branch directly to the target block for
1650 // the current Case Value, rather than emitting a RHS leaf node for it.
1651 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001652 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1653 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1654 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001655 } else {
1656 FalseBB = new MachineBasicBlock(LLVMBB);
1657 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1658 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1659 }
1660
1661 // Create a CaseBlock record representing a conditional branch to
1662 // the LHS node if the value being switched on SV is less than C.
1663 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001664 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1665 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001666
1667 if (CR.CaseBB == CurMBB)
1668 visitSwitchCase(CB);
1669 else
1670 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001671
1672 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001673}
1674
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001675/// handleBitTestsSwitchCase - if current case range has few destination and
1676/// range span less, than machine word bitwidth, encode case range into series
1677/// of masks and emit bit tests with these masks.
1678bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1679 CaseRecVector& WorkList,
1680 Value* SV,
1681 MachineBasicBlock* Default) {
1682 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1683
1684 Case& FrontCase = *CR.Range.first;
1685 Case& BackCase = *(CR.Range.second-1);
1686
1687 // Get the MachineFunction which holds the current MBB. This is used when
1688 // inserting any additional MBBs necessary to represent the switch.
1689 MachineFunction *CurMF = CurMBB->getParent();
1690
1691 unsigned numCmps = 0;
1692 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1693 I!=E; ++I) {
1694 // Single case counts one, case range - two.
1695 if (I->Low == I->High)
1696 numCmps +=1;
1697 else
1698 numCmps +=2;
1699 }
1700
1701 // Count unique destinations
1702 SmallSet<MachineBasicBlock*, 4> Dests;
1703 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1704 Dests.insert(I->BB);
1705 if (Dests.size() > 3)
1706 // Don't bother the code below, if there are too much unique destinations
1707 return false;
1708 }
1709 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1710 << "Total number of comparisons: " << numCmps << "\n";
1711
1712 // Compute span of values.
1713 Constant* minValue = FrontCase.Low;
1714 Constant* maxValue = BackCase.High;
1715 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1716 cast<ConstantInt>(minValue)->getSExtValue();
1717 DOUT << "Compare range: " << range << "\n"
1718 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1719 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1720
1721 if (range>IntPtrBits ||
1722 (!(Dests.size() == 1 && numCmps >= 3) &&
1723 !(Dests.size() == 2 && numCmps >= 5) &&
1724 !(Dests.size() >= 3 && numCmps >= 6)))
1725 return false;
1726
1727 DOUT << "Emitting bit tests\n";
1728 int64_t lowBound = 0;
1729
1730 // Optimize the case where all the case values fit in a
1731 // word without having to subtract minValue. In this case,
1732 // we can optimize away the subtraction.
1733 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1734 cast<ConstantInt>(maxValue)->getSExtValue() <= IntPtrBits) {
1735 range = cast<ConstantInt>(maxValue)->getSExtValue();
1736 } else {
1737 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1738 }
1739
1740 CaseBitsVector CasesBits;
1741 unsigned i, count = 0;
1742
1743 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1744 MachineBasicBlock* Dest = I->BB;
1745 for (i = 0; i < count; ++i)
1746 if (Dest == CasesBits[i].BB)
1747 break;
1748
1749 if (i == count) {
1750 assert((count < 3) && "Too much destinations to test!");
1751 CasesBits.push_back(CaseBits(0, Dest, 0));
1752 count++;
1753 }
1754
1755 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1756 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1757
1758 for (uint64_t j = lo; j <= hi; j++) {
1759 CasesBits[i].Mask |= 1 << j;
1760 CasesBits[i].Bits++;
1761 }
1762
1763 }
1764 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1765
1766 SelectionDAGISel::BitTestInfo BTC;
1767
1768 // Figure out which block is immediately after the current one.
1769 MachineFunction::iterator BBI = CR.CaseBB;
1770 ++BBI;
1771
1772 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1773
1774 DOUT << "Cases:\n";
1775 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1776 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1777 << ", BB: " << CasesBits[i].BB << "\n";
1778
1779 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1780 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1781 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1782 CaseBB,
1783 CasesBits[i].BB));
1784 }
1785
1786 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001787 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001788 CR.CaseBB, Default, BTC);
1789
1790 if (CR.CaseBB == CurMBB)
1791 visitBitTestHeader(BTB);
1792
1793 BitTestCases.push_back(BTB);
1794
1795 return true;
1796}
1797
1798
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001799// Clusterify - Transform simple list of Cases into list of CaseRange's
1800unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1801 const SwitchInst& SI) {
1802 unsigned numCmps = 0;
1803
1804 // Start with "simple" cases
1805 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1806 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1807 Cases.push_back(Case(SI.getSuccessorValue(i),
1808 SI.getSuccessorValue(i),
1809 SMBB));
1810 }
1811 sort(Cases.begin(), Cases.end(), CaseCmp());
1812
1813 // Merge case into clusters
1814 if (Cases.size()>=2)
1815 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1816 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1817 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1818 MachineBasicBlock* nextBB = J->BB;
1819 MachineBasicBlock* currentBB = I->BB;
1820
1821 // If the two neighboring cases go to the same destination, merge them
1822 // into a single case.
1823 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1824 I->High = J->High;
1825 J = Cases.erase(J);
1826 } else {
1827 I = J++;
1828 }
1829 }
1830
1831 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1832 if (I->Low != I->High)
1833 // A range counts double, since it requires two compares.
1834 ++numCmps;
1835 }
1836
1837 return numCmps;
1838}
1839
1840void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001841 // Figure out which block is immediately after the current one.
1842 MachineBasicBlock *NextBlock = 0;
1843 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001844
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001845 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001846
Nate Begemaned728c12006-03-27 01:32:24 +00001847 // If there is only the default destination, branch to it if it is not the
1848 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001849 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001850 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001851
Nate Begemaned728c12006-03-27 01:32:24 +00001852 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001853 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001854 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001855 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001856
Chris Lattner6d6fc262006-10-22 21:36:53 +00001857 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001858 return;
1859 }
1860
1861 // If there are any non-default case statements, create a vector of Cases
1862 // representing each one, and sort the vector so that we can efficiently
1863 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001864 CaseVector Cases;
1865 unsigned numCmps = Clusterify(Cases, SI);
1866 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1867 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001868
Nate Begemaned728c12006-03-27 01:32:24 +00001869 // Get the Value to be switched on and default basic blocks, which will be
1870 // inserted into CaseBlock records, representing basic blocks in the binary
1871 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001872 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001873
Nate Begemaned728c12006-03-27 01:32:24 +00001874 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001875 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001876 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1877
1878 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001879 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001880 CaseRec CR = WorkList.back();
1881 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001882
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001883 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1884 continue;
1885
Anton Korobeynikov70378262007-03-25 15:07:15 +00001886 // If the range has few cases (two or less) emit a series of specific
1887 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001888 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1889 continue;
1890
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001891 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001892 // target supports indirect branches, then emit a jump table rather than
1893 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001894 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1895 continue;
1896
1897 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1898 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1899 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001900 }
1901}
1902
Anton Korobeynikov70378262007-03-25 15:07:15 +00001903
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001904void SelectionDAGLowering::visitSub(User &I) {
1905 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001906 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001907 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001908 visitVectorBinary(I, ISD::VSUB);
1909 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001910 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1911 if (CFP->isExactlyValue(-0.0)) {
1912 SDOperand Op2 = getValue(I.getOperand(1));
1913 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1914 return;
1915 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001916 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001917 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001918 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001919}
1920
Reid Spencer2eadb532007-01-21 00:29:26 +00001921void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001922 SDOperand Op1 = getValue(I.getOperand(0));
1923 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001924
1925 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001926}
1927
Reid Spencer2eadb532007-01-21 00:29:26 +00001928void
1929SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001930 assert(isa<VectorType>(I.getType()));
1931 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001932 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001933
Reid Spencer2eadb532007-01-21 00:29:26 +00001934 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1935 getValue(I.getOperand(0)),
1936 getValue(I.getOperand(1)),
1937 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1938 Typ));
1939}
1940
1941void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1942 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001943 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001944 visitVectorBinary(I, VectorOp);
1945 else
1946 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001947}
Chris Lattner96c26752005-01-19 22:31:21 +00001948
Nate Begeman127321b2005-11-18 07:42:56 +00001949void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1950 SDOperand Op1 = getValue(I.getOperand(0));
1951 SDOperand Op2 = getValue(I.getOperand(1));
1952
Reid Spencer2341c222007-02-02 02:16:23 +00001953 if (TLI.getShiftAmountTy() < Op2.getValueType())
1954 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1955 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1956 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001957
Chris Lattner7a60d912005-01-07 07:47:53 +00001958 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1959}
1960
Reid Spencerd9436b62006-11-20 01:22:35 +00001961void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001962 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1963 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1964 predicate = IC->getPredicate();
1965 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1966 predicate = ICmpInst::Predicate(IC->getPredicate());
1967 SDOperand Op1 = getValue(I.getOperand(0));
1968 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001969 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001970 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001971 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1972 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1973 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1974 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1975 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1976 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1977 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1978 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1979 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1980 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1981 default:
1982 assert(!"Invalid ICmp predicate value");
1983 Opcode = ISD::SETEQ;
1984 break;
1985 }
1986 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1987}
1988
1989void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001990 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1991 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1992 predicate = FC->getPredicate();
1993 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1994 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001995 SDOperand Op1 = getValue(I.getOperand(0));
1996 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001997 ISD::CondCode Condition, FOC, FPC;
1998 switch (predicate) {
1999 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2000 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2001 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2002 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2003 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2004 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2005 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2006 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2007 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2008 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2009 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2010 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2011 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2012 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2013 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2014 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2015 default:
2016 assert(!"Invalid FCmp predicate value");
2017 FOC = FPC = ISD::SETFALSE;
2018 break;
2019 }
2020 if (FiniteOnlyFPMath())
2021 Condition = FOC;
2022 else
2023 Condition = FPC;
2024 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00002025}
2026
2027void SelectionDAGLowering::visitSelect(User &I) {
2028 SDOperand Cond = getValue(I.getOperand(0));
2029 SDOperand TrueVal = getValue(I.getOperand(1));
2030 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002031 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00002032 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2033 TrueVal, FalseVal));
2034 } else {
2035 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2036 *(TrueVal.Val->op_end()-2),
2037 *(TrueVal.Val->op_end()-1)));
2038 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002039}
2040
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002041
2042void SelectionDAGLowering::visitTrunc(User &I) {
2043 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2044 SDOperand N = getValue(I.getOperand(0));
2045 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2046 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2047}
2048
2049void SelectionDAGLowering::visitZExt(User &I) {
2050 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2051 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2052 SDOperand N = getValue(I.getOperand(0));
2053 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2054 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2055}
2056
2057void SelectionDAGLowering::visitSExt(User &I) {
2058 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2059 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2060 SDOperand N = getValue(I.getOperand(0));
2061 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2062 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2063}
2064
2065void SelectionDAGLowering::visitFPTrunc(User &I) {
2066 // FPTrunc is never a no-op cast, no need to check
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2069 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2070}
2071
2072void SelectionDAGLowering::visitFPExt(User &I){
2073 // FPTrunc is never a no-op cast, no need to check
2074 SDOperand N = getValue(I.getOperand(0));
2075 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2076 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2077}
2078
2079void SelectionDAGLowering::visitFPToUI(User &I) {
2080 // FPToUI is never a no-op cast, no need to check
2081 SDOperand N = getValue(I.getOperand(0));
2082 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2083 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2084}
2085
2086void SelectionDAGLowering::visitFPToSI(User &I) {
2087 // FPToSI is never a no-op cast, no need to check
2088 SDOperand N = getValue(I.getOperand(0));
2089 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2090 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2091}
2092
2093void SelectionDAGLowering::visitUIToFP(User &I) {
2094 // UIToFP is never a no-op cast, no need to check
2095 SDOperand N = getValue(I.getOperand(0));
2096 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2097 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2098}
2099
2100void SelectionDAGLowering::visitSIToFP(User &I){
2101 // UIToFP is never a no-op cast, no need to check
2102 SDOperand N = getValue(I.getOperand(0));
2103 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2104 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2105}
2106
2107void SelectionDAGLowering::visitPtrToInt(User &I) {
2108 // What to do depends on the size of the integer and the size of the pointer.
2109 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002110 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002111 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002112 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002113 SDOperand Result;
2114 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2115 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2116 else
2117 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2118 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2119 setValue(&I, Result);
2120}
Chris Lattner7a60d912005-01-07 07:47:53 +00002121
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002122void SelectionDAGLowering::visitIntToPtr(User &I) {
2123 // What to do depends on the size of the integer and the size of the pointer.
2124 // We can either truncate, zero extend, or no-op, accordingly.
2125 SDOperand N = getValue(I.getOperand(0));
2126 MVT::ValueType SrcVT = N.getValueType();
2127 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2128 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2129 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2130 else
2131 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2132 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2133}
2134
2135void SelectionDAGLowering::visitBitCast(User &I) {
2136 SDOperand N = getValue(I.getOperand(0));
2137 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002138 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002139 // This is a cast to a vector from something else.
2140 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002141 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002142 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2143 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2144 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2145 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002146 return;
2147 }
2148 MVT::ValueType SrcVT = N.getValueType();
2149 if (SrcVT == MVT::Vector) {
2150 // This is a cast from a vctor to something else.
2151 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00002152 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002153 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002154 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002155
2156 // BitCast assures us that source and destination are the same size so this
2157 // is either a BIT_CONVERT or a no-op.
2158 if (DestVT != N.getValueType())
2159 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2160 else
2161 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002162}
2163
Chris Lattner67271862006-03-29 00:11:43 +00002164void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002165 SDOperand InVec = getValue(I.getOperand(0));
2166 SDOperand InVal = getValue(I.getOperand(1));
2167 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2168 getValue(I.getOperand(2)));
2169
Chris Lattner29b23012006-03-19 01:17:20 +00002170 SDOperand Num = *(InVec.Val->op_end()-2);
2171 SDOperand Typ = *(InVec.Val->op_end()-1);
2172 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2173 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00002174}
2175
Chris Lattner67271862006-03-29 00:11:43 +00002176void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002177 SDOperand InVec = getValue(I.getOperand(0));
2178 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2179 getValue(I.getOperand(1)));
2180 SDOperand Typ = *(InVec.Val->op_end()-1);
2181 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2182 TLI.getValueType(I.getType()), InVec, InIdx));
2183}
Chris Lattner32206f52006-03-18 01:44:44 +00002184
Chris Lattner098c01e2006-04-08 04:15:24 +00002185void SelectionDAGLowering::visitShuffleVector(User &I) {
2186 SDOperand V1 = getValue(I.getOperand(0));
2187 SDOperand V2 = getValue(I.getOperand(1));
2188 SDOperand Mask = getValue(I.getOperand(2));
2189
2190 SDOperand Num = *(V1.Val->op_end()-2);
2191 SDOperand Typ = *(V2.Val->op_end()-1);
2192 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2193 V1, V2, Mask, Num, Typ));
2194}
2195
2196
Chris Lattner7a60d912005-01-07 07:47:53 +00002197void SelectionDAGLowering::visitGetElementPtr(User &I) {
2198 SDOperand N = getValue(I.getOperand(0));
2199 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002200
2201 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2202 OI != E; ++OI) {
2203 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002204 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002205 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002206 if (Field) {
2207 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002208 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002209 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002210 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002211 }
2212 Ty = StTy->getElementType(Field);
2213 } else {
2214 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002215
Chris Lattner43535a12005-11-09 04:45:33 +00002216 // If this is a constant subscript, handle it quickly.
2217 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002218 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002219 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002220 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002221 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2222 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002223 }
Chris Lattner43535a12005-11-09 04:45:33 +00002224
2225 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002226 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002227 SDOperand IdxN = getValue(Idx);
2228
2229 // If the index is smaller or larger than intptr_t, truncate or extend
2230 // it.
2231 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002232 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002233 } else if (IdxN.getValueType() > N.getValueType())
2234 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2235
2236 // If this is a multiply by a power of two, turn it into a shl
2237 // immediately. This is a very common case.
2238 if (isPowerOf2_64(ElementSize)) {
2239 unsigned Amt = Log2_64(ElementSize);
2240 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002241 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002242 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2243 continue;
2244 }
2245
2246 SDOperand Scale = getIntPtrConstant(ElementSize);
2247 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2248 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002249 }
2250 }
2251 setValue(&I, N);
2252}
2253
2254void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2255 // If this is a fixed sized alloca in the entry block of the function,
2256 // allocate it statically on the stack.
2257 if (FuncInfo.StaticAllocaMap.count(&I))
2258 return; // getValue will auto-populate this.
2259
2260 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002261 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002262 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002263 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002264 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002265
2266 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002267 MVT::ValueType IntPtr = TLI.getPointerTy();
2268 if (IntPtr < AllocSize.getValueType())
2269 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2270 else if (IntPtr > AllocSize.getValueType())
2271 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002272
Chris Lattnereccb73d2005-01-22 23:04:37 +00002273 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002274 getIntPtrConstant(TySize));
2275
2276 // Handle alignment. If the requested alignment is less than or equal to the
2277 // stack alignment, ignore it and round the size of the allocation up to the
2278 // stack alignment size. If the size is greater than the stack alignment, we
2279 // note this in the DYNAMIC_STACKALLOC node.
2280 unsigned StackAlign =
2281 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2282 if (Align <= StackAlign) {
2283 Align = 0;
2284 // Add SA-1 to the size.
2285 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2286 getIntPtrConstant(StackAlign-1));
2287 // Mask out the low bits for alignment purposes.
2288 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2289 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2290 }
2291
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002292 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002293 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2294 MVT::Other);
2295 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002296 setValue(&I, DSA);
2297 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002298
2299 // Inform the Frame Information that we have just allocated a variable-sized
2300 // object.
2301 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2302}
2303
Chris Lattner7a60d912005-01-07 07:47:53 +00002304void SelectionDAGLowering::visitLoad(LoadInst &I) {
2305 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002306
Chris Lattner4d9651c2005-01-17 22:19:26 +00002307 SDOperand Root;
2308 if (I.isVolatile())
2309 Root = getRoot();
2310 else {
2311 // Do not serialize non-volatile loads against each other.
2312 Root = DAG.getRoot();
2313 }
Chris Lattner4024c002006-03-15 22:19:46 +00002314
Evan Chenge71fe34d2006-10-09 20:57:25 +00002315 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00002316 Root, I.isVolatile()));
2317}
2318
2319SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002320 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00002321 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002322 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002323 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002324 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002325 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2326 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002327 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00002328 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002329 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002330
Chris Lattner4024c002006-03-15 22:19:46 +00002331 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002332 DAG.setRoot(L.getValue(1));
2333 else
2334 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002335
2336 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002337}
2338
2339
2340void SelectionDAGLowering::visitStore(StoreInst &I) {
2341 Value *SrcV = I.getOperand(0);
2342 SDOperand Src = getValue(SrcV);
2343 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002344 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00002345 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002346}
2347
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002348/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2349/// access memory and has no other side effects at all.
2350static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2351#define GET_NO_MEMORY_INTRINSICS
2352#include "llvm/Intrinsics.gen"
2353#undef GET_NO_MEMORY_INTRINSICS
2354 return false;
2355}
2356
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002357// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2358// have any side-effects or if it only reads memory.
2359static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2360#define GET_SIDE_EFFECT_INFO
2361#include "llvm/Intrinsics.gen"
2362#undef GET_SIDE_EFFECT_INFO
2363 return false;
2364}
2365
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002366/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2367/// node.
2368void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2369 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002370 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002371 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002372
2373 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002374 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002375 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2376 if (OnlyLoad) {
2377 // We don't need to serialize loads against other loads.
2378 Ops.push_back(DAG.getRoot());
2379 } else {
2380 Ops.push_back(getRoot());
2381 }
2382 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002383
2384 // Add the intrinsic ID as an integer operand.
2385 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2386
2387 // Add all operands of the call to the operand list.
2388 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2389 SDOperand Op = getValue(I.getOperand(i));
2390
Reid Spencer09575ba2007-02-15 03:39:18 +00002391 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002392 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002393 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002394 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2395
2396 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2397 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2398 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2399 }
2400
2401 assert(TLI.isTypeLegal(Op.getValueType()) &&
2402 "Intrinsic uses a non-legal type?");
2403 Ops.push_back(Op);
2404 }
2405
2406 std::vector<MVT::ValueType> VTs;
2407 if (I.getType() != Type::VoidTy) {
2408 MVT::ValueType VT = TLI.getValueType(I.getType());
2409 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002410 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002411 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2412
2413 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2414 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2415 }
2416
2417 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2418 VTs.push_back(VT);
2419 }
2420 if (HasChain)
2421 VTs.push_back(MVT::Other);
2422
Chris Lattnerbd887772006-08-14 23:53:35 +00002423 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2424
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002425 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002426 SDOperand Result;
2427 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002428 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2429 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002430 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002431 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2432 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002433 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002434 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2435 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002436
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002437 if (HasChain) {
2438 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2439 if (OnlyLoad)
2440 PendingLoads.push_back(Chain);
2441 else
2442 DAG.setRoot(Chain);
2443 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002444 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002445 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002446 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2447 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2448 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2449 DAG.getValueType(EVT));
2450 }
2451 setValue(&I, Result);
2452 }
2453}
2454
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002455/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2456/// we want to emit this as a call to a named external function, return the name
2457/// otherwise lower it and return null.
2458const char *
2459SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2460 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002461 default:
2462 // By default, turn this into a target intrinsic node.
2463 visitTargetIntrinsic(I, Intrinsic);
2464 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002465 case Intrinsic::vastart: visitVAStart(I); return 0;
2466 case Intrinsic::vaend: visitVAEnd(I); return 0;
2467 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002468 case Intrinsic::returnaddress:
2469 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2470 getValue(I.getOperand(1))));
2471 return 0;
2472 case Intrinsic::frameaddress:
2473 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2474 getValue(I.getOperand(1))));
2475 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002476 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002477 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002478 break;
2479 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002480 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002481 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002482 case Intrinsic::memcpy_i32:
2483 case Intrinsic::memcpy_i64:
2484 visitMemIntrinsic(I, ISD::MEMCPY);
2485 return 0;
2486 case Intrinsic::memset_i32:
2487 case Intrinsic::memset_i64:
2488 visitMemIntrinsic(I, ISD::MEMSET);
2489 return 0;
2490 case Intrinsic::memmove_i32:
2491 case Intrinsic::memmove_i64:
2492 visitMemIntrinsic(I, ISD::MEMMOVE);
2493 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002494
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002495 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002496 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002497 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002498 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002499 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002500
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002501 Ops[0] = getRoot();
2502 Ops[1] = getValue(SPI.getLineValue());
2503 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002504
Jim Laskeyc56315c2007-01-26 21:22:28 +00002505 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002506 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002507 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2508
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002509 Ops[3] = DAG.getString(CompileUnit->getFileName());
2510 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002511
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002512 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002513 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002514
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002515 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002516 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002517 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002518 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002519 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002520 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2521 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002522 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002523 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002524 }
2525
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002526 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002527 }
2528 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002529 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002530 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002531 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2532 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002533 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002534 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002535 }
2536
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002537 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002538 }
2539 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002540 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002541 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002542 if (MMI && FSI.getSubprogram() &&
2543 MMI->Verify(FSI.getSubprogram())) {
2544 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002545 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002546 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002547 }
2548
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002549 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002550 }
2551 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002552 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002553 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002554 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002555 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002556 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002557 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002558 }
2559
2560 return 0;
2561 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002562
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002563 case Intrinsic::eh_exception: {
2564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2565
Jim Laskey504e9942007-02-22 15:38:06 +00002566 if (MMI) {
2567 // Add a label to mark the beginning of the landing pad. Deletion of the
2568 // landing pad can thus be detected via the MachineModuleInfo.
2569 unsigned LabelID = MMI->addLandingPad(CurMBB);
2570 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2571 DAG.getConstant(LabelID, MVT::i32)));
2572
2573 // Mark exception register as live in.
2574 unsigned Reg = TLI.getExceptionAddressRegister();
2575 if (Reg) CurMBB->addLiveIn(Reg);
2576
2577 // Insert the EXCEPTIONADDR instruction.
2578 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2579 SDOperand Ops[1];
2580 Ops[0] = DAG.getRoot();
2581 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2582 setValue(&I, Op);
2583 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002584 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002585 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002586 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002587 return 0;
2588 }
2589
Jim Laskeyd5453d72007-03-01 20:24:30 +00002590 case Intrinsic::eh_selector:
2591 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002592 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2593
Jim Laskey504e9942007-02-22 15:38:06 +00002594 if (MMI) {
2595 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002596 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2597 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2598 isa<Function>(CE->getOperand(0)) &&
2599 "Personality should be a function");
2600 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002601 if (Intrinsic == Intrinsic::eh_filter)
2602 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002603
Jim Laskey504e9942007-02-22 15:38:06 +00002604 // Gather all the type infos for this landing pad and pass them along to
2605 // MachineModuleInfo.
2606 std::vector<GlobalVariable *> TyInfo;
2607 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002608 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2609 if (CE && CE->getOpcode() == Instruction::BitCast &&
2610 isa<GlobalVariable>(CE->getOperand(0))) {
2611 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2612 } else {
2613 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2614 assert(CI && CI->getZExtValue() == 0 &&
2615 "TypeInfo must be a global variable typeinfo or NULL");
2616 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002617 }
Jim Laskey504e9942007-02-22 15:38:06 +00002618 }
2619 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2620
2621 // Mark exception selector register as live in.
2622 unsigned Reg = TLI.getExceptionSelectorRegister();
2623 if (Reg) CurMBB->addLiveIn(Reg);
2624
2625 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002626 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002627 SDOperand Ops[2];
2628 Ops[0] = getValue(I.getOperand(1));
2629 Ops[1] = getRoot();
2630 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2631 setValue(&I, Op);
2632 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002633 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002634 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002635 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002636
2637 return 0;
2638 }
2639
2640 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002641 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002642
Jim Laskey504e9942007-02-22 15:38:06 +00002643 if (MMI) {
2644 // Find the type id for the given typeinfo.
2645 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002646 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2647 if (CE && CE->getOpcode() == Instruction::BitCast &&
2648 isa<GlobalVariable>(CE->getOperand(0))) {
2649 GV = cast<GlobalVariable>(CE->getOperand(0));
2650 } else {
2651 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2652 assert(CI && CI->getZExtValue() == 0 &&
2653 "TypeInfo must be a global variable typeinfo or NULL");
2654 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002655 }
2656
2657 unsigned TypeID = MMI->getTypeIDFor(GV);
2658 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002659 } else {
2660 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002661 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002662
2663 return 0;
2664 }
2665
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002666 case Intrinsic::sqrt_f32:
2667 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002668 setValue(&I, DAG.getNode(ISD::FSQRT,
2669 getValue(I.getOperand(1)).getValueType(),
2670 getValue(I.getOperand(1))));
2671 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002672 case Intrinsic::powi_f32:
2673 case Intrinsic::powi_f64:
2674 setValue(&I, DAG.getNode(ISD::FPOWI,
2675 getValue(I.getOperand(1)).getValueType(),
2676 getValue(I.getOperand(1)),
2677 getValue(I.getOperand(2))));
2678 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002679 case Intrinsic::pcmarker: {
2680 SDOperand Tmp = getValue(I.getOperand(1));
2681 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2682 return 0;
2683 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002684 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002685 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002686 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2687 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2688 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002689 setValue(&I, Tmp);
2690 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002691 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002692 }
Reid Spencercce90f52007-04-04 23:48:25 +00002693 case Intrinsic::bit_part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002694 // Currently not implemented: just abort
2695 assert(0 && "bit_part_select intrinsic not implemented");
2696 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002697 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002698 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002699 setValue(&I, DAG.getNode(ISD::BSWAP,
2700 getValue(I.getOperand(1)).getValueType(),
2701 getValue(I.getOperand(1))));
2702 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002703 case Intrinsic::cttz: {
2704 SDOperand Arg = getValue(I.getOperand(1));
2705 MVT::ValueType Ty = Arg.getValueType();
2706 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2707 if (Ty < MVT::i32)
2708 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2709 else if (Ty > MVT::i32)
2710 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2711 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002712 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002713 }
2714 case Intrinsic::ctlz: {
2715 SDOperand Arg = getValue(I.getOperand(1));
2716 MVT::ValueType Ty = Arg.getValueType();
2717 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2718 if (Ty < MVT::i32)
2719 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2720 else if (Ty > MVT::i32)
2721 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2722 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002723 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002724 }
2725 case Intrinsic::ctpop: {
2726 SDOperand Arg = getValue(I.getOperand(1));
2727 MVT::ValueType Ty = Arg.getValueType();
2728 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2729 if (Ty < MVT::i32)
2730 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2731 else if (Ty > MVT::i32)
2732 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2733 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002734 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002735 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002736 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002737 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002738 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2739 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002740 setValue(&I, Tmp);
2741 DAG.setRoot(Tmp.getValue(1));
2742 return 0;
2743 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002744 case Intrinsic::stackrestore: {
2745 SDOperand Tmp = getValue(I.getOperand(1));
2746 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002747 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002748 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002749 case Intrinsic::prefetch:
2750 // FIXME: Currently discarding prefetches.
2751 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002752 }
2753}
2754
2755
Jim Laskey31fef782007-02-23 21:45:01 +00002756void SelectionDAGLowering::LowerCallTo(Instruction &I,
2757 const Type *CalledValueTy,
2758 unsigned CallingConv,
2759 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002760 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002761 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002762 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002763 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey504e9942007-02-22 15:38:06 +00002764
2765 TargetLowering::ArgListTy Args;
2766 TargetLowering::ArgListEntry Entry;
2767 Args.reserve(I.getNumOperands());
2768 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2769 Value *Arg = I.getOperand(i);
2770 SDOperand ArgNode = getValue(Arg);
2771 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencer71b79e32007-04-09 06:17:21 +00002772 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, SExtAttribute);
2773 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ZExtAttribute);
2774 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, InRegAttribute);
2775 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, StructRetAttribute);
Jim Laskey504e9942007-02-22 15:38:06 +00002776 Args.push_back(Entry);
2777 }
2778
2779 std::pair<SDOperand,SDOperand> Result =
2780 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer71b79e32007-04-09 06:17:21 +00002781 Attrs && Attrs->paramHasAttr(0, SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002782 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002783 Callee, Args, DAG);
2784 if (I.getType() != Type::VoidTy)
2785 setValue(&I, Result.first);
2786 DAG.setRoot(Result.second);
2787}
2788
2789
Chris Lattner7a60d912005-01-07 07:47:53 +00002790void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002791 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002792 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002793 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002794 if (unsigned IID = F->getIntrinsicID()) {
2795 RenameFn = visitIntrinsicCall(I, IID);
2796 if (!RenameFn)
2797 return;
2798 } else { // Not an LLVM intrinsic.
2799 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002800 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2801 if (I.getNumOperands() == 3 && // Basic sanity checks.
2802 I.getOperand(1)->getType()->isFloatingPoint() &&
2803 I.getType() == I.getOperand(1)->getType() &&
2804 I.getType() == I.getOperand(2)->getType()) {
2805 SDOperand LHS = getValue(I.getOperand(1));
2806 SDOperand RHS = getValue(I.getOperand(2));
2807 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2808 LHS, RHS));
2809 return;
2810 }
2811 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002812 if (I.getNumOperands() == 2 && // Basic sanity checks.
2813 I.getOperand(1)->getType()->isFloatingPoint() &&
2814 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002815 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002816 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2817 return;
2818 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002819 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002820 if (I.getNumOperands() == 2 && // Basic sanity checks.
2821 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002822 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002823 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002824 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2825 return;
2826 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002827 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002828 if (I.getNumOperands() == 2 && // Basic sanity checks.
2829 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002830 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002831 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002832 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2833 return;
2834 }
2835 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002836 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002837 } else if (isa<InlineAsm>(I.getOperand(0))) {
2838 visitInlineAsm(I);
2839 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002840 }
Misha Brukman835702a2005-04-21 22:36:52 +00002841
Chris Lattner18d2b342005-01-08 22:48:57 +00002842 SDOperand Callee;
2843 if (!RenameFn)
2844 Callee = getValue(I.getOperand(0));
2845 else
2846 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002847
Jim Laskey31fef782007-02-23 21:45:01 +00002848 LowerCallTo(I, I.getCalledValue()->getType(),
2849 I.getCallingConv(),
2850 I.isTailCall(),
2851 Callee,
2852 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002853}
2854
Jim Laskey504e9942007-02-22 15:38:06 +00002855
Chris Lattner6f87d182006-02-22 22:37:12 +00002856SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002857 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002858 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2859 Chain = Val.getValue(1);
2860 Flag = Val.getValue(2);
2861
2862 // If the result was expanded, copy from the top part.
2863 if (Regs.size() > 1) {
2864 assert(Regs.size() == 2 &&
2865 "Cannot expand to more than 2 elts yet!");
2866 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002867 Chain = Hi.getValue(1);
2868 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002869 if (DAG.getTargetLoweringInfo().isLittleEndian())
2870 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2871 else
2872 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002873 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002874
Chris Lattner705948d2006-06-08 18:22:48 +00002875 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002876 // appropriate type.
2877 if (RegVT == ValueVT)
2878 return Val;
2879
Chris Lattner77f04792007-03-25 05:00:54 +00002880 if (MVT::isVector(RegVT)) {
2881 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2882 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2883 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2884 MVT::i32),
2885 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2886 }
2887
Chris Lattner705948d2006-06-08 18:22:48 +00002888 if (MVT::isInteger(RegVT)) {
2889 if (ValueVT < RegVT)
2890 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2891 else
2892 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002893 }
Chris Lattner77f04792007-03-25 05:00:54 +00002894
2895 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2896 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002897}
2898
Chris Lattner571d9642006-02-23 19:21:04 +00002899/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2900/// specified value into the registers specified by this object. This uses
2901/// Chain/Flag as the input and updates them for the output Chain/Flag.
2902void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002903 SDOperand &Chain, SDOperand &Flag,
2904 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002905 if (Regs.size() == 1) {
2906 // If there is a single register and the types differ, this must be
2907 // a promotion.
2908 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002909 if (MVT::isVector(RegVT)) {
2910 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2911 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002912 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002913 if (RegVT < ValueVT)
2914 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2915 else
2916 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002917 } else if (MVT::isFloatingPoint(RegVT) &&
2918 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002919 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002920 } else if (MVT::getSizeInBits(RegVT) ==
2921 MVT::getSizeInBits(Val.getValueType())) {
2922 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2923 } else {
2924 assert(0 && "Unknown mismatch!");
2925 }
Chris Lattner571d9642006-02-23 19:21:04 +00002926 }
2927 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2928 Flag = Chain.getValue(1);
2929 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002930 std::vector<unsigned> R(Regs);
2931 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2932 std::reverse(R.begin(), R.end());
2933
2934 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002935 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002936 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002937 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002938 Flag = Chain.getValue(1);
2939 }
2940 }
2941}
Chris Lattner6f87d182006-02-22 22:37:12 +00002942
Chris Lattner571d9642006-02-23 19:21:04 +00002943/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2944/// operand list. This adds the code marker and includes the number of
2945/// values added into it.
2946void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002947 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002948 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2949 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002950 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2951 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2952}
Chris Lattner6f87d182006-02-22 22:37:12 +00002953
2954/// isAllocatableRegister - If the specified register is safe to allocate,
2955/// i.e. it isn't a stack pointer or some other special register, return the
2956/// register class for the register. Otherwise, return null.
2957static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002958isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2959 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002960 MVT::ValueType FoundVT = MVT::Other;
2961 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002962 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2963 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002964 MVT::ValueType ThisVT = MVT::Other;
2965
Chris Lattnerb1124f32006-02-22 23:09:03 +00002966 const TargetRegisterClass *RC = *RCI;
2967 // If none of the the value types for this register class are valid, we
2968 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002969 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2970 I != E; ++I) {
2971 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002972 // If we have already found this register in a different register class,
2973 // choose the one with the largest VT specified. For example, on
2974 // PowerPC, we favor f64 register classes over f32.
2975 if (FoundVT == MVT::Other ||
2976 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2977 ThisVT = *I;
2978 break;
2979 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002980 }
2981 }
2982
Chris Lattnerbec582f2006-04-02 00:24:45 +00002983 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002984
Chris Lattner6f87d182006-02-22 22:37:12 +00002985 // NOTE: This isn't ideal. In particular, this might allocate the
2986 // frame pointer in functions that need it (due to them not being taken
2987 // out of allocation, because a variable sized allocation hasn't been seen
2988 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002989 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2990 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002991 if (*I == Reg) {
2992 // We found a matching register class. Keep looking at others in case
2993 // we find one with larger registers that this physreg is also in.
2994 FoundRC = RC;
2995 FoundVT = ThisVT;
2996 break;
2997 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002998 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002999 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00003000}
3001
3002RegsForValue SelectionDAGLowering::
3003GetRegistersForValue(const std::string &ConstrCode,
3004 MVT::ValueType VT, bool isOutReg, bool isInReg,
3005 std::set<unsigned> &OutputRegs,
3006 std::set<unsigned> &InputRegs) {
3007 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3008 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
3009 std::vector<unsigned> Regs;
3010
3011 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
3012 MVT::ValueType RegVT;
3013 MVT::ValueType ValueVT = VT;
3014
Chris Lattner55402d42006-11-02 01:41:49 +00003015 // If this is a constraint for a specific physical register, like {r17},
3016 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00003017 if (PhysReg.first) {
3018 if (VT == MVT::Other)
3019 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00003020
3021 // Get the actual register value type. This is important, because the user
3022 // may have asked for (e.g.) the AX register in i32 type. We need to
3023 // remember that AX is actually i16 to get the right extension.
3024 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00003025
3026 // This is a explicit reference to a physical register.
3027 Regs.push_back(PhysReg.first);
3028
3029 // If this is an expanded reference, add the rest of the regs to Regs.
3030 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003031 TargetRegisterClass::iterator I = PhysReg.second->begin();
3032 TargetRegisterClass::iterator E = PhysReg.second->end();
3033 for (; *I != PhysReg.first; ++I)
3034 assert(I != E && "Didn't find reg!");
3035
3036 // Already added the first reg.
3037 --NumRegs; ++I;
3038 for (; NumRegs; --NumRegs, ++I) {
3039 assert(I != E && "Ran out of registers to allocate!");
3040 Regs.push_back(*I);
3041 }
3042 }
3043 return RegsForValue(Regs, RegVT, ValueVT);
3044 }
3045
Chris Lattner55402d42006-11-02 01:41:49 +00003046 // Otherwise, if this was a reference to an LLVM register class, create vregs
3047 // for this reference.
3048 std::vector<unsigned> RegClassRegs;
3049 if (PhysReg.second) {
3050 // If this is an early clobber or tied register, our regalloc doesn't know
3051 // how to maintain the constraint. If it isn't, go ahead and create vreg
3052 // and let the regalloc do the right thing.
3053 if (!isOutReg || !isInReg) {
3054 if (VT == MVT::Other)
3055 ValueVT = *PhysReg.second->vt_begin();
3056 RegVT = *PhysReg.second->vt_begin();
3057
3058 // Create the appropriate number of virtual registers.
3059 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
3060 for (; NumRegs; --NumRegs)
3061 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3062
3063 return RegsForValue(Regs, RegVT, ValueVT);
3064 }
3065
3066 // Otherwise, we can't allocate it. Let the code below figure out how to
3067 // maintain these constraints.
3068 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3069
3070 } else {
3071 // This is a reference to a register class that doesn't directly correspond
3072 // to an LLVM register class. Allocate NumRegs consecutive, available,
3073 // registers from the class.
3074 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
3075 }
Chris Lattner6f87d182006-02-22 22:37:12 +00003076
3077 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3078 MachineFunction &MF = *CurMBB->getParent();
3079 unsigned NumAllocated = 0;
3080 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3081 unsigned Reg = RegClassRegs[i];
3082 // See if this register is available.
3083 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3084 (isInReg && InputRegs.count(Reg))) { // Already used.
3085 // Make sure we find consecutive registers.
3086 NumAllocated = 0;
3087 continue;
3088 }
3089
3090 // Check to see if this register is allocatable (i.e. don't give out the
3091 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00003092 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00003093 if (!RC) {
3094 // Make sure we find consecutive registers.
3095 NumAllocated = 0;
3096 continue;
3097 }
3098
3099 // Okay, this register is good, we can use it.
3100 ++NumAllocated;
3101
Chris Lattner1c741e92007-04-06 17:47:14 +00003102 // If we allocated enough consecutive registers, succeed.
Chris Lattner6f87d182006-02-22 22:37:12 +00003103 if (NumAllocated == NumRegs) {
3104 unsigned RegStart = (i-NumAllocated)+1;
3105 unsigned RegEnd = i+1;
3106 // Mark all of the allocated registers used.
3107 for (unsigned i = RegStart; i != RegEnd; ++i) {
3108 unsigned Reg = RegClassRegs[i];
3109 Regs.push_back(Reg);
3110 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3111 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3112 }
3113
3114 return RegsForValue(Regs, *RC->vt_begin(), VT);
3115 }
3116 }
3117
3118 // Otherwise, we couldn't allocate enough registers for this.
3119 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00003120}
3121
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003122/// getConstraintGenerality - Return an integer indicating how general CT is.
3123static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3124 switch (CT) {
3125 default: assert(0 && "Unknown constraint type!");
3126 case TargetLowering::C_Other:
3127 case TargetLowering::C_Unknown:
3128 return 0;
3129 case TargetLowering::C_Register:
3130 return 1;
3131 case TargetLowering::C_RegisterClass:
3132 return 2;
3133 case TargetLowering::C_Memory:
3134 return 3;
3135 }
3136}
3137
3138static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
3139 const TargetLowering &TLI) {
3140 assert(!C.empty() && "Must have at least one constraint");
3141 if (C.size() == 1) return C[0];
3142
3143 std::string *Current = &C[0];
3144 // If we have multiple constraints, try to pick the most general one ahead
3145 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattnerd6855142007-03-25 02:14:49 +00003146 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003147 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattnerd6855142007-03-25 02:14:49 +00003148 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003149 if (getConstraintGenerality(ThisFlavor) >
3150 getConstraintGenerality(Flavor)) {
3151 // This constraint letter is more general than the previous one,
3152 // use it.
3153 Flavor = ThisFlavor;
3154 Current = &C[j];
3155 }
3156 }
3157 return *Current;
3158}
3159
Chris Lattner6f87d182006-02-22 22:37:12 +00003160
Chris Lattner476e67b2006-01-26 22:24:51 +00003161/// visitInlineAsm - Handle a call to an InlineAsm object.
3162///
3163void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3164 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3165
3166 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
3167 MVT::Other);
3168
Chris Lattner3a5ed552006-02-01 01:28:23 +00003169 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00003170 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00003171
3172 /// AsmNodeOperands - A list of pairs. The first element is a register, the
3173 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
3174 /// if it is a def of that register.
3175 std::vector<SDOperand> AsmNodeOperands;
3176 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3177 AsmNodeOperands.push_back(AsmStr);
3178
3179 SDOperand Chain = getRoot();
3180 SDOperand Flag;
3181
Chris Lattner1558fc62006-02-01 18:59:47 +00003182 // We fully assign registers here at isel time. This is not optimal, but
3183 // should work. For register classes that correspond to LLVM classes, we
3184 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
3185 // over the constraints, collecting fixed registers that we know we can't use.
3186 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003187 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00003188 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003189 std::string ConstraintCode =
3190 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00003191
Chris Lattner7ad77df2006-02-22 00:56:39 +00003192 MVT::ValueType OpVT;
3193
3194 // Compute the value type for each operand and add it to ConstraintVTs.
3195 switch (Constraints[i].Type) {
3196 case InlineAsm::isOutput:
3197 if (!Constraints[i].isIndirectOutput) {
3198 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3199 OpVT = TLI.getValueType(I.getType());
3200 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003201 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00003202 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
3203 OpNum++; // Consumes a call operand.
3204 }
3205 break;
3206 case InlineAsm::isInput:
3207 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
3208 OpNum++; // Consumes a call operand.
3209 break;
3210 case InlineAsm::isClobber:
3211 OpVT = MVT::Other;
3212 break;
3213 }
3214
3215 ConstraintVTs.push_back(OpVT);
3216
Chris Lattner6f87d182006-02-22 22:37:12 +00003217 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
3218 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003219
Chris Lattner6f87d182006-02-22 22:37:12 +00003220 // Build a list of regs that this operand uses. This always has a single
3221 // element for promoted/expanded operands.
3222 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
3223 false, false,
3224 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00003225
3226 switch (Constraints[i].Type) {
3227 case InlineAsm::isOutput:
3228 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00003229 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003230 // If this is an early-clobber output, it cannot be assigned to the same
3231 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00003232 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00003233 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003234 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003235 case InlineAsm::isInput:
3236 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00003237 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00003238 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00003239 case InlineAsm::isClobber:
3240 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003241 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3242 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003243 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00003244 }
3245 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00003246
Chris Lattner5c79f982006-02-21 23:12:12 +00003247 // Loop over all of the inputs, copying the operand values into the
3248 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003249 RegsForValue RetValRegs;
3250 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003251 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00003252
Chris Lattner2e56e892006-01-31 02:03:41 +00003253 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00003254 std::string ConstraintCode =
3255 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003256
Chris Lattner3a5ed552006-02-01 01:28:23 +00003257 switch (Constraints[i].Type) {
3258 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003259 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3260 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00003261 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003262
3263 if (CTy == TargetLowering::C_Memory) {
3264 // Memory output.
3265 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3266
3267 // Check that the operand (the address to store to) isn't a float.
3268 if (!MVT::isInteger(InOperandVal.getValueType()))
3269 assert(0 && "MATCH FAIL!");
3270
3271 if (!Constraints[i].isIndirectOutput)
3272 assert(0 && "MATCH FAIL!");
3273
3274 OpNum++; // Consumes a call operand.
3275
3276 // Extend/truncate to the right pointer type if needed.
3277 MVT::ValueType PtrType = TLI.getPointerTy();
3278 if (InOperandVal.getValueType() < PtrType)
3279 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3280 else if (InOperandVal.getValueType() > PtrType)
3281 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3282
3283 // Add information to the INLINEASM node to know about this output.
3284 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3285 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3286 AsmNodeOperands.push_back(InOperandVal);
3287 break;
3288 }
3289
3290 // Otherwise, this is a register output.
3291 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3292
Chris Lattner6f87d182006-02-22 22:37:12 +00003293 // If this is an early-clobber output, or if there is an input
3294 // constraint that matches this, we need to reserve the input register
3295 // so no other inputs allocate to it.
3296 bool UsesInputRegister = false;
3297 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3298 UsesInputRegister = true;
3299
3300 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003301 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00003302 RegsForValue Regs =
3303 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3304 true, UsesInputRegister,
3305 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00003306 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003307 cerr << "Couldn't allocate output reg for contraint '"
3308 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003309 exit(1);
3310 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003311
Chris Lattner3a5ed552006-02-01 01:28:23 +00003312 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003313 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003314 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003315 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00003316 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003317 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003318 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3319 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003320 OpNum++; // Consumes a call operand.
3321 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003322
3323 // Add information to the INLINEASM node to know that this register is
3324 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00003325 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003326 break;
3327 }
3328 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00003329 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00003330 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00003331
Chris Lattner7f5880b2006-02-02 00:25:23 +00003332 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3333 // If this is required to match an output register we have already set,
3334 // just use its register.
3335 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003336
Chris Lattner571d9642006-02-23 19:21:04 +00003337 // Scan until we find the definition we already emitted of this operand.
3338 // When we find it, create a RegsForValue operand.
3339 unsigned CurOp = 2; // The first operand.
3340 for (; OperandNo; --OperandNo) {
3341 // Advance to the next operand.
3342 unsigned NumOps =
3343 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003344 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3345 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003346 "Skipped past definitions?");
3347 CurOp += (NumOps>>3)+1;
3348 }
3349
3350 unsigned NumOps =
3351 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003352 if ((NumOps & 7) == 2 /*REGDEF*/) {
3353 // Add NumOps>>3 registers to MatchedRegs.
3354 RegsForValue MatchedRegs;
3355 MatchedRegs.ValueVT = InOperandVal.getValueType();
3356 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3357 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3358 unsigned Reg =
3359 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3360 MatchedRegs.Regs.push_back(Reg);
3361 }
Chris Lattner571d9642006-02-23 19:21:04 +00003362
Chris Lattnere3eeb242007-02-01 01:21:12 +00003363 // Use the produced MatchedRegs object to
3364 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3365 TLI.getPointerTy());
3366 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3367 break;
3368 } else {
3369 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3370 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003371 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003372 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003373
3374 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3375 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattnerd6855142007-03-25 02:14:49 +00003376 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner7ef7a642006-02-24 01:11:24 +00003377
3378 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00003379 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3380 ConstraintCode[0], DAG);
3381 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003382 cerr << "Invalid operand for inline asm constraint '"
3383 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003384 exit(1);
3385 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003386
3387 // Add information to the INLINEASM node to know about this input.
3388 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3389 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3390 AsmNodeOperands.push_back(InOperandVal);
3391 break;
3392 } else if (CTy == TargetLowering::C_Memory) {
3393 // Memory input.
3394
Chris Lattnerce8aba02007-03-08 22:29:47 +00003395 // If the operand is a float, spill to a constant pool entry to get its
3396 // address.
3397 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3398 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3399
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003400 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattnerce8aba02007-03-08 22:29:47 +00003401 cerr << "Match failed, cannot handle this yet!\n";
3402 InOperandVal.Val->dump();
Chris Lattnerb7bc3f22007-03-08 07:07:03 +00003403 exit(1);
3404 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003405
3406 // Extend/truncate to the right pointer type if needed.
3407 MVT::ValueType PtrType = TLI.getPointerTy();
3408 if (InOperandVal.getValueType() < PtrType)
3409 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3410 else if (InOperandVal.getValueType() > PtrType)
3411 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3412
3413 // Add information to the INLINEASM node to know about this input.
3414 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3415 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3416 AsmNodeOperands.push_back(InOperandVal);
3417 break;
3418 }
3419
3420 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3421
3422 // Copy the input into the appropriate registers.
3423 RegsForValue InRegs =
3424 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3425 false, true, OutputRegs, InputRegs);
3426 // FIXME: should be match fail.
3427 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3428
Evan Chengef9e07d2006-06-15 08:11:54 +00003429 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003430
3431 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003432 break;
3433 }
Chris Lattner571d9642006-02-23 19:21:04 +00003434 case InlineAsm::isClobber: {
3435 RegsForValue ClobberedRegs =
3436 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3437 OutputRegs, InputRegs);
3438 // Add the clobbered value to the operand list, so that the register
3439 // allocator is aware that the physreg got clobbered.
3440 if (!ClobberedRegs.Regs.empty())
3441 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003442 break;
3443 }
Chris Lattner571d9642006-02-23 19:21:04 +00003444 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003445 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003446
3447 // Finish up input operands.
3448 AsmNodeOperands[0] = Chain;
3449 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3450
Chris Lattnerbd887772006-08-14 23:53:35 +00003451 Chain = DAG.getNode(ISD::INLINEASM,
3452 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003453 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003454 Flag = Chain.getValue(1);
3455
Chris Lattner2e56e892006-01-31 02:03:41 +00003456 // If this asm returns a register value, copy the result from that register
3457 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003458 if (!RetValRegs.Regs.empty())
3459 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00003460
Chris Lattner2e56e892006-01-31 02:03:41 +00003461 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3462
3463 // Process indirect outputs, first output all of the flagged copies out of
3464 // physregs.
3465 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003466 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003467 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003468 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3469 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003470 }
3471
3472 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003473 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003474 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00003475 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003476 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003477 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003478 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003479 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3480 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003481 DAG.setRoot(Chain);
3482}
3483
3484
Chris Lattner7a60d912005-01-07 07:47:53 +00003485void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3486 SDOperand Src = getValue(I.getOperand(0));
3487
3488 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003489
3490 if (IntPtr < Src.getValueType())
3491 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3492 else if (IntPtr > Src.getValueType())
3493 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003494
3495 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003496 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003497 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3498 Src, getIntPtrConstant(ElementSize));
3499
Reid Spencere63b6512006-12-31 05:55:36 +00003500 TargetLowering::ArgListTy Args;
3501 TargetLowering::ArgListEntry Entry;
3502 Entry.Node = Src;
3503 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003504 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003505
3506 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003507 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003508 DAG.getExternalSymbol("malloc", IntPtr),
3509 Args, DAG);
3510 setValue(&I, Result.first); // Pointers always fit in registers
3511 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003512}
3513
3514void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003515 TargetLowering::ArgListTy Args;
3516 TargetLowering::ArgListEntry Entry;
3517 Entry.Node = getValue(I.getOperand(0));
3518 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003519 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003520 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003521 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003522 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003523 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3524 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003525}
3526
Chris Lattner13d7c252005-08-26 20:54:47 +00003527// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3528// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3529// instructions are special in various ways, which require special support to
3530// insert. The specified MachineInstr is created but not inserted into any
3531// basic blocks, and the scheduler passes ownership of it to this method.
3532MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3533 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003534 cerr << "If a target marks an instruction with "
3535 << "'usesCustomDAGSchedInserter', it must implement "
3536 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003537 abort();
3538 return 0;
3539}
3540
Chris Lattner58cfd792005-01-09 00:00:49 +00003541void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003542 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3543 getValue(I.getOperand(1)),
3544 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003545}
3546
3547void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003548 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3549 getValue(I.getOperand(0)),
3550 DAG.getSrcValue(I.getOperand(0)));
3551 setValue(&I, V);
3552 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003553}
3554
3555void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003556 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3557 getValue(I.getOperand(1)),
3558 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003559}
3560
3561void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003562 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3563 getValue(I.getOperand(1)),
3564 getValue(I.getOperand(2)),
3565 DAG.getSrcValue(I.getOperand(1)),
3566 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003567}
3568
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003569/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3570/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3571static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3572 unsigned &i, SelectionDAG &DAG,
3573 TargetLowering &TLI) {
3574 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3575 return SDOperand(Arg, i++);
3576
3577 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3578 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3579 if (NumVals == 1) {
3580 return DAG.getNode(ISD::BIT_CONVERT, VT,
3581 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3582 } else if (NumVals == 2) {
3583 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3584 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3585 if (!TLI.isLittleEndian())
3586 std::swap(Lo, Hi);
3587 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3588 } else {
3589 // Value scalarized into many values. Unimp for now.
3590 assert(0 && "Cannot expand i64 -> i16 yet!");
3591 }
3592 return SDOperand();
3593}
3594
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003595/// TargetLowering::LowerArguments - This is the default LowerArguments
3596/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003597/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3598/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003599std::vector<SDOperand>
3600TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003601 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003602 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003603 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3604 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003605 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003606 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3607 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3608
3609 // Add one result value for each formal argument.
3610 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003611 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003612 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3613 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003614 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003615 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003616 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003617 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003618
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003619 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3620 // that is zero extended!
Reid Spencer71b79e32007-04-09 06:17:21 +00003621 if (Attrs && Attrs->paramHasAttr(j, ZExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003622 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer71b79e32007-04-09 06:17:21 +00003623 if (Attrs && Attrs->paramHasAttr(j, SExtAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003624 Flags |= ISD::ParamFlags::SExt;
Reid Spencer71b79e32007-04-09 06:17:21 +00003625 if (Attrs && Attrs->paramHasAttr(j, InRegAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003626 Flags |= ISD::ParamFlags::InReg;
Reid Spencer71b79e32007-04-09 06:17:21 +00003627 if (Attrs && Attrs->paramHasAttr(j, StructRetAttribute))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003628 Flags |= ISD::ParamFlags::StructReturn;
3629 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003630
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003631 switch (getTypeAction(VT)) {
3632 default: assert(0 && "Unknown type action!");
3633 case Legal:
3634 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003635 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003636 break;
3637 case Promote:
3638 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003639 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003640 break;
3641 case Expand:
3642 if (VT != MVT::Vector) {
3643 // If this is a large integer, it needs to be broken up into small
3644 // integers. Figure out what the destination type is and how many small
3645 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003646 MVT::ValueType NVT = getTypeToExpandTo(VT);
3647 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003648 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003649 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003650 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003651 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003652 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3653 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003654 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3655 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003656 } else {
3657 // Otherwise, this is a vector type. We only support legal vectors
3658 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003659 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3660 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003661
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003662 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003663 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003664 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3665 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3666 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003667 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003668 } else {
3669 assert(0 && "Don't support illegal by-val vector arguments yet!");
3670 }
3671 }
3672 break;
3673 }
3674 }
Evan Cheng9618df12006-04-25 23:03:35 +00003675
Chris Lattner3d826992006-05-16 06:45:34 +00003676 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003677
3678 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003679 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3680 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003681 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003682
3683 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003684
3685 // Set up the return result vector.
3686 Ops.clear();
3687 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003688 unsigned Idx = 1;
3689 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3690 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003691 MVT::ValueType VT = getValueType(I->getType());
3692
3693 switch (getTypeAction(VT)) {
3694 default: assert(0 && "Unknown type action!");
3695 case Legal:
3696 Ops.push_back(SDOperand(Result, i++));
3697 break;
3698 case Promote: {
3699 SDOperand Op(Result, i++);
3700 if (MVT::isInteger(VT)) {
Reid Spencer71b79e32007-04-09 06:17:21 +00003701 if (Attrs && Attrs->paramHasAttr(Idx, SExtAttribute))
Chris Lattner96035be2007-01-04 22:22:37 +00003702 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3703 DAG.getValueType(VT));
Reid Spencer71b79e32007-04-09 06:17:21 +00003704 else if (Attrs && Attrs->paramHasAttr(Idx, ZExtAttribute))
Chris Lattner96035be2007-01-04 22:22:37 +00003705 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3706 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003707 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3708 } else {
3709 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3710 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3711 }
3712 Ops.push_back(Op);
3713 break;
3714 }
3715 case Expand:
3716 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003717 // If this is a large integer or a floating point node that needs to be
3718 // expanded, it needs to be reassembled from small integers. Figure out
3719 // what the source elt type is and how many small integers it is.
3720 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003721 } else {
3722 // Otherwise, this is a vector type. We only support legal vectors
3723 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003724 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003725 unsigned NumElems = PTy->getNumElements();
3726 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003727
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003728 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003729 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003730 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003731 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003732 SDOperand N = SDOperand(Result, i++);
3733 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003734 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3735 DAG.getConstant(NumElems, MVT::i32),
3736 DAG.getValueType(getValueType(EltTy)));
3737 Ops.push_back(N);
3738 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003739 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003740 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003741 }
3742 }
3743 break;
3744 }
3745 }
3746 return Ops;
3747}
3748
Chris Lattneraaa23d92006-05-16 22:53:20 +00003749
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003750/// ExpandScalarCallArgs - Recursively expand call argument node by
3751/// bit_converting it or extract a pair of elements from the larger node.
3752static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003753 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003754 SmallVector<SDOperand, 32> &Ops,
3755 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003756 TargetLowering &TLI,
3757 bool isFirst = true) {
3758
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003759 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003760 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003761 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003762 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3763 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003764 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003765 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003766 return;
3767 }
3768
3769 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3770 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3771 if (NumVals == 1) {
3772 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003773 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003774 } else if (NumVals == 2) {
3775 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3776 DAG.getConstant(0, TLI.getPointerTy()));
3777 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3778 DAG.getConstant(1, TLI.getPointerTy()));
3779 if (!TLI.isLittleEndian())
3780 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003781 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3782 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003783 } else {
3784 // Value scalarized into many values. Unimp for now.
3785 assert(0 && "Cannot expand i64 -> i16 yet!");
3786 }
3787}
3788
Chris Lattneraaa23d92006-05-16 22:53:20 +00003789/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3790/// implementation, which just inserts an ISD::CALL node, which is later custom
3791/// lowered by the target to something concrete. FIXME: When all targets are
3792/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3793std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003794TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3795 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003796 unsigned CallingConv, bool isTailCall,
3797 SDOperand Callee,
3798 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003799 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003800 Ops.push_back(Chain); // Op#0 - Chain
3801 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3802 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3803 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3804 Ops.push_back(Callee);
3805
3806 // Handle all of the outgoing arguments.
3807 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003808 MVT::ValueType VT = getValueType(Args[i].Ty);
3809 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003810 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003811 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003812 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003813
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003814 if (Args[i].isSExt)
3815 Flags |= ISD::ParamFlags::SExt;
3816 if (Args[i].isZExt)
3817 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003818 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003819 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003820 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003821 Flags |= ISD::ParamFlags::StructReturn;
3822 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003823
Chris Lattneraaa23d92006-05-16 22:53:20 +00003824 switch (getTypeAction(VT)) {
3825 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003826 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003827 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003828 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003829 break;
3830 case Promote:
3831 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003832 unsigned ExtOp;
3833 if (Args[i].isSExt)
3834 ExtOp = ISD::SIGN_EXTEND;
3835 else if (Args[i].isZExt)
3836 ExtOp = ISD::ZERO_EXTEND;
3837 else
3838 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003839 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3840 } else {
3841 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3842 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3843 }
3844 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003845 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003846 break;
3847 case Expand:
3848 if (VT != MVT::Vector) {
3849 // If this is a large integer, it needs to be broken down into small
3850 // integers. Figure out what the source elt type is and how many small
3851 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003852 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003853 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003854 // Otherwise, this is a vector type. We only support legal vectors
3855 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003856 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003857 unsigned NumElems = PTy->getNumElements();
3858 const Type *EltTy = PTy->getElementType();
3859
3860 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003861 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003862 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003863 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003864 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003865 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3866 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003867 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003868 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003869 assert(0 && "Don't support illegal by-val vector call args yet!");
3870 abort();
3871 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003872 }
3873 break;
3874 }
3875 }
3876
3877 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003878 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003879
3880 if (RetTy != Type::VoidTy) {
3881 MVT::ValueType VT = getValueType(RetTy);
3882 switch (getTypeAction(VT)) {
3883 default: assert(0 && "Unknown type action!");
3884 case Legal:
3885 RetTys.push_back(VT);
3886 break;
3887 case Promote:
3888 RetTys.push_back(getTypeToTransformTo(VT));
3889 break;
3890 case Expand:
3891 if (VT != MVT::Vector) {
3892 // If this is a large integer, it needs to be reassembled from small
3893 // integers. Figure out what the source elt type is and how many small
3894 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003895 MVT::ValueType NVT = getTypeToExpandTo(VT);
3896 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003897 for (unsigned i = 0; i != NumVals; ++i)
3898 RetTys.push_back(NVT);
3899 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003900 // Otherwise, this is a vector type. We only support legal vectors
3901 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003902 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003903 unsigned NumElems = PTy->getNumElements();
3904 const Type *EltTy = PTy->getElementType();
3905
3906 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003907 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003908 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3909 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3910 RetTys.push_back(TVT);
3911 } else {
3912 assert(0 && "Don't support illegal by-val vector call results yet!");
3913 abort();
3914 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003915 }
3916 }
3917 }
3918
3919 RetTys.push_back(MVT::Other); // Always has a chain.
3920
3921 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003922 SDOperand Res = DAG.getNode(ISD::CALL,
3923 DAG.getVTList(&RetTys[0], RetTys.size()),
3924 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003925
3926 // This returns a pair of operands. The first element is the
3927 // return value for the function (if RetTy is not VoidTy). The second
3928 // element is the outgoing token chain.
3929 SDOperand ResVal;
3930 if (RetTys.size() != 1) {
3931 MVT::ValueType VT = getValueType(RetTy);
3932 if (RetTys.size() == 2) {
3933 ResVal = Res;
3934
3935 // If this value was promoted, truncate it down.
3936 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003937 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00003938 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00003939 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003940 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3941 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003942
3943 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003944 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003945 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003946 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003947 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3948 // "N x PTyElementVT" MVT::Vector type.
3949 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003950 DAG.getConstant(NumElems, MVT::i32),
3951 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003952 } else {
3953 abort();
3954 }
3955 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003956 unsigned AssertOp = ISD::AssertSext;
3957 if (!RetTyIsSigned)
3958 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003959 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3960 DAG.getValueType(VT));
3961 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3962 } else {
3963 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003964 if (getTypeAction(VT) == Expand)
3965 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3966 else
3967 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003968 }
3969 }
3970 } else if (RetTys.size() == 3) {
3971 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3972 Res.getValue(0), Res.getValue(1));
3973
3974 } else {
3975 assert(0 && "Case not handled yet!");
3976 }
3977 }
3978
3979 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3980}
3981
Chris Lattner29dcc712005-05-14 05:50:48 +00003982SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003983 assert(0 && "LowerOperation not implemented for this target!");
3984 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003985 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003986}
3987
Nate Begeman595ec732006-01-28 03:14:31 +00003988SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3989 SelectionDAG &DAG) {
3990 assert(0 && "CustomPromoteOperation not implemented for this target!");
3991 abort();
3992 return SDOperand();
3993}
3994
Evan Cheng6781b6e2006-02-15 21:59:04 +00003995/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003996/// operand.
3997static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003998 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003999 MVT::ValueType CurVT = VT;
4000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4001 uint64_t Val = C->getValue() & 255;
4002 unsigned Shift = 8;
4003 while (CurVT != MVT::i8) {
4004 Val = (Val << Shift) | Val;
4005 Shift <<= 1;
4006 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004007 }
4008 return DAG.getConstant(Val, VT);
4009 } else {
4010 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4011 unsigned Shift = 8;
4012 while (CurVT != MVT::i8) {
4013 Value =
4014 DAG.getNode(ISD::OR, VT,
4015 DAG.getNode(ISD::SHL, VT, Value,
4016 DAG.getConstant(Shift, MVT::i8)), Value);
4017 Shift <<= 1;
4018 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004019 }
4020
4021 return Value;
4022 }
4023}
4024
Evan Cheng6781b6e2006-02-15 21:59:04 +00004025/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4026/// used when a memcpy is turned into a memset when the source is a constant
4027/// string ptr.
4028static SDOperand getMemsetStringVal(MVT::ValueType VT,
4029 SelectionDAG &DAG, TargetLowering &TLI,
4030 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004031 uint64_t Val = 0;
4032 unsigned MSB = getSizeInBits(VT) / 8;
4033 if (TLI.isLittleEndian())
4034 Offset = Offset + MSB - 1;
4035 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004036 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004037 Offset += TLI.isLittleEndian() ? -1 : 1;
4038 }
4039 return DAG.getConstant(Val, VT);
4040}
4041
Evan Cheng81fcea82006-02-14 08:22:34 +00004042/// getMemBasePlusOffset - Returns base and offset node for the
4043static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4044 SelectionDAG &DAG, TargetLowering &TLI) {
4045 MVT::ValueType VT = Base.getValueType();
4046 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4047}
4048
Evan Chengdb2a7a72006-02-14 20:12:38 +00004049/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004050/// to replace the memset / memcpy is below the threshold. It also returns the
4051/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004052static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4053 unsigned Limit, uint64_t Size,
4054 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004055 MVT::ValueType VT;
4056
4057 if (TLI.allowsUnalignedMemoryAccesses()) {
4058 VT = MVT::i64;
4059 } else {
4060 switch (Align & 7) {
4061 case 0:
4062 VT = MVT::i64;
4063 break;
4064 case 4:
4065 VT = MVT::i32;
4066 break;
4067 case 2:
4068 VT = MVT::i16;
4069 break;
4070 default:
4071 VT = MVT::i8;
4072 break;
4073 }
4074 }
4075
Evan Chengd5026102006-02-14 09:11:59 +00004076 MVT::ValueType LVT = MVT::i64;
4077 while (!TLI.isTypeLegal(LVT))
4078 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4079 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004080
Evan Chengd5026102006-02-14 09:11:59 +00004081 if (VT > LVT)
4082 VT = LVT;
4083
Evan Cheng04514992006-02-14 23:05:54 +00004084 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004085 while (Size != 0) {
4086 unsigned VTSize = getSizeInBits(VT) / 8;
4087 while (VTSize > Size) {
4088 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004089 VTSize >>= 1;
4090 }
Evan Chengd5026102006-02-14 09:11:59 +00004091 assert(MVT::isInteger(VT));
4092
4093 if (++NumMemOps > Limit)
4094 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004095 MemOps.push_back(VT);
4096 Size -= VTSize;
4097 }
Evan Chengd5026102006-02-14 09:11:59 +00004098
4099 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004100}
4101
Chris Lattner875def92005-01-11 05:56:49 +00004102void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004103 SDOperand Op1 = getValue(I.getOperand(1));
4104 SDOperand Op2 = getValue(I.getOperand(2));
4105 SDOperand Op3 = getValue(I.getOperand(3));
4106 SDOperand Op4 = getValue(I.getOperand(4));
4107 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4108 if (Align == 0) Align = 1;
4109
4110 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4111 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004112
4113 // Expand memset / memcpy to a series of load / store ops
4114 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004115 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004116 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004117 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004118 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004119 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4120 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004121 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004122 unsigned Offset = 0;
4123 for (unsigned i = 0; i < NumMemOps; i++) {
4124 MVT::ValueType VT = MemOps[i];
4125 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004126 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004127 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004128 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004129 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004130 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004131 Offset += VTSize;
4132 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004133 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004134 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004135 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004136 case ISD::MEMCPY: {
4137 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4138 Size->getValue(), Align, TLI)) {
4139 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004140 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004141 GlobalAddressSDNode *G = NULL;
4142 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004143 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004144
4145 if (Op2.getOpcode() == ISD::GlobalAddress)
4146 G = cast<GlobalAddressSDNode>(Op2);
4147 else if (Op2.getOpcode() == ISD::ADD &&
4148 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4149 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4150 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004151 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004152 }
4153 if (G) {
4154 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004155 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004156 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004157 if (!Str.empty()) {
4158 CopyFromStr = true;
4159 SrcOff += SrcDelta;
4160 }
4161 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004162 }
4163
Evan Chenge2038bd2006-02-15 01:54:51 +00004164 for (unsigned i = 0; i < NumMemOps; i++) {
4165 MVT::ValueType VT = MemOps[i];
4166 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004167 SDOperand Value, Chain, Store;
4168
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004169 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004170 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4171 Chain = getRoot();
4172 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004173 DAG.getStore(Chain, Value,
4174 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004175 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004176 } else {
4177 Value = DAG.getLoad(VT, getRoot(),
4178 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004179 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004180 Chain = Value.getValue(1);
4181 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004182 DAG.getStore(Chain, Value,
4183 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004184 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004185 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004186 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004187 SrcOff += VTSize;
4188 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004189 }
4190 }
4191 break;
4192 }
4193 }
4194
4195 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004196 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4197 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004198 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004199 }
4200 }
4201
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004202 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004203}
4204
Chris Lattner875def92005-01-11 05:56:49 +00004205//===----------------------------------------------------------------------===//
4206// SelectionDAGISel code
4207//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004208
4209unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4210 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4211}
4212
Chris Lattnerc9950c12005-08-17 06:37:43 +00004213void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004214 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004215 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004216}
Chris Lattner7a60d912005-01-07 07:47:53 +00004217
Chris Lattner35397782005-12-05 07:10:48 +00004218
Chris Lattnerbba52192006-10-28 19:22:10 +00004219
Chris Lattner7a60d912005-01-07 07:47:53 +00004220bool SelectionDAGISel::runOnFunction(Function &Fn) {
4221 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4222 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004223 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004224
4225 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4226
4227 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4228 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004229
Evan Cheng276b44b2007-02-10 02:43:39 +00004230 // Add function live-ins to entry block live-in set.
4231 BasicBlock *EntryBB = &Fn.getEntryBlock();
4232 BB = FuncInfo.MBBMap[EntryBB];
4233 if (!MF.livein_empty())
4234 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4235 E = MF.livein_end(); I != E; ++I)
4236 BB->addLiveIn(I->first);
4237
Chris Lattner7a60d912005-01-07 07:47:53 +00004238 return true;
4239}
4240
Chris Lattnered0110b2006-10-27 21:36:01 +00004241SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4242 unsigned Reg) {
4243 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004244 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004245 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004246 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004247
4248 // If this type is not legal, we must make sure to not create an invalid
4249 // register use.
4250 MVT::ValueType SrcVT = Op.getValueType();
4251 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004252 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004253 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004254 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004255 // Handle copies from generic vectors to registers.
4256 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004257 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004258 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004259
Chris Lattner5fe1f542006-03-31 02:06:56 +00004260 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4261 // MVT::Vector type.
4262 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4263 DAG.getConstant(NE, MVT::i32),
4264 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004265
Chris Lattner5fe1f542006-03-31 02:06:56 +00004266 // Loop over all of the elements of the resultant vector,
4267 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4268 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004269 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004270 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004271 for (unsigned i = 0; i != NE; ++i) {
4272 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004273 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004274 if (PTyElementVT == PTyLegalElementVT) {
4275 // Elements are legal.
4276 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4277 } else if (PTyLegalElementVT > PTyElementVT) {
4278 // Elements are promoted.
4279 if (MVT::isFloatingPoint(PTyLegalElementVT))
4280 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4281 else
4282 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4283 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4284 } else {
4285 // Elements are expanded.
4286 // The src value is expanded into multiple registers.
4287 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004288 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004289 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004290 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004291 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4292 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4293 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004294 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004295 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4296 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004297 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004298 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004299 if (MVT::isFloatingPoint(SrcVT))
4300 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4301 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004302 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004303 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004304 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004305 DestVT = TLI.getTypeToExpandTo(SrcVT);
4306 unsigned NumVals = TLI.getNumElements(SrcVT);
4307 if (NumVals == 1)
4308 return DAG.getCopyToReg(getRoot(), Reg,
4309 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4310 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004311 // The src value is expanded into multiple registers.
4312 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004313 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004314 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004315 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004316 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004317 return DAG.getCopyToReg(Op, Reg+1, Hi);
4318 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004319}
4320
Chris Lattner16f64df2005-01-17 17:15:02 +00004321void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004322LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004323 std::vector<SDOperand> &UnorderedChains) {
4324 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004325 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004326 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004327 SDOperand OldRoot = SDL.DAG.getRoot();
4328 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004329
Chris Lattner6871b232005-10-30 19:42:35 +00004330 unsigned a = 0;
4331 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4332 AI != E; ++AI, ++a)
4333 if (!AI->use_empty()) {
4334 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004335
Chris Lattner6871b232005-10-30 19:42:35 +00004336 // If this argument is live outside of the entry block, insert a copy from
4337 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004338 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4339 if (VMI != FuncInfo.ValueMap.end()) {
4340 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004341 UnorderedChains.push_back(Copy);
4342 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004343 }
Chris Lattner6871b232005-10-30 19:42:35 +00004344
Chris Lattner6871b232005-10-30 19:42:35 +00004345 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004346 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004347 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004348}
4349
Chris Lattner7a60d912005-01-07 07:47:53 +00004350void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4351 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004352 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004353 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004354
4355 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004356
Chris Lattner6871b232005-10-30 19:42:35 +00004357 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004358 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004359 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004360
4361 BB = FuncInfo.MBBMap[LLVMBB];
4362 SDL.setCurrentBasicBlock(BB);
4363
4364 // Lower all of the non-terminator instructions.
4365 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4366 I != E; ++I)
4367 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004368
4369 // Lower call part of invoke.
4370 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4371 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004372
Chris Lattner7a60d912005-01-07 07:47:53 +00004373 // Ensure that all instructions which are used outside of their defining
4374 // blocks are available as virtual registers.
4375 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004376 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004377 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004378 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004379 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004380 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004381 }
4382
4383 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4384 // ensure constants are generated when needed. Remember the virtual registers
4385 // that need to be added to the Machine PHI nodes as input. We cannot just
4386 // directly add them, because expansion might result in multiple MBB's for one
4387 // BB. As such, the start of the BB might correspond to a different MBB than
4388 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004389 //
Chris Lattner84a03502006-10-27 23:50:33 +00004390 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004391
4392 // Emit constants only once even if used by multiple PHI nodes.
4393 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004394
Chris Lattner84a03502006-10-27 23:50:33 +00004395 // Vector bool would be better, but vector<bool> is really slow.
4396 std::vector<unsigned char> SuccsHandled;
4397 if (TI->getNumSuccessors())
4398 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4399
Chris Lattner7a60d912005-01-07 07:47:53 +00004400 // Check successor nodes PHI nodes that expect a constant to be available from
4401 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004402 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4403 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004404 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004405 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004406
Chris Lattner84a03502006-10-27 23:50:33 +00004407 // If this terminator has multiple identical successors (common for
4408 // switches), only handle each succ once.
4409 unsigned SuccMBBNo = SuccMBB->getNumber();
4410 if (SuccsHandled[SuccMBBNo]) continue;
4411 SuccsHandled[SuccMBBNo] = true;
4412
4413 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004414 PHINode *PN;
4415
4416 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4417 // nodes and Machine PHI nodes, but the incoming operands have not been
4418 // emitted yet.
4419 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004420 (PN = dyn_cast<PHINode>(I)); ++I) {
4421 // Ignore dead phi's.
4422 if (PN->use_empty()) continue;
4423
4424 unsigned Reg;
4425 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004426
Chris Lattner84a03502006-10-27 23:50:33 +00004427 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4428 unsigned &RegOut = ConstantsOut[C];
4429 if (RegOut == 0) {
4430 RegOut = FuncInfo.CreateRegForValue(C);
4431 UnorderedChains.push_back(
4432 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004433 }
Chris Lattner84a03502006-10-27 23:50:33 +00004434 Reg = RegOut;
4435 } else {
4436 Reg = FuncInfo.ValueMap[PHIOp];
4437 if (Reg == 0) {
4438 assert(isa<AllocaInst>(PHIOp) &&
4439 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4440 "Didn't codegen value into a register!??");
4441 Reg = FuncInfo.CreateRegForValue(PHIOp);
4442 UnorderedChains.push_back(
4443 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004444 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004445 }
Chris Lattner84a03502006-10-27 23:50:33 +00004446
4447 // Remember that this register needs to added to the machine PHI node as
4448 // the input for this MBB.
4449 MVT::ValueType VT = TLI.getValueType(PN->getType());
4450 unsigned NumElements;
4451 if (VT != MVT::Vector)
4452 NumElements = TLI.getNumElements(VT);
4453 else {
4454 MVT::ValueType VT1,VT2;
4455 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004456 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004457 VT1, VT2);
4458 }
4459 for (unsigned i = 0, e = NumElements; i != e; ++i)
4460 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4461 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004462 }
4463 ConstantsOut.clear();
4464
Chris Lattner718b5c22005-01-13 17:59:43 +00004465 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004466 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004467 SDOperand Root = SDL.getRoot();
4468 if (Root.getOpcode() != ISD::EntryToken) {
4469 unsigned i = 0, e = UnorderedChains.size();
4470 for (; i != e; ++i) {
4471 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4472 if (UnorderedChains[i].Val->getOperand(0) == Root)
4473 break; // Don't add the root if we already indirectly depend on it.
4474 }
4475
4476 if (i == e)
4477 UnorderedChains.push_back(Root);
4478 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004479 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4480 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004481 }
4482
Chris Lattner7a60d912005-01-07 07:47:53 +00004483 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004484 if (Invoke) {
4485 // Just the branch part of invoke.
4486 SDL.visitInvoke(*Invoke, true);
4487 } else {
4488 SDL.visit(*LLVMBB->getTerminator());
4489 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004490
Nate Begemaned728c12006-03-27 01:32:24 +00004491 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004492 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004493 SwitchCases.clear();
4494 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004495 JTCases.clear();
4496 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004497 BitTestCases.clear();
4498 BitTestCases = SDL.BitTestCases;
4499
Chris Lattner4108bb02005-01-17 19:43:36 +00004500 // Make sure the root of the DAG is up-to-date.
4501 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004502}
4503
Nate Begemaned728c12006-03-27 01:32:24 +00004504void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004505 // Get alias analysis for load/store combining.
4506 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4507
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004508 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004509 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004510
Bill Wendling22e978a2006-12-07 20:04:42 +00004511 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004512 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004513
Chris Lattner7a60d912005-01-07 07:47:53 +00004514 // Second step, hack on the DAG until it only uses operations and types that
4515 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004516 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004517
Bill Wendling22e978a2006-12-07 20:04:42 +00004518 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004519 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004520
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004521 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004522 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004523
Evan Cheng739a6a42006-01-21 02:32:06 +00004524 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004525
Chris Lattner5ca31d92005-03-30 01:10:47 +00004526 // Third, instruction select all of the operations to machine code, adding the
4527 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004528 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004529
Bill Wendling22e978a2006-12-07 20:04:42 +00004530 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004531 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004532}
Chris Lattner7a60d912005-01-07 07:47:53 +00004533
Nate Begemaned728c12006-03-27 01:32:24 +00004534void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4535 FunctionLoweringInfo &FuncInfo) {
4536 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4537 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004538 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004539 CurDAG = &DAG;
4540
4541 // First step, lower LLVM code to some DAG. This DAG may use operations and
4542 // types that are not supported by the target.
4543 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4544
4545 // Second step, emit the lowered DAG as machine code.
4546 CodeGenAndEmitDAG(DAG);
4547 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004548
4549 DOUT << "Total amount of phi nodes to update: "
4550 << PHINodesToUpdate.size() << "\n";
4551 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4552 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4553 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004554
Chris Lattner5ca31d92005-03-30 01:10:47 +00004555 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004556 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004557 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004558 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4559 MachineInstr *PHI = PHINodesToUpdate[i].first;
4560 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4561 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004562 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004563 PHI->addMachineBasicBlockOperand(BB);
4564 }
4565 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004566 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004567
4568 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4569 // Lower header first, if it wasn't already lowered
4570 if (!BitTestCases[i].Emitted) {
4571 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4572 CurDAG = &HSDAG;
4573 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4574 // Set the current basic block to the mbb we wish to insert the code into
4575 BB = BitTestCases[i].Parent;
4576 HSDL.setCurrentBasicBlock(BB);
4577 // Emit the code
4578 HSDL.visitBitTestHeader(BitTestCases[i]);
4579 HSDAG.setRoot(HSDL.getRoot());
4580 CodeGenAndEmitDAG(HSDAG);
4581 }
4582
4583 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4584 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4585 CurDAG = &BSDAG;
4586 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4587 // Set the current basic block to the mbb we wish to insert the code into
4588 BB = BitTestCases[i].Cases[j].ThisBB;
4589 BSDL.setCurrentBasicBlock(BB);
4590 // Emit the code
4591 if (j+1 != ej)
4592 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4593 BitTestCases[i].Reg,
4594 BitTestCases[i].Cases[j]);
4595 else
4596 BSDL.visitBitTestCase(BitTestCases[i].Default,
4597 BitTestCases[i].Reg,
4598 BitTestCases[i].Cases[j]);
4599
4600
4601 BSDAG.setRoot(BSDL.getRoot());
4602 CodeGenAndEmitDAG(BSDAG);
4603 }
4604
4605 // Update PHI Nodes
4606 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4607 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4608 MachineBasicBlock *PHIBB = PHI->getParent();
4609 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4610 "This is not a machine PHI node that we are updating!");
4611 // This is "default" BB. We have two jumps to it. From "header" BB and
4612 // from last "case" BB.
4613 if (PHIBB == BitTestCases[i].Default) {
4614 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4615 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4616 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4617 }
4618 // One of "cases" BB.
4619 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4620 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4621 if (cBB->succ_end() !=
4622 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4623 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4624 PHI->addMachineBasicBlockOperand(cBB);
4625 }
4626 }
4627 }
4628 }
4629
Nate Begeman866b4b42006-04-23 06:26:20 +00004630 // If the JumpTable record is filled in, then we need to emit a jump table.
4631 // Updating the PHI nodes is tricky in this case, since we need to determine
4632 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004633 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4634 // Lower header first, if it wasn't already lowered
4635 if (!JTCases[i].first.Emitted) {
4636 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4637 CurDAG = &HSDAG;
4638 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4639 // Set the current basic block to the mbb we wish to insert the code into
4640 BB = JTCases[i].first.HeaderBB;
4641 HSDL.setCurrentBasicBlock(BB);
4642 // Emit the code
4643 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4644 HSDAG.setRoot(HSDL.getRoot());
4645 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004646 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004647
4648 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4649 CurDAG = &JSDAG;
4650 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004651 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004652 BB = JTCases[i].second.MBB;
4653 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004654 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004655 JSDL.visitJumpTable(JTCases[i].second);
4656 JSDAG.setRoot(JSDL.getRoot());
4657 CodeGenAndEmitDAG(JSDAG);
4658
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004659 // Update PHI Nodes
4660 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4661 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4662 MachineBasicBlock *PHIBB = PHI->getParent();
4663 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4664 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004665 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004666 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004667 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004668 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004669 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004670 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004671 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004672 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004673 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004674 }
4675 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004676 }
4677
Chris Lattner76a7bc82006-10-22 23:00:53 +00004678 // If the switch block involved a branch to one of the actual successors, we
4679 // need to update PHI nodes in that block.
4680 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4681 MachineInstr *PHI = PHINodesToUpdate[i].first;
4682 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4683 "This is not a machine PHI node that we are updating!");
4684 if (BB->isSuccessor(PHI->getParent())) {
4685 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4686 PHI->addMachineBasicBlockOperand(BB);
4687 }
4688 }
4689
Nate Begemaned728c12006-03-27 01:32:24 +00004690 // If we generated any switch lowering information, build and codegen any
4691 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004692 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004693 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004694 CurDAG = &SDAG;
4695 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004696
Nate Begemaned728c12006-03-27 01:32:24 +00004697 // Set the current basic block to the mbb we wish to insert the code into
4698 BB = SwitchCases[i].ThisBB;
4699 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004700
Nate Begemaned728c12006-03-27 01:32:24 +00004701 // Emit the code
4702 SDL.visitSwitchCase(SwitchCases[i]);
4703 SDAG.setRoot(SDL.getRoot());
4704 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004705
4706 // Handle any PHI nodes in successors of this chunk, as if we were coming
4707 // from the original BB before switch expansion. Note that PHI nodes can
4708 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4709 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004710 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004711 for (MachineBasicBlock::iterator Phi = BB->begin();
4712 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4713 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4714 for (unsigned pn = 0; ; ++pn) {
4715 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4716 if (PHINodesToUpdate[pn].first == Phi) {
4717 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4718 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4719 break;
4720 }
4721 }
Nate Begemaned728c12006-03-27 01:32:24 +00004722 }
Chris Lattner707339a52006-09-07 01:59:34 +00004723
4724 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004725 if (BB == SwitchCases[i].FalseBB)
4726 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004727
4728 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004729 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004730 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004731 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004732 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004733 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004734}
Evan Cheng739a6a42006-01-21 02:32:06 +00004735
Jim Laskey95eda5b2006-08-01 14:21:23 +00004736
Evan Cheng739a6a42006-01-21 02:32:06 +00004737//===----------------------------------------------------------------------===//
4738/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4739/// target node in the graph.
4740void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4741 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004742
Jim Laskey29e635d2006-08-02 12:30:23 +00004743 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004744
4745 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004746 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004747 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004748 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004749
Jim Laskey03593f72006-08-01 18:29:48 +00004750 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004751 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004752 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004753}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004754
Chris Lattner47639db2006-03-06 00:22:00 +00004755
Jim Laskey03593f72006-08-01 18:29:48 +00004756HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4757 return new HazardRecognizer();
4758}
4759
Chris Lattner6df34962006-10-11 03:58:02 +00004760//===----------------------------------------------------------------------===//
4761// Helper functions used by the generated instruction selector.
4762//===----------------------------------------------------------------------===//
4763// Calls to these methods are generated by tblgen.
4764
4765/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4766/// the dag combiner simplified the 255, we still want to match. RHS is the
4767/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4768/// specified in the .td file (e.g. 255).
4769bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4770 int64_t DesiredMaskS) {
4771 uint64_t ActualMask = RHS->getValue();
4772 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4773
4774 // If the actual mask exactly matches, success!
4775 if (ActualMask == DesiredMask)
4776 return true;
4777
4778 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4779 if (ActualMask & ~DesiredMask)
4780 return false;
4781
4782 // Otherwise, the DAG Combiner may have proven that the value coming in is
4783 // either already zero or is not demanded. Check for known zero input bits.
4784 uint64_t NeededMask = DesiredMask & ~ActualMask;
4785 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4786 return true;
4787
4788 // TODO: check to see if missing bits are just not demanded.
4789
4790 // Otherwise, this pattern doesn't match.
4791 return false;
4792}
4793
4794/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4795/// the dag combiner simplified the 255, we still want to match. RHS is the
4796/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4797/// specified in the .td file (e.g. 255).
4798bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4799 int64_t DesiredMaskS) {
4800 uint64_t ActualMask = RHS->getValue();
4801 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4802
4803 // If the actual mask exactly matches, success!
4804 if (ActualMask == DesiredMask)
4805 return true;
4806
4807 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4808 if (ActualMask & ~DesiredMask)
4809 return false;
4810
4811 // Otherwise, the DAG Combiner may have proven that the value coming in is
4812 // either already zero or is not demanded. Check for known zero input bits.
4813 uint64_t NeededMask = DesiredMask & ~ActualMask;
4814
4815 uint64_t KnownZero, KnownOne;
4816 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4817
4818 // If all the missing bits in the or are already known to be set, match!
4819 if ((NeededMask & KnownOne) == NeededMask)
4820 return true;
4821
4822 // TODO: check to see if missing bits are just not demanded.
4823
4824 // Otherwise, this pattern doesn't match.
4825 return false;
4826}
4827
Jim Laskey03593f72006-08-01 18:29:48 +00004828
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004829/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4830/// by tblgen. Others should not call it.
4831void SelectionDAGISel::
4832SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4833 std::vector<SDOperand> InOps;
4834 std::swap(InOps, Ops);
4835
4836 Ops.push_back(InOps[0]); // input chain.
4837 Ops.push_back(InOps[1]); // input asm string.
4838
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004839 unsigned i = 2, e = InOps.size();
4840 if (InOps[e-1].getValueType() == MVT::Flag)
4841 --e; // Don't process a flag operand if it is here.
4842
4843 while (i != e) {
4844 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4845 if ((Flags & 7) != 4 /*MEM*/) {
4846 // Just skip over this operand, copying the operands verbatim.
4847 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4848 i += (Flags >> 3) + 1;
4849 } else {
4850 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4851 // Otherwise, this is a memory operand. Ask the target to select it.
4852 std::vector<SDOperand> SelOps;
4853 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004854 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004855 exit(1);
4856 }
4857
4858 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00004859 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004860 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00004861 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004862 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4863 i += 2;
4864 }
4865 }
4866
4867 // Add the flag input back if present.
4868 if (e != InOps.size())
4869 Ops.push_back(InOps.back());
4870}