blob: e009488fd61486884cced6a5c6141248469bc2e9 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-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 Prus12472912006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000057#else
Chris Lattner5e46a192006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000059#endif
60
Jim Laskeyeb577ba2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000073namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey9ff542f2006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner864635a2006-02-22 22:37:12 +000085namespace {
86 /// RegsForValue - This struct represents the physical registers that a
87 /// particular value is assigned and the type information about the value.
88 /// This is needed because values can be promoted into larger registers and
89 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000090 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000091 /// Regs - This list hold the register (for legal and promoted values)
92 /// or register set (for expanded values) that the value should be assigned
93 /// to.
94 std::vector<unsigned> Regs;
95
96 /// RegVT - The value type of each register.
97 ///
98 MVT::ValueType RegVT;
99
100 /// ValueVT - The value type of the LLVM value, which may be promoted from
101 /// RegVT or made from merging the two expanded parts.
102 MVT::ValueType ValueVT;
103
104 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
105
106 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
107 : RegVT(regvt), ValueVT(valuevt) {
108 Regs.push_back(Reg);
109 }
110 RegsForValue(const std::vector<unsigned> &regs,
111 MVT::ValueType regvt, MVT::ValueType valuevt)
112 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
113 }
114
115 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
116 /// this value and returns the result as a ValueVT value. This uses
117 /// Chain/Flag as the input and updates them for the output Chain/Flag.
118 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000119 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000120
121 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
122 /// specified value into the registers specified by this object. This uses
123 /// Chain/Flag as the input and updates them for the output Chain/Flag.
124 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000125 SDOperand &Chain, SDOperand &Flag,
126 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000127
128 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
129 /// operand list. This adds the code marker and includes the number of
130 /// values added into it.
131 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000132 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000133 };
134}
Evan Cheng4ef10862006-01-23 07:01:07 +0000135
Chris Lattner1c08c712005-01-07 07:47:53 +0000136namespace llvm {
137 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
139 /// for the target.
140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
141 SelectionDAG *DAG,
142 MachineBasicBlock *BB) {
143 TargetLowering &TLI = IS->getTargetLowering();
144
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
146 return createTDListDAGScheduler(IS, DAG, BB);
147 } else {
148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
150 return createBURRListDAGScheduler(IS, DAG, BB);
151 }
152 }
153
154
155 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000156 /// FunctionLoweringInfo - This contains information that is global to a
157 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000158 class FunctionLoweringInfo {
159 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000160 TargetLowering &TLI;
161 Function &Fn;
162 MachineFunction &MF;
163 SSARegMap *RegMap;
164
165 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
166
167 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
168 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
169
170 /// ValueMap - Since we emit code for the function a basic block at a time,
171 /// we must remember which virtual registers hold the values for
172 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000173 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000174
175 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
176 /// the entry block. This allows the allocas to be efficiently referenced
177 /// anywhere in the function.
178 std::map<const AllocaInst*, int> StaticAllocaMap;
179
180 unsigned MakeReg(MVT::ValueType VT) {
181 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
182 }
Chris Lattner571e4342006-10-27 21:36:01 +0000183
184 /// isExportedInst - Return true if the specified value is an instruction
185 /// exported from its block.
186 bool isExportedInst(const Value *V) {
187 return ValueMap.count(V);
188 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000189
Chris Lattner3c384492006-03-16 19:51:18 +0000190 unsigned CreateRegForValue(const Value *V);
191
Chris Lattner1c08c712005-01-07 07:47:53 +0000192 unsigned InitializeRegForValue(const Value *V) {
193 unsigned &R = ValueMap[V];
194 assert(R == 0 && "Already initialized this value register!");
195 return R = CreateRegForValue(V);
196 }
197 };
198}
199
200/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000201/// PHI nodes or outside of the basic block that defines it, or used by a
202/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000203static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
204 if (isa<PHINode>(I)) return true;
205 BasicBlock *BB = I->getParent();
206 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000207 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000208 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000209 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000210 return true;
211 return false;
212}
213
Chris Lattnerbf209482005-10-30 19:42:35 +0000214/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000215/// entry block, return true. This includes arguments used by switches, since
216/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000220 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner1c08c712005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattnerbf209482005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner1c08c712005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000242 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000243 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000244 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000245 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000246 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000247 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000248
Reid Spencerb83eb642006-10-20 07:07:24 +0000249 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000250 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000251 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000252 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 }
254
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000255 for (; BB != EB; ++BB)
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
258 if (!isa<AllocaInst>(I) ||
259 !StaticAllocaMap.count(cast<AllocaInst>(I)))
260 InitializeRegForValue(I);
261
262 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
263 // also creates the initial PHI MachineInstrs, though none of the input
264 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000265 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000266 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
267 MBBMap[BB] = MBB;
268 MF.getBasicBlockList().push_back(MBB);
269
270 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
271 // appropriate.
272 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000273 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
274 if (PN->use_empty()) continue;
275
276 MVT::ValueType VT = TLI.getValueType(PN->getType());
277 unsigned NumElements;
278 if (VT != MVT::Vector)
279 NumElements = TLI.getNumElements(VT);
280 else {
281 MVT::ValueType VT1,VT2;
282 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000283 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000284 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000285 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000286 unsigned PHIReg = ValueMap[PN];
287 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000288 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000289 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000290 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000291 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000292 }
293}
294
Chris Lattner3c384492006-03-16 19:51:18 +0000295/// CreateRegForValue - Allocate the appropriate number of virtual registers of
296/// the correctly promoted or expanded types. Assign these registers
297/// consecutive vreg numbers and return the first assigned number.
298unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
299 MVT::ValueType VT = TLI.getValueType(V->getType());
300
301 // The number of multiples of registers that we need, to, e.g., split up
302 // a <2 x int64> -> 4 x i32 registers.
303 unsigned NumVectorRegs = 1;
304
Reid Spencerac9dcb92007-02-15 03:39:18 +0000305 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000306 // and how many of the elements it will use.
307 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000308 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000309 unsigned NumElts = PTy->getNumElements();
310 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
311
312 // Divide the input until we get to a supported size. This will always
313 // end with a scalar if the target doesn't support vectors.
314 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
315 NumElts >>= 1;
316 NumVectorRegs <<= 1;
317 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000318 if (NumElts == 1)
319 VT = EltTy;
320 else
321 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000322 }
323
324 // The common case is that we will only create one register for this
325 // value. If we have that case, create and return the virtual register.
326 unsigned NV = TLI.getNumElements(VT);
327 if (NV == 1) {
328 // If we are promoting this value, pick the next largest supported type.
329 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
330 unsigned Reg = MakeReg(PromotedType);
331 // If this is a vector of supported or promoted types (e.g. 4 x i16),
332 // create all of the registers.
333 for (unsigned i = 1; i != NumVectorRegs; ++i)
334 MakeReg(PromotedType);
335 return Reg;
336 }
337
338 // If this value is represented with multiple target registers, make sure
339 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000340 VT = TLI.getTypeToExpandTo(VT);
341 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000342 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000343 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000344 return R;
345}
Chris Lattner1c08c712005-01-07 07:47:53 +0000346
347//===----------------------------------------------------------------------===//
348/// SelectionDAGLowering - This is the common target-independent lowering
349/// implementation that is parameterized by a TargetLowering object.
350/// Also, targets can overload any lowering method.
351///
352namespace llvm {
353class SelectionDAGLowering {
354 MachineBasicBlock *CurMBB;
355
Chris Lattner0da331f2007-02-04 01:31:47 +0000356 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000357
Chris Lattnerd3948112005-01-17 22:19:26 +0000358 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
359 /// them up and then emit token factor nodes when possible. This allows us to
360 /// get simple disambiguation between loads without worrying about alias
361 /// analysis.
362 std::vector<SDOperand> PendingLoads;
363
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000364 /// Case - A struct to record the Value for a switch case, and the
365 /// case's target basic block.
366 struct Case {
367 Constant* Low;
368 Constant* High;
369 MachineBasicBlock* BB;
370
371 Case() : Low(0), High(0), BB(0) { }
372 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
373 Low(low), High(high), BB(bb) { }
374 uint64_t size() const {
375 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
376 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
377 return (rHigh - rLow + 1ULL);
378 }
379 };
380
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000381 struct CaseBits {
382 uint64_t Mask;
383 MachineBasicBlock* BB;
384 unsigned Bits;
385
386 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
387 Mask(mask), BB(bb), Bits(bits) { }
388 };
389
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000390 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000391 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000392 typedef CaseVector::iterator CaseItr;
393 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000394
395 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
396 /// of conditional branches.
397 struct CaseRec {
398 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
399 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
400
401 /// CaseBB - The MBB in which to emit the compare and branch
402 MachineBasicBlock *CaseBB;
403 /// LT, GE - If nonzero, we know the current case value must be less-than or
404 /// greater-than-or-equal-to these Constants.
405 Constant *LT;
406 Constant *GE;
407 /// Range - A pair of iterators representing the range of case values to be
408 /// processed at this point in the binary search tree.
409 CaseRange Range;
410 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000411
412 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000413
414 /// The comparison function for sorting the switch case values in the vector.
415 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000416 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000417 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000418 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
419 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
420 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
421 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000422 }
423 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000424
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000425 struct CaseBitsCmp {
426 bool operator () (const CaseBits& C1, const CaseBits& C2) {
427 return C1.Bits > C2.Bits;
428 }
429 };
430
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000431 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000432
Chris Lattner1c08c712005-01-07 07:47:53 +0000433public:
434 // TLI - This is information that describes the available target features we
435 // need for lowering. This indicates when operations are unavailable,
436 // implemented with a libcall, etc.
437 TargetLowering &TLI;
438 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000439 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000440
Nate Begemanf15485a2006-03-27 01:32:24 +0000441 /// SwitchCases - Vector of CaseBlock structures used to communicate
442 /// SwitchInst code generation information.
443 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000444 /// JTCases - Vector of JumpTable structures used to communicate
445 /// SwitchInst code generation information.
446 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000447 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000448
Chris Lattner1c08c712005-01-07 07:47:53 +0000449 /// FuncInfo - Information about the function as a whole.
450 ///
451 FunctionLoweringInfo &FuncInfo;
452
453 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000454 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000455 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000456 FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000457 }
458
Chris Lattnera651cf62005-01-17 19:43:36 +0000459 /// getRoot - Return the current virtual root of the Selection DAG.
460 ///
461 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000462 if (PendingLoads.empty())
463 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000464
Chris Lattnerd3948112005-01-17 22:19:26 +0000465 if (PendingLoads.size() == 1) {
466 SDOperand Root = PendingLoads[0];
467 DAG.setRoot(Root);
468 PendingLoads.clear();
469 return Root;
470 }
471
472 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000473 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
474 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000475 PendingLoads.clear();
476 DAG.setRoot(Root);
477 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000478 }
479
Chris Lattner571e4342006-10-27 21:36:01 +0000480 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
481
Chris Lattner1c08c712005-01-07 07:47:53 +0000482 void visit(Instruction &I) { visit(I.getOpcode(), I); }
483
484 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000485 // Note: this doesn't use InstVisitor, because it has to work with
486 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000487 switch (Opcode) {
488 default: assert(0 && "Unknown instruction type encountered!");
489 abort();
490 // Build the switch statement using the Instruction.def file.
491#define HANDLE_INST(NUM, OPCODE, CLASS) \
492 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
493#include "llvm/Instruction.def"
494 }
495 }
496
497 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
498
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000499 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000500 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000501 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000502
503 SDOperand getIntPtrConstant(uint64_t Val) {
504 return DAG.getConstant(Val, TLI.getPointerTy());
505 }
506
Chris Lattner199862b2006-03-16 19:57:50 +0000507 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000508
Chris Lattner0da331f2007-02-04 01:31:47 +0000509 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000510 SDOperand &N = NodeMap[V];
511 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000512 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000514
Chris Lattner864635a2006-02-22 22:37:12 +0000515 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
516 MVT::ValueType VT,
517 bool OutReg, bool InReg,
518 std::set<unsigned> &OutputRegs,
519 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000520
Chris Lattner571e4342006-10-27 21:36:01 +0000521 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
522 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
523 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000524 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000525 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000526 void LowerCallTo(Instruction &I,
527 const Type *CalledValueTy, unsigned CallingConv,
528 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey735b6f82007-02-22 15:38:06 +0000529
Chris Lattner1c08c712005-01-07 07:47:53 +0000530 // Terminator instructions.
531 void visitRet(ReturnInst &I);
532 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000533 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000534 void visitUnreachable(UnreachableInst &I) { /* noop */ }
535
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000536 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000537 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000538 CaseRecVector& WorkList,
539 Value* SV,
540 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000541 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000542 CaseRecVector& WorkList,
543 Value* SV,
544 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000545 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000546 CaseRecVector& WorkList,
547 Value* SV,
548 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000549 bool handleBitTestsSwitchCase(CaseRec& CR,
550 CaseRecVector& WorkList,
551 Value* SV,
552 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000553 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000554 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
555 void visitBitTestCase(MachineBasicBlock* NextMBB,
556 unsigned Reg,
557 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000558 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000559 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
560 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000561
Chris Lattner1c08c712005-01-07 07:47:53 +0000562 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000563 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000564 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000565 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000566
Reid Spencer24d6da52007-01-21 00:29:26 +0000567 void visitScalarBinary(User &I, unsigned OpCode);
568 void visitVectorBinary(User &I, unsigned OpCode);
569 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000570 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000571 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000572 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000573 visitVectorBinary(I, ISD::VADD);
574 else if (I.getType()->isFloatingPoint())
575 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000576 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000577 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000578 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000579 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000580 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000581 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000582 visitVectorBinary(I, ISD::VMUL);
583 else if (I.getType()->isFloatingPoint())
584 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000586 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000587 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000588 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
589 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
590 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
591 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
592 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
593 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
594 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
595 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
596 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
597 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000598 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
599 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000600 void visitICmp(User &I);
601 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000602 // Visit the conversion instructions
603 void visitTrunc(User &I);
604 void visitZExt(User &I);
605 void visitSExt(User &I);
606 void visitFPTrunc(User &I);
607 void visitFPExt(User &I);
608 void visitFPToUI(User &I);
609 void visitFPToSI(User &I);
610 void visitUIToFP(User &I);
611 void visitSIToFP(User &I);
612 void visitPtrToInt(User &I);
613 void visitIntToPtr(User &I);
614 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000615
Chris Lattner2bbd8102006-03-29 00:11:43 +0000616 void visitExtractElement(User &I);
617 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000618 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000619
Chris Lattner1c08c712005-01-07 07:47:53 +0000620 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000622
623 void visitMalloc(MallocInst &I);
624 void visitFree(FreeInst &I);
625 void visitAlloca(AllocaInst &I);
626 void visitLoad(LoadInst &I);
627 void visitStore(StoreInst &I);
628 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
629 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000630 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000631 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000632 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000633
Chris Lattner1c08c712005-01-07 07:47:53 +0000634 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000635 void visitVAArg(VAArgInst &I);
636 void visitVAEnd(CallInst &I);
637 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000638
Chris Lattner7041ee32005-01-11 05:56:49 +0000639 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000640
641 void visitUserOp1(Instruction &I) {
642 assert(0 && "UserOp1 should not exist at instruction selection time!");
643 abort();
644 }
645 void visitUserOp2(Instruction &I) {
646 assert(0 && "UserOp2 should not exist at instruction selection time!");
647 abort();
648 }
649};
650} // end namespace llvm
651
Chris Lattner199862b2006-03-16 19:57:50 +0000652SDOperand SelectionDAGLowering::getValue(const Value *V) {
653 SDOperand &N = NodeMap[V];
654 if (N.Val) return N;
655
656 const Type *VTy = V->getType();
657 MVT::ValueType VT = TLI.getValueType(VTy);
658 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
660 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000661 SDOperand N1 = NodeMap[V];
662 assert(N1.Val && "visit didn't populate the ValueMap!");
663 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000664 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
665 return N = DAG.getGlobalAddress(GV, VT);
666 } else if (isa<ConstantPointerNull>(C)) {
667 return N = DAG.getConstant(0, TLI.getPointerTy());
668 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000669 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000670 return N = DAG.getNode(ISD::UNDEF, VT);
671
Chris Lattnerb2827b02006-03-19 00:52:58 +0000672 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000673 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000674 unsigned NumElements = PTy->getNumElements();
675 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
676
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000677 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000678 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
679
680 // Create a VConstant node with generic Vector type.
681 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
682 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000683 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
684 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000685 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
686 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000687 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000688 unsigned NumElements = PTy->getNumElements();
689 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000690
691 // Now that we know the number and type of the elements, push a
692 // Constant or ConstantFP node onto the ops list for each element of
693 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000694 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000695 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000696 for (unsigned i = 0; i != NumElements; ++i)
697 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000698 } else {
699 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
700 SDOperand Op;
701 if (MVT::isFloatingPoint(PVT))
702 Op = DAG.getConstantFP(0, PVT);
703 else
704 Op = DAG.getConstant(0, PVT);
705 Ops.assign(NumElements, Op);
706 }
707
Chris Lattnerb2827b02006-03-19 00:52:58 +0000708 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000709 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
710 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000711 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
712 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000713 } else {
714 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000715 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000716 }
717 }
718
719 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
720 std::map<const AllocaInst*, int>::iterator SI =
721 FuncInfo.StaticAllocaMap.find(AI);
722 if (SI != FuncInfo.StaticAllocaMap.end())
723 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
724 }
725
Chris Lattner251db182007-02-25 18:40:32 +0000726 unsigned InReg = FuncInfo.ValueMap[V];
727 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000728
729 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000730 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000731 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000732 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000733 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000734 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
735 unsigned NumVals = TLI.getNumElements(VT);
736 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
737 if (NumVals == 1)
738 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
739 else {
740 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
741 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
742 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
743 }
744 } else {
745 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
746 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
747 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
748 N = MVT::isFloatingPoint(VT)
749 ? DAG.getNode(ISD::FP_ROUND, VT, N)
750 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000751 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000752 } else {
753 // Otherwise, if this is a vector, make it available as a generic vector
754 // here.
755 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000756 const VectorType *PTy = cast<VectorType>(VTy);
757 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000758 PTyLegalElementVT);
759
760 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000761 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000762 if (PTyElementVT == PTyLegalElementVT) {
763 // If the value types are legal, just VBUILD the CopyFromReg nodes.
764 for (unsigned i = 0; i != NE; ++i)
765 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
766 PTyElementVT));
767 } else if (PTyElementVT < PTyLegalElementVT) {
768 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
769 for (unsigned i = 0; i != NE; ++i) {
770 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
771 PTyElementVT);
772 if (MVT::isFloatingPoint(PTyElementVT))
773 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
774 else
775 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
776 Ops.push_back(Op);
777 }
778 } else {
779 // If the register was expanded, use BUILD_PAIR.
780 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
781 for (unsigned i = 0; i != NE/2; ++i) {
782 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
783 PTyElementVT);
784 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
785 PTyElementVT);
786 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
787 }
788 }
789
790 Ops.push_back(DAG.getConstant(NE, MVT::i32));
791 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000792 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000793
794 // Finally, use a VBIT_CONVERT to make this available as the appropriate
795 // vector type.
796 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
797 DAG.getConstant(PTy->getNumElements(),
798 MVT::i32),
799 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000800 }
801
802 return N;
803}
804
805
Chris Lattner1c08c712005-01-07 07:47:53 +0000806void SelectionDAGLowering::visitRet(ReturnInst &I) {
807 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000808 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000809 return;
810 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000811 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000812 NewValues.push_back(getRoot());
813 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
814 SDOperand RetOp = getValue(I.getOperand(i));
815
816 // If this is an integer return value, we need to promote it ourselves to
817 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
818 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000819 // FIXME: C calling convention requires the return type to be promoted to
820 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000821 if (MVT::isInteger(RetOp.getValueType()) &&
822 RetOp.getValueType() < MVT::i64) {
823 MVT::ValueType TmpVT;
824 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
825 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
826 else
827 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000828 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +0000829 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerbcca3402007-01-03 16:49:33 +0000830 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000831 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000832 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000833 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencer47857812006-12-31 05:55:36 +0000834 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000835 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000836 }
837 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000838 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000839 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000840 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
841 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000842}
843
Chris Lattner571e4342006-10-27 21:36:01 +0000844/// ExportFromCurrentBlock - If this condition isn't known to be exported from
845/// the current basic block, add it to ValueMap now so that we'll get a
846/// CopyTo/FromReg.
847void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
848 // No need to export constants.
849 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
850
851 // Already exported?
852 if (FuncInfo.isExportedInst(V)) return;
853
854 unsigned Reg = FuncInfo.InitializeRegForValue(V);
855 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
856}
857
Chris Lattner8c494ab2006-10-27 23:50:33 +0000858bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
859 const BasicBlock *FromBB) {
860 // The operands of the setcc have to be in this block. We don't know
861 // how to export them from some other block.
862 if (Instruction *VI = dyn_cast<Instruction>(V)) {
863 // Can export from current BB.
864 if (VI->getParent() == FromBB)
865 return true;
866
867 // Is already exported, noop.
868 return FuncInfo.isExportedInst(V);
869 }
870
871 // If this is an argument, we can export it if the BB is the entry block or
872 // if it is already exported.
873 if (isa<Argument>(V)) {
874 if (FromBB == &FromBB->getParent()->getEntryBlock())
875 return true;
876
877 // Otherwise, can only export this if it is already exported.
878 return FuncInfo.isExportedInst(V);
879 }
880
881 // Otherwise, constants can always be exported.
882 return true;
883}
884
Chris Lattner6a586c82006-10-29 21:01:20 +0000885static bool InBlock(const Value *V, const BasicBlock *BB) {
886 if (const Instruction *I = dyn_cast<Instruction>(V))
887 return I->getParent() == BB;
888 return true;
889}
890
Chris Lattner571e4342006-10-27 21:36:01 +0000891/// FindMergedConditions - If Cond is an expression like
892void SelectionDAGLowering::FindMergedConditions(Value *Cond,
893 MachineBasicBlock *TBB,
894 MachineBasicBlock *FBB,
895 MachineBasicBlock *CurBB,
896 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000897 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000898 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000899
Reid Spencere4d87aa2006-12-23 06:05:41 +0000900 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
901 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000902 BOp->getParent() != CurBB->getBasicBlock() ||
903 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
904 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000905 const BasicBlock *BB = CurBB->getBasicBlock();
906
Reid Spencere4d87aa2006-12-23 06:05:41 +0000907 // If the leaf of the tree is a comparison, merge the condition into
908 // the caseblock.
909 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
910 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000911 // how to export them from some other block. If this is the first block
912 // of the sequence, no exporting is needed.
913 (CurBB == CurMBB ||
914 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
915 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000916 BOp = cast<Instruction>(Cond);
917 ISD::CondCode Condition;
918 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
919 switch (IC->getPredicate()) {
920 default: assert(0 && "Unknown icmp predicate opcode!");
921 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
922 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
923 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
924 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
925 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
926 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
927 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
928 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
929 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
930 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
931 }
932 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
933 ISD::CondCode FPC, FOC;
934 switch (FC->getPredicate()) {
935 default: assert(0 && "Unknown fcmp predicate opcode!");
936 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
937 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
938 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
939 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
940 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
941 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
942 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
943 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
944 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
945 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
946 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
947 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
948 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
949 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
950 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
951 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
952 }
953 if (FiniteOnlyFPMath())
954 Condition = FOC;
955 else
956 Condition = FPC;
957 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000958 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000959 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000960 }
961
Chris Lattner571e4342006-10-27 21:36:01 +0000962 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000963 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000964 SwitchCases.push_back(CB);
965 return;
966 }
967
968 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000969 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000970 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000971 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000972 return;
973 }
974
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000975
976 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000977 MachineFunction::iterator BBI = CurBB;
978 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
979 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
980
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000981 if (Opc == Instruction::Or) {
982 // Codegen X | Y as:
983 // jmp_if_X TBB
984 // jmp TmpBB
985 // TmpBB:
986 // jmp_if_Y TBB
987 // jmp FBB
988 //
Chris Lattner571e4342006-10-27 21:36:01 +0000989
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000990 // Emit the LHS condition.
991 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
992
993 // Emit the RHS condition into TmpBB.
994 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
995 } else {
996 assert(Opc == Instruction::And && "Unknown merge op!");
997 // Codegen X & Y as:
998 // jmp_if_X TmpBB
999 // jmp FBB
1000 // TmpBB:
1001 // jmp_if_Y TBB
1002 // jmp FBB
1003 //
1004 // This requires creation of TmpBB after CurBB.
1005
1006 // Emit the LHS condition.
1007 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1008
1009 // Emit the RHS condition into TmpBB.
1010 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1011 }
Chris Lattner571e4342006-10-27 21:36:01 +00001012}
1013
Chris Lattnerdf19f272006-10-31 22:37:42 +00001014/// If the set of cases should be emitted as a series of branches, return true.
1015/// If we should emit this as a bunch of and/or'd together conditions, return
1016/// false.
1017static bool
1018ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1019 if (Cases.size() != 2) return true;
1020
Chris Lattner0ccb5002006-10-31 23:06:00 +00001021 // If this is two comparisons of the same values or'd or and'd together, they
1022 // will get folded into a single comparison, so don't emit two blocks.
1023 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1024 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1025 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1026 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1027 return false;
1028 }
1029
Chris Lattnerdf19f272006-10-31 22:37:42 +00001030 return true;
1031}
1032
Chris Lattner1c08c712005-01-07 07:47:53 +00001033void SelectionDAGLowering::visitBr(BranchInst &I) {
1034 // Update machine-CFG edges.
1035 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001036
1037 // Figure out which block is immediately after the current one.
1038 MachineBasicBlock *NextBlock = 0;
1039 MachineFunction::iterator BBI = CurMBB;
1040 if (++BBI != CurMBB->getParent()->end())
1041 NextBlock = BBI;
1042
1043 if (I.isUnconditional()) {
1044 // If this is not a fall-through branch, emit the branch.
1045 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001046 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001047 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001048
Chris Lattner57ab6592006-10-24 17:57:59 +00001049 // Update machine-CFG edges.
1050 CurMBB->addSuccessor(Succ0MBB);
1051
1052 return;
1053 }
1054
1055 // If this condition is one of the special cases we handle, do special stuff
1056 // now.
1057 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001058 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001059
1060 // If this is a series of conditions that are or'd or and'd together, emit
1061 // this as a sequence of branches instead of setcc's with and/or operations.
1062 // For example, instead of something like:
1063 // cmp A, B
1064 // C = seteq
1065 // cmp D, E
1066 // F = setle
1067 // or C, F
1068 // jnz foo
1069 // Emit:
1070 // cmp A, B
1071 // je foo
1072 // cmp D, E
1073 // jle foo
1074 //
1075 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1076 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001077 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001078 BOp->getOpcode() == Instruction::Or)) {
1079 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001080 // If the compares in later blocks need to use values not currently
1081 // exported from this block, export them now. This block should always
1082 // be the first entry.
1083 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1084
Chris Lattnerdf19f272006-10-31 22:37:42 +00001085 // Allow some cases to be rejected.
1086 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001087 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1088 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1089 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1090 }
1091
1092 // Emit the branch for this block.
1093 visitSwitchCase(SwitchCases[0]);
1094 SwitchCases.erase(SwitchCases.begin());
1095 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001096 }
1097
Chris Lattner0ccb5002006-10-31 23:06:00 +00001098 // Okay, we decided not to do this, remove any inserted MBB's and clear
1099 // SwitchCases.
1100 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1101 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1102
Chris Lattnerdf19f272006-10-31 22:37:42 +00001103 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001104 }
1105 }
Chris Lattner24525952006-10-24 18:07:37 +00001106
1107 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001108 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001109 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001110 // Use visitSwitchCase to actually insert the fast branch sequence for this
1111 // cond branch.
1112 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001113}
1114
Nate Begemanf15485a2006-03-27 01:32:24 +00001115/// visitSwitchCase - Emits the necessary code to represent a single node in
1116/// the binary search tree resulting from lowering a switch instruction.
1117void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001118 SDOperand Cond;
1119 SDOperand CondLHS = getValue(CB.CmpLHS);
1120
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001121 // Build the setcc now.
1122 if (CB.CmpMHS == NULL) {
1123 // Fold "(X == true)" to X and "(X == false)" to !X to
1124 // handle common cases produced by branch lowering.
1125 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1126 Cond = CondLHS;
1127 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1128 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1129 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1130 } else
1131 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1132 } else {
1133 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001134
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001135 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1136 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1137
1138 SDOperand CmpOp = getValue(CB.CmpMHS);
1139 MVT::ValueType VT = CmpOp.getValueType();
1140
1141 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1142 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1143 } else {
1144 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1145 Cond = DAG.getSetCC(MVT::i1, SUB,
1146 DAG.getConstant(High-Low, VT), ISD::SETULE);
1147 }
1148
1149 }
1150
Nate Begemanf15485a2006-03-27 01:32:24 +00001151 // Set NextBlock to be the MBB immediately after the current one, if any.
1152 // This is used to avoid emitting unnecessary branches to the next block.
1153 MachineBasicBlock *NextBlock = 0;
1154 MachineFunction::iterator BBI = CurMBB;
1155 if (++BBI != CurMBB->getParent()->end())
1156 NextBlock = BBI;
1157
1158 // If the lhs block is the next block, invert the condition so that we can
1159 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001160 if (CB.TrueBB == NextBlock) {
1161 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001162 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1163 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1164 }
1165 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001166 DAG.getBasicBlock(CB.TrueBB));
1167 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001168 DAG.setRoot(BrCond);
1169 else
1170 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001171 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001172 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001173 CurMBB->addSuccessor(CB.TrueBB);
1174 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001175}
1176
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001177/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001178void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001179 // Emit the code for the jump table
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001180 assert(JT.Reg != -1UL && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001181 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001182 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1183 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1184 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1185 Table, Index));
1186 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001187}
1188
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001189/// visitJumpTableHeader - This function emits necessary code to produce index
1190/// in the JumpTable from switch case.
1191void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1192 SelectionDAGISel::JumpTableHeader &JTH) {
1193 // Subtract the lowest switch case value from the value being switched on
1194 // and conditional branch to default mbb if the result is greater than the
1195 // difference between smallest and largest cases.
1196 SDOperand SwitchOp = getValue(JTH.SValue);
1197 MVT::ValueType VT = SwitchOp.getValueType();
1198 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1199 DAG.getConstant(JTH.First, VT));
1200
1201 // The SDNode we just created, which holds the value being switched on
1202 // minus the the smallest case value, needs to be copied to a virtual
1203 // register so it can be used as an index into the jump table in a
1204 // subsequent basic block. This value may be smaller or larger than the
1205 // target's pointer type, and therefore require extension or truncating.
1206 if (VT > TLI.getPointerTy())
1207 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1208 else
1209 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1210
1211 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1212 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1213 JT.Reg = JumpTableReg;
1214
1215 // Emit the range check for the jump table, and branch to the default
1216 // block for the switch statement if the value being switched on exceeds
1217 // the largest case in the switch.
1218 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1219 DAG.getConstant(JTH.Last-JTH.First,VT),
1220 ISD::SETUGT);
1221
1222 // Set NextBlock to be the MBB immediately after the current one, if any.
1223 // This is used to avoid emitting unnecessary branches to the next block.
1224 MachineBasicBlock *NextBlock = 0;
1225 MachineFunction::iterator BBI = CurMBB;
1226 if (++BBI != CurMBB->getParent()->end())
1227 NextBlock = BBI;
1228
1229 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1230 DAG.getBasicBlock(JT.Default));
1231
1232 if (JT.MBB == NextBlock)
1233 DAG.setRoot(BrCond);
1234 else
1235 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001236 DAG.getBasicBlock(JT.MBB)));
1237
1238 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001239}
1240
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001241/// visitBitTestHeader - This function emits necessary code to produce value
1242/// suitable for "bit tests"
1243void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1244 // Subtract the minimum value
1245 SDOperand SwitchOp = getValue(B.SValue);
1246 MVT::ValueType VT = SwitchOp.getValueType();
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1248 DAG.getConstant(B.First, VT));
1249
1250 // Check range
1251 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1252 DAG.getConstant(B.Range, VT),
1253 ISD::SETUGT);
1254
1255 SDOperand ShiftOp;
1256 if (VT > TLI.getShiftAmountTy())
1257 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1258 else
1259 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1260
1261 // Make desired shift
1262 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1263 DAG.getConstant(1, TLI.getPointerTy()),
1264 ShiftOp);
1265
1266 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1267 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1268 B.Reg = SwitchReg;
1269
1270 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1271 DAG.getBasicBlock(B.Default));
1272
1273 // Set NextBlock to be the MBB immediately after the current one, if any.
1274 // This is used to avoid emitting unnecessary branches to the next block.
1275 MachineBasicBlock *NextBlock = 0;
1276 MachineFunction::iterator BBI = CurMBB;
1277 if (++BBI != CurMBB->getParent()->end())
1278 NextBlock = BBI;
1279
1280 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1281 if (MBB == NextBlock)
1282 DAG.setRoot(BrRange);
1283 else
1284 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1285 DAG.getBasicBlock(MBB)));
1286
1287 CurMBB->addSuccessor(B.Default);
1288 CurMBB->addSuccessor(MBB);
1289
1290 return;
1291}
1292
1293/// visitBitTestCase - this function produces one "bit test"
1294void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1295 unsigned Reg,
1296 SelectionDAGISel::BitTestCase &B) {
1297 // Emit bit tests and jumps
1298 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1299
1300 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1301 SwitchVal,
1302 DAG.getConstant(B.Mask,
1303 TLI.getPointerTy()));
1304 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1305 DAG.getConstant(0, TLI.getPointerTy()),
1306 ISD::SETNE);
1307 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1308 AndCmp, DAG.getBasicBlock(B.TargetBB));
1309
1310 // Set NextBlock to be the MBB immediately after the current one, if any.
1311 // This is used to avoid emitting unnecessary branches to the next block.
1312 MachineBasicBlock *NextBlock = 0;
1313 MachineFunction::iterator BBI = CurMBB;
1314 if (++BBI != CurMBB->getParent()->end())
1315 NextBlock = BBI;
1316
1317 if (NextMBB == NextBlock)
1318 DAG.setRoot(BrAnd);
1319 else
1320 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1321 DAG.getBasicBlock(NextMBB)));
1322
1323 CurMBB->addSuccessor(B.TargetBB);
1324 CurMBB->addSuccessor(NextMBB);
1325
1326 return;
1327}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001328
Jim Laskeyb180aa12007-02-21 22:53:45 +00001329void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001330 assert(0 && "Should never be visited directly");
1331}
1332void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001333 // Retrieve successors.
1334 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1335 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1336
Jim Laskey183f47f2007-02-25 21:43:59 +00001337 if (!AsTerminator) {
1338 // Mark landing pad so that it doesn't get deleted in branch folding.
1339 LandingPad->setIsLandingPad();
1340
1341 // Insert a label before the invoke call to mark the try range.
1342 // This can be used to detect deletion of the invoke via the
1343 // MachineModuleInfo.
1344 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1345 unsigned BeginLabel = MMI->NextLabelID();
1346 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1347 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001348
Jim Laskey183f47f2007-02-25 21:43:59 +00001349 LowerCallTo(I, I.getCalledValue()->getType(),
1350 I.getCallingConv(),
1351 false,
1352 getValue(I.getOperand(0)),
1353 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001354
Jim Laskey183f47f2007-02-25 21:43:59 +00001355 // Insert a label before the invoke call to mark the try range.
1356 // This can be used to detect deletion of the invoke via the
1357 // MachineModuleInfo.
1358 unsigned EndLabel = MMI->NextLabelID();
1359 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1360 DAG.getConstant(EndLabel, MVT::i32)));
1361
1362 // Inform MachineModuleInfo of range.
1363 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1364
1365 // Update successor info
1366 CurMBB->addSuccessor(Return);
1367 CurMBB->addSuccessor(LandingPad);
1368 } else {
1369 // Drop into normal successor.
1370 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1371 DAG.getBasicBlock(Return)));
1372 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001373}
1374
1375void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1376}
1377
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001378/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001379/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001380bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001381 CaseRecVector& WorkList,
1382 Value* SV,
1383 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001384 Case& BackCase = *(CR.Range.second-1);
1385
1386 // Size is the number of Cases represented by this range.
1387 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001388 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001389 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001390
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001391 // Get the MachineFunction which holds the current MBB. This is used when
1392 // inserting any additional MBBs necessary to represent the switch.
1393 MachineFunction *CurMF = CurMBB->getParent();
1394
1395 // Figure out which block is immediately after the current one.
1396 MachineBasicBlock *NextBlock = 0;
1397 MachineFunction::iterator BBI = CR.CaseBB;
1398
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001399 if (++BBI != CurMBB->getParent()->end())
1400 NextBlock = BBI;
1401
1402 // TODO: If any two of the cases has the same destination, and if one value
1403 // is the same as the other, but has one bit unset that the other has set,
1404 // use bit manipulation to do two compares at once. For example:
1405 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1406
1407 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001408 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001409 // The last case block won't fall through into 'NextBlock' if we emit the
1410 // branches in this order. See if rearranging a case value would help.
1411 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001412 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001413 std::swap(*I, BackCase);
1414 break;
1415 }
1416 }
1417 }
1418
1419 // Create a CaseBlock record representing a conditional branch to
1420 // the Case's target mbb if the value being switched on SV is equal
1421 // to C.
1422 MachineBasicBlock *CurBlock = CR.CaseBB;
1423 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1424 MachineBasicBlock *FallThrough;
1425 if (I != E-1) {
1426 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1427 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1428 } else {
1429 // If the last case doesn't match, go to the default block.
1430 FallThrough = Default;
1431 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001432
1433 Value *RHS, *LHS, *MHS;
1434 ISD::CondCode CC;
1435 if (I->High == I->Low) {
1436 // This is just small small case range :) containing exactly 1 case
1437 CC = ISD::SETEQ;
1438 LHS = SV; RHS = I->High; MHS = NULL;
1439 } else {
1440 CC = ISD::SETLE;
1441 LHS = I->Low; MHS = SV; RHS = I->High;
1442 }
1443 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1444 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001445
1446 // If emitting the first comparison, just call visitSwitchCase to emit the
1447 // code into the current block. Otherwise, push the CaseBlock onto the
1448 // vector to be later processed by SDISel, and insert the node's MBB
1449 // before the next MBB.
1450 if (CurBlock == CurMBB)
1451 visitSwitchCase(CB);
1452 else
1453 SwitchCases.push_back(CB);
1454
1455 CurBlock = FallThrough;
1456 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001457
1458 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001459}
1460
1461/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001462bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001463 CaseRecVector& WorkList,
1464 Value* SV,
1465 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001466 Case& FrontCase = *CR.Range.first;
1467 Case& BackCase = *(CR.Range.second-1);
1468
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001469 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1470 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1471
1472 uint64_t TSize = 0;
1473 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1474 I!=E; ++I)
1475 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001476
1477 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1478 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001479 TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001480 return false;
1481
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001482 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1483 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001484 return false;
1485
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001486 DOUT << "Lowering jump table\n"
1487 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001488 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001489
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001490 // Get the MachineFunction which holds the current MBB. This is used when
1491 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001492 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001493
1494 // Figure out which block is immediately after the current one.
1495 MachineBasicBlock *NextBlock = 0;
1496 MachineFunction::iterator BBI = CR.CaseBB;
1497
1498 if (++BBI != CurMBB->getParent()->end())
1499 NextBlock = BBI;
1500
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001501 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1502
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001503 // Create a new basic block to hold the code for loading the address
1504 // of the jump table, and jumping to it. Update successor information;
1505 // we will either branch to the default case for the switch, or the jump
1506 // table.
1507 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1508 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1509 CR.CaseBB->addSuccessor(Default);
1510 CR.CaseBB->addSuccessor(JumpTableBB);
1511
1512 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001513 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001514 // a case statement, push the case's BB onto the vector, otherwise, push
1515 // the default BB.
1516 std::vector<MachineBasicBlock*> DestBBs;
1517 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001518 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1519 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1520 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1521
1522 if ((Low <= TEI) && (TEI <= High)) {
1523 DestBBs.push_back(I->BB);
1524 if (TEI==High)
1525 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001526 } else {
1527 DestBBs.push_back(Default);
1528 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001529 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001530
1531 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001532 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001533 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1534 E = DestBBs.end(); I != E; ++I) {
1535 if (!SuccsHandled[(*I)->getNumber()]) {
1536 SuccsHandled[(*I)->getNumber()] = true;
1537 JumpTableBB->addSuccessor(*I);
1538 }
1539 }
1540
1541 // Create a jump table index for this jump table, or return an existing
1542 // one.
1543 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1544
1545 // Set the jump table information so that we can codegen it as a second
1546 // MachineBasicBlock
1547 SelectionDAGISel::JumpTable JT(-1UL, JTI, JumpTableBB, Default);
1548 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1549 (CR.CaseBB == CurMBB));
1550 if (CR.CaseBB == CurMBB)
1551 visitJumpTableHeader(JT, JTH);
1552
1553 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001554
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001555 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001556}
1557
1558/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1559/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001560bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001561 CaseRecVector& WorkList,
1562 Value* SV,
1563 MachineBasicBlock* Default) {
1564 // Get the MachineFunction which holds the current MBB. This is used when
1565 // inserting any additional MBBs necessary to represent the switch.
1566 MachineFunction *CurMF = CurMBB->getParent();
1567
1568 // Figure out which block is immediately after the current one.
1569 MachineBasicBlock *NextBlock = 0;
1570 MachineFunction::iterator BBI = CR.CaseBB;
1571
1572 if (++BBI != CurMBB->getParent()->end())
1573 NextBlock = BBI;
1574
1575 Case& FrontCase = *CR.Range.first;
1576 Case& BackCase = *(CR.Range.second-1);
1577 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1578
1579 // Size is the number of Cases represented by this range.
1580 unsigned Size = CR.Range.second - CR.Range.first;
1581
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001582 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1583 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001584 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001585 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001586
1587 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1588 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001589 uint64_t TSize = 0;
1590 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1591 I!=E; ++I)
1592 TSize += I->size();
1593
1594 uint64_t LSize = FrontCase.size();
1595 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001596 DOUT << "Selecting best pivot: \n"
1597 << "First: " << First << ", Last: " << Last <<"\n"
1598 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001599 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001600 J!=E; ++I, ++J) {
1601 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1602 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001603 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001604 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1605 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001606 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001607 // Should always split in some non-trivial place
1608 DOUT <<"=>Step\n"
1609 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1610 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1611 << "Metric: " << Metric << "\n";
1612 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001613 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001614 FMetric = Metric;
1615 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001616 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001617
1618 LSize += J->size();
1619 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001620 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001621 // If our case is dense we *really* should handle it earlier!
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001622 assert((FMetric > 0) && "Should handle dense range earlier!");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001623
1624 CaseRange LHSR(CR.Range.first, Pivot);
1625 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001626 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001627 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1628
1629 // We know that we branch to the LHS if the Value being switched on is
1630 // less than the Pivot value, C. We use this to optimize our binary
1631 // tree a bit, by recognizing that if SV is greater than or equal to the
1632 // LHS's Case Value, and that Case Value is exactly one less than the
1633 // Pivot's Value, then we can branch directly to the LHS's Target,
1634 // rather than creating a leaf node for it.
1635 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001636 LHSR.first->High == CR.GE &&
1637 cast<ConstantInt>(C)->getSExtValue() ==
1638 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1639 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001640 } else {
1641 TrueBB = new MachineBasicBlock(LLVMBB);
1642 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1643 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1644 }
1645
1646 // Similar to the optimization above, if the Value being switched on is
1647 // known to be less than the Constant CR.LT, and the current Case Value
1648 // is CR.LT - 1, then we can branch directly to the target block for
1649 // the current Case Value, rather than emitting a RHS leaf node for it.
1650 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001651 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1652 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1653 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001654 } else {
1655 FalseBB = new MachineBasicBlock(LLVMBB);
1656 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1657 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1658 }
1659
1660 // Create a CaseBlock record representing a conditional branch to
1661 // the LHS node if the value being switched on SV is less than C.
1662 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001663 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1664 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001665
1666 if (CR.CaseBB == CurMBB)
1667 visitSwitchCase(CB);
1668 else
1669 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001670
1671 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001672}
1673
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001674/// handleBitTestsSwitchCase - if current case range has few destination and
1675/// range span less, than machine word bitwidth, encode case range into series
1676/// of masks and emit bit tests with these masks.
1677bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1678 CaseRecVector& WorkList,
1679 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001680 MachineBasicBlock* Default){
Chris Lattner1c359682007-04-14 19:39:41 +00001681 return false;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001682 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 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001734 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001735 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++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001759 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001760 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 Cohenefc36622007-04-09 14:32:59 +00001787 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-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 Korobeynikov5502bf62007-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 Begemanf15485a2006-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 Wendlingc70ddad2006-10-19 21:46:38 +00001844
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001845 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001846
Nate Begemanf15485a2006-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 Korobeynikov5502bf62007-04-04 21:14:49 +00001849 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001850 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001851
Nate Begemanf15485a2006-03-27 01:32:24 +00001852 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001853 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001854 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001855 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001856
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001857 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-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 Korobeynikov5502bf62007-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 Wendlingc70ddad2006-10-19 21:46:38 +00001868
Nate Begemanf15485a2006-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 Korobeynikov5502bf62007-04-04 21:14:49 +00001872 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001873
Nate Begemanf15485a2006-03-27 01:32:24 +00001874 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001875 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001876 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1877
1878 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001879 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001880 CaseRec CR = WorkList.back();
1881 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001882
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001883 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1884 continue;
1885
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001886 // If the range has few cases (two or less) emit a series of specific
1887 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001888 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1889 continue;
1890
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001891 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-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 Korobeynikovdd433212007-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 Begemanf15485a2006-03-27 01:32:24 +00001900 }
1901}
1902
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001903
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001904void SelectionDAGLowering::visitSub(User &I) {
1905 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001906 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001907 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001908 visitVectorBinary(I, ISD::VSUB);
1909 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-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 Spencer24d6da52007-01-21 00:29:26 +00001916 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001917 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001918 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001919}
1920
Reid Spencer24d6da52007-01-21 00:29:26 +00001921void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001922 SDOperand Op1 = getValue(I.getOperand(0));
1923 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001924
1925 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001926}
1927
Reid Spencer24d6da52007-01-21 00:29:26 +00001928void
1929SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001930 assert(isa<VectorType>(I.getType()));
1931 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001932 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001933
Reid Spencer24d6da52007-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 Spencer9d6565a2007-02-15 02:26:10 +00001943 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001944 visitVectorBinary(I, VectorOp);
1945 else
1946 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001947}
Chris Lattner2c49f272005-01-19 22:31:21 +00001948
Nate Begemane21ea612005-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 Spencer832254e2007-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 Begemane21ea612005-11-18 07:42:56 +00001957
Chris Lattner1c08c712005-01-07 07:47:53 +00001958 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1959}
1960
Reid Spencer45fb3f32006-11-20 01:22:35 +00001961void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-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 Spencer45fb3f32006-11-20 01:22:35 +00001969 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001970 switch (predicate) {
Reid Spencer45fb3f32006-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 Spencere4d87aa2006-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 Lattner1c08c712005-01-07 07:47:53 +00001995 SDOperand Op1 = getValue(I.getOperand(0));
1996 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-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 Lattner1c08c712005-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 Spencer9d6565a2007-02-15 02:26:10 +00002031 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-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 Lattner1c08c712005-01-07 07:47:53 +00002039}
2040
Reid Spencer3da59db2006-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 Lattner1c08c712005-01-07 07:47:53 +00002110 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002111 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002112 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-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 Lattner1c08c712005-01-07 07:47:53 +00002121
Reid Spencer3da59db2006-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 Lattnere25ca692006-03-22 20:09:35 +00002138 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002139 // This is a cast to a vector from something else.
2140 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002141 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-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 Spencer3da59db2006-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 Lattnere25ca692006-03-22 20:09:35 +00002152 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00002153 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002154 }
Reid Spencer3da59db2006-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 Lattner1c08c712005-01-07 07:47:53 +00002162}
2163
Chris Lattner2bbd8102006-03-29 00:11:43 +00002164void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-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 Lattner2332b9f2006-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 Lattnerc7029802006-03-18 01:44:44 +00002174}
2175
Chris Lattner2bbd8102006-03-29 00:11:43 +00002176void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-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 Lattnerc7029802006-03-18 01:44:44 +00002184
Chris Lattner3e104b12006-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 Lattner1c08c712005-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 Lattner1c08c712005-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 Lattnerc88d8e92005-12-05 07:10:48 +00002204 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002205 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002206 if (Field) {
2207 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002208 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002209 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00002210 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002211 }
2212 Ty = StTy->getElementType(Field);
2213 } else {
2214 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002215
Chris Lattner7c0104b2005-11-09 04:45:33 +00002216 // If this is a constant subscript, handle it quickly.
2217 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002218 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002219 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00002220 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00002221 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2222 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002223 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002224
2225 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00002226 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-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 Spencer47857812006-12-31 05:55:36 +00002232 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-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 Lattner6b2d6962005-11-09 16:50:40 +00002241 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-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 Lattner1c08c712005-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 Andersona69571c2006-05-03 01:29:57 +00002261 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002262 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002263 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002264 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002265
2266 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-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 Lattner1c08c712005-01-07 07:47:53 +00002272
Chris Lattner68cd65e2005-01-22 23:04:37 +00002273 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-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 Lattnerbd564bf2006-08-08 02:23:42 +00002292 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-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 Lattner0da331f2007-02-04 01:31:47 +00002296 setValue(&I, DSA);
2297 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-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 Lattner1c08c712005-01-07 07:47:53 +00002304void SelectionDAGLowering::visitLoad(LoadInst &I) {
2305 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002306
Chris Lattnerd3948112005-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 Lattner28b5b1c2006-03-15 22:19:46 +00002314
Evan Cheng466685d2006-10-09 20:57:25 +00002315 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002316 Root, I.isVolatile()));
2317}
2318
2319SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002320 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002321 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002322 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002323 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00002324 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00002325 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2326 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002327 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002328 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002329 }
Chris Lattnerd3948112005-01-17 22:19:26 +00002330
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002331 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002332 DAG.setRoot(L.getValue(1));
2333 else
2334 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002335
2336 return L;
Chris Lattner1c08c712005-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 Cheng0b4f80e2006-12-20 01:27:29 +00002344 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00002345 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002346}
2347
Chris Lattner0eade312006-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 Lattnere58a7802006-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 Lattner0eade312006-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 Lattner7255a542006-03-24 22:49:42 +00002370 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002371 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002372
2373 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002374 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-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 Lattner0eade312006-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 Spencerac9dcb92007-02-15 03:39:18 +00002391 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00002392 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002393 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-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 Spencer9d6565a2007-02-15 02:26:10 +00002410 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-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 Lattnerf9f37fc2006-08-14 23:53:35 +00002423 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2424
Chris Lattner0eade312006-03-24 02:22:33 +00002425 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002426 SDOperand Result;
2427 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002428 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2429 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002430 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002431 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2432 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002433 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002434 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2435 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002436
Chris Lattnere58a7802006-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 Lattner0eade312006-03-24 02:22:33 +00002444 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002445 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-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 Lattnerc9ea6fd2005-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 Lattner0eade312006-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 Lattnerc9ea6fd2005-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 Begemanbcc5f362007-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 Lattnerc9ea6fd2005-11-09 19:44:01 +00002476 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002477 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002478 break;
2479 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002480 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002481 break;
Chris Lattner03dd4652006-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 Lattnerc9ea6fd2005-11-09 19:44:01 +00002494
Chris Lattner86cb6432005-12-13 17:40:33 +00002495 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002496 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002497 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002498 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002499 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002500
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002501 Ops[0] = getRoot();
2502 Ops[1] = getValue(SPI.getLineValue());
2503 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002504
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002505 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002506 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002507 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2508
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002509 Ops[3] = DAG.getString(CompileUnit->getFileName());
2510 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002511
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002512 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002513 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002514
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002515 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002516 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002517 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002518 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002519 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002520 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2521 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002522 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002523 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002524 }
2525
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002526 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002527 }
2528 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002529 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002530 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002531 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2532 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002533 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002534 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002535 }
2536
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002537 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002538 }
2539 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002540 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002541 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002542 if (MMI && FSI.getSubprogram() &&
2543 MMI->Verify(FSI.getSubprogram())) {
2544 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002545 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002546 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002547 }
2548
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002549 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002550 }
2551 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002552 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002553 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002554 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002555 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002556 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002557 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002558 }
2559
2560 return 0;
2561 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002562
Jim Laskeyb180aa12007-02-21 22:53:45 +00002563 case Intrinsic::eh_exception: {
2564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2565
Jim Laskey735b6f82007-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 Laskey7a1de982007-02-24 09:45:44 +00002584 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002585 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002586 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002587 return 0;
2588 }
2589
Jim Laskey0b4711b2007-03-01 20:24:30 +00002590 case Intrinsic::eh_selector:
2591 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002592 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2593
Jim Laskey735b6f82007-02-22 15:38:06 +00002594 if (MMI) {
2595 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-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 Laskey0b4711b2007-03-01 20:24:30 +00002601 if (Intrinsic == Intrinsic::eh_filter)
2602 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002603
Jim Laskey735b6f82007-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 Laskeycbfdb7b2007-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 Laskey735b6f82007-02-22 15:38:06 +00002617 }
Jim Laskey735b6f82007-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 Laskey64ce0ca2007-02-28 18:37:04 +00002626 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-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 Laskey7a1de982007-02-24 09:45:44 +00002633 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002634 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002635 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002636
2637 return 0;
2638 }
2639
2640 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002641 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002642
Jim Laskey735b6f82007-02-22 15:38:06 +00002643 if (MMI) {
2644 // Find the type id for the given typeinfo.
2645 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-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 Laskey735b6f82007-02-22 15:38:06 +00002655 }
2656
2657 unsigned TypeID = MMI->getTypeIDFor(GV);
2658 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002659 } else {
2660 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002661 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002662
2663 return 0;
2664 }
2665
Reid Spencer0b118202006-01-16 21:12:35 +00002666 case Intrinsic::sqrt_f32:
2667 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-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 Lattner6ddf8ed2006-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 Lattnerc9ea6fd2005-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 Lenharth8b91c772005-11-11 22:48:54 +00002684 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002685 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002686 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2687 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2688 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002689 setValue(&I, Tmp);
2690 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002691 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002692 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00002693 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002694 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00002695 assert(0 && "part_select intrinsic not implemented");
2696 abort();
2697 }
2698 case Intrinsic::part_set: {
2699 // Currently not implemented: just abort
2700 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00002701 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002702 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002703 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002704 setValue(&I, DAG.getNode(ISD::BSWAP,
2705 getValue(I.getOperand(1)).getValueType(),
2706 getValue(I.getOperand(1))));
2707 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002708 case Intrinsic::cttz: {
2709 SDOperand Arg = getValue(I.getOperand(1));
2710 MVT::ValueType Ty = Arg.getValueType();
2711 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2712 if (Ty < MVT::i32)
2713 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2714 else if (Ty > MVT::i32)
2715 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2716 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002717 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002718 }
2719 case Intrinsic::ctlz: {
2720 SDOperand Arg = getValue(I.getOperand(1));
2721 MVT::ValueType Ty = Arg.getValueType();
2722 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2723 if (Ty < MVT::i32)
2724 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2725 else if (Ty > MVT::i32)
2726 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2727 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002728 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002729 }
2730 case Intrinsic::ctpop: {
2731 SDOperand Arg = getValue(I.getOperand(1));
2732 MVT::ValueType Ty = Arg.getValueType();
2733 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2734 if (Ty < MVT::i32)
2735 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2736 else if (Ty > MVT::i32)
2737 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2738 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002739 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002740 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002741 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002742 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002743 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2744 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002745 setValue(&I, Tmp);
2746 DAG.setRoot(Tmp.getValue(1));
2747 return 0;
2748 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002749 case Intrinsic::stackrestore: {
2750 SDOperand Tmp = getValue(I.getOperand(1));
2751 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002752 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002753 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002754 case Intrinsic::prefetch:
2755 // FIXME: Currently discarding prefetches.
2756 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002757 }
2758}
2759
2760
Jim Laskey1da20a72007-02-23 21:45:01 +00002761void SelectionDAGLowering::LowerCallTo(Instruction &I,
2762 const Type *CalledValueTy,
2763 unsigned CallingConv,
2764 bool IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002765 SDOperand Callee, unsigned OpIdx) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002766 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002767 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer5694b6e2007-04-09 06:17:21 +00002768 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey735b6f82007-02-22 15:38:06 +00002769
2770 TargetLowering::ArgListTy Args;
2771 TargetLowering::ArgListEntry Entry;
2772 Args.reserve(I.getNumOperands());
2773 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2774 Value *Arg = I.getOperand(i);
2775 SDOperand ArgNode = getValue(Arg);
2776 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencer18da0722007-04-11 02:44:20 +00002777 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2778 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2779 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2780 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
Jim Laskey735b6f82007-02-22 15:38:06 +00002781 Args.push_back(Entry);
2782 }
2783
2784 std::pair<SDOperand,SDOperand> Result =
2785 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer18da0722007-04-11 02:44:20 +00002786 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey1da20a72007-02-23 21:45:01 +00002787 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002788 Callee, Args, DAG);
2789 if (I.getType() != Type::VoidTy)
2790 setValue(&I, Result.first);
2791 DAG.setRoot(Result.second);
2792}
2793
2794
Chris Lattner1c08c712005-01-07 07:47:53 +00002795void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002796 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002797 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002798 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002799 if (unsigned IID = F->getIntrinsicID()) {
2800 RenameFn = visitIntrinsicCall(I, IID);
2801 if (!RenameFn)
2802 return;
2803 } else { // Not an LLVM intrinsic.
2804 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002805 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2806 if (I.getNumOperands() == 3 && // Basic sanity checks.
2807 I.getOperand(1)->getType()->isFloatingPoint() &&
2808 I.getType() == I.getOperand(1)->getType() &&
2809 I.getType() == I.getOperand(2)->getType()) {
2810 SDOperand LHS = getValue(I.getOperand(1));
2811 SDOperand RHS = getValue(I.getOperand(2));
2812 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2813 LHS, RHS));
2814 return;
2815 }
2816 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002817 if (I.getNumOperands() == 2 && // Basic sanity checks.
2818 I.getOperand(1)->getType()->isFloatingPoint() &&
2819 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002820 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002821 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2822 return;
2823 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002824 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002825 if (I.getNumOperands() == 2 && // Basic sanity checks.
2826 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002827 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002828 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002829 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2830 return;
2831 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002832 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002833 if (I.getNumOperands() == 2 && // Basic sanity checks.
2834 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002835 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002836 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002837 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2838 return;
2839 }
2840 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002841 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002842 } else if (isa<InlineAsm>(I.getOperand(0))) {
2843 visitInlineAsm(I);
2844 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002845 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002846
Chris Lattner64e14b12005-01-08 22:48:57 +00002847 SDOperand Callee;
2848 if (!RenameFn)
2849 Callee = getValue(I.getOperand(0));
2850 else
2851 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002852
Jim Laskey1da20a72007-02-23 21:45:01 +00002853 LowerCallTo(I, I.getCalledValue()->getType(),
2854 I.getCallingConv(),
2855 I.isTailCall(),
2856 Callee,
2857 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002858}
2859
Jim Laskey735b6f82007-02-22 15:38:06 +00002860
Chris Lattner864635a2006-02-22 22:37:12 +00002861SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002862 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002863 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2864 Chain = Val.getValue(1);
2865 Flag = Val.getValue(2);
2866
2867 // If the result was expanded, copy from the top part.
2868 if (Regs.size() > 1) {
2869 assert(Regs.size() == 2 &&
2870 "Cannot expand to more than 2 elts yet!");
2871 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002872 Chain = Hi.getValue(1);
2873 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002874 if (DAG.getTargetLoweringInfo().isLittleEndian())
2875 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2876 else
2877 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002878 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002879
Chris Lattnercf752aa2006-06-08 18:22:48 +00002880 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002881 // appropriate type.
2882 if (RegVT == ValueVT)
2883 return Val;
2884
Chris Lattner5df99b32007-03-25 05:00:54 +00002885 if (MVT::isVector(RegVT)) {
2886 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2887 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2888 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2889 MVT::i32),
2890 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2891 }
2892
Chris Lattnercf752aa2006-06-08 18:22:48 +00002893 if (MVT::isInteger(RegVT)) {
2894 if (ValueVT < RegVT)
2895 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2896 else
2897 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002898 }
Chris Lattner5df99b32007-03-25 05:00:54 +00002899
2900 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2901 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002902}
2903
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002904/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2905/// specified value into the registers specified by this object. This uses
2906/// Chain/Flag as the input and updates them for the output Chain/Flag.
2907void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002908 SDOperand &Chain, SDOperand &Flag,
2909 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002910 if (Regs.size() == 1) {
2911 // If there is a single register and the types differ, this must be
2912 // a promotion.
2913 if (RegVT != ValueVT) {
Chris Lattner5df99b32007-03-25 05:00:54 +00002914 if (MVT::isVector(RegVT)) {
2915 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2916 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002917 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002918 if (RegVT < ValueVT)
2919 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2920 else
2921 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002922 } else if (MVT::isFloatingPoint(RegVT) &&
2923 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002924 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002925 } else if (MVT::getSizeInBits(RegVT) ==
2926 MVT::getSizeInBits(Val.getValueType())) {
2927 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2928 } else {
2929 assert(0 && "Unknown mismatch!");
2930 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002931 }
2932 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2933 Flag = Chain.getValue(1);
2934 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002935 std::vector<unsigned> R(Regs);
2936 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2937 std::reverse(R.begin(), R.end());
2938
2939 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002940 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002941 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002942 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002943 Flag = Chain.getValue(1);
2944 }
2945 }
2946}
Chris Lattner864635a2006-02-22 22:37:12 +00002947
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002948/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2949/// operand list. This adds the code marker and includes the number of
2950/// values added into it.
2951void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002952 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00002953 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2954 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002955 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2956 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2957}
Chris Lattner864635a2006-02-22 22:37:12 +00002958
2959/// isAllocatableRegister - If the specified register is safe to allocate,
2960/// i.e. it isn't a stack pointer or some other special register, return the
2961/// register class for the register. Otherwise, return null.
2962static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002963isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2964 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002965 MVT::ValueType FoundVT = MVT::Other;
2966 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002967 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2968 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002969 MVT::ValueType ThisVT = MVT::Other;
2970
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002971 const TargetRegisterClass *RC = *RCI;
2972 // If none of the the value types for this register class are valid, we
2973 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002974 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2975 I != E; ++I) {
2976 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002977 // If we have already found this register in a different register class,
2978 // choose the one with the largest VT specified. For example, on
2979 // PowerPC, we favor f64 register classes over f32.
2980 if (FoundVT == MVT::Other ||
2981 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2982 ThisVT = *I;
2983 break;
2984 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002985 }
2986 }
2987
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002988 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002989
Chris Lattner864635a2006-02-22 22:37:12 +00002990 // NOTE: This isn't ideal. In particular, this might allocate the
2991 // frame pointer in functions that need it (due to them not being taken
2992 // out of allocation, because a variable sized allocation hasn't been seen
2993 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002994 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2995 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002996 if (*I == Reg) {
2997 // We found a matching register class. Keep looking at others in case
2998 // we find one with larger registers that this physreg is also in.
2999 FoundRC = RC;
3000 FoundVT = ThisVT;
3001 break;
3002 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003003 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003004 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003005}
3006
3007RegsForValue SelectionDAGLowering::
3008GetRegistersForValue(const std::string &ConstrCode,
3009 MVT::ValueType VT, bool isOutReg, bool isInReg,
3010 std::set<unsigned> &OutputRegs,
3011 std::set<unsigned> &InputRegs) {
3012 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3013 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
3014 std::vector<unsigned> Regs;
3015
3016 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
3017 MVT::ValueType RegVT;
3018 MVT::ValueType ValueVT = VT;
3019
Chris Lattner2a821602006-11-02 01:41:49 +00003020 // If this is a constraint for a specific physical register, like {r17},
3021 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00003022 if (PhysReg.first) {
3023 if (VT == MVT::Other)
3024 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00003025
3026 // Get the actual register value type. This is important, because the user
3027 // may have asked for (e.g.) the AX register in i32 type. We need to
3028 // remember that AX is actually i16 to get the right extension.
3029 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00003030
3031 // This is a explicit reference to a physical register.
3032 Regs.push_back(PhysReg.first);
3033
3034 // If this is an expanded reference, add the rest of the regs to Regs.
3035 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00003036 TargetRegisterClass::iterator I = PhysReg.second->begin();
3037 TargetRegisterClass::iterator E = PhysReg.second->end();
3038 for (; *I != PhysReg.first; ++I)
3039 assert(I != E && "Didn't find reg!");
3040
3041 // Already added the first reg.
3042 --NumRegs; ++I;
3043 for (; NumRegs; --NumRegs, ++I) {
3044 assert(I != E && "Ran out of registers to allocate!");
3045 Regs.push_back(*I);
3046 }
3047 }
3048 return RegsForValue(Regs, RegVT, ValueVT);
3049 }
3050
Chris Lattner2a821602006-11-02 01:41:49 +00003051 // Otherwise, if this was a reference to an LLVM register class, create vregs
3052 // for this reference.
3053 std::vector<unsigned> RegClassRegs;
3054 if (PhysReg.second) {
3055 // If this is an early clobber or tied register, our regalloc doesn't know
3056 // how to maintain the constraint. If it isn't, go ahead and create vreg
3057 // and let the regalloc do the right thing.
3058 if (!isOutReg || !isInReg) {
Chris Lattner2a821602006-11-02 01:41:49 +00003059 RegVT = *PhysReg.second->vt_begin();
Chris Lattner3a508c92007-04-12 06:00:20 +00003060
3061 if (VT == MVT::Other)
3062 ValueVT = RegVT;
Chris Lattner2a821602006-11-02 01:41:49 +00003063
3064 // Create the appropriate number of virtual registers.
3065 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
3066 for (; NumRegs; --NumRegs)
3067 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3068
3069 return RegsForValue(Regs, RegVT, ValueVT);
3070 }
3071
3072 // Otherwise, we can't allocate it. Let the code below figure out how to
3073 // maintain these constraints.
3074 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3075
3076 } else {
3077 // This is a reference to a register class that doesn't directly correspond
3078 // to an LLVM register class. Allocate NumRegs consecutive, available,
3079 // registers from the class.
3080 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
3081 }
Chris Lattner864635a2006-02-22 22:37:12 +00003082
3083 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3084 MachineFunction &MF = *CurMBB->getParent();
3085 unsigned NumAllocated = 0;
3086 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3087 unsigned Reg = RegClassRegs[i];
3088 // See if this register is available.
3089 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3090 (isInReg && InputRegs.count(Reg))) { // Already used.
3091 // Make sure we find consecutive registers.
3092 NumAllocated = 0;
3093 continue;
3094 }
3095
3096 // Check to see if this register is allocatable (i.e. don't give out the
3097 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003098 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00003099 if (!RC) {
3100 // Make sure we find consecutive registers.
3101 NumAllocated = 0;
3102 continue;
3103 }
3104
3105 // Okay, this register is good, we can use it.
3106 ++NumAllocated;
3107
Chris Lattnere303ac92007-04-06 17:47:14 +00003108 // If we allocated enough consecutive registers, succeed.
Chris Lattner864635a2006-02-22 22:37:12 +00003109 if (NumAllocated == NumRegs) {
3110 unsigned RegStart = (i-NumAllocated)+1;
3111 unsigned RegEnd = i+1;
3112 // Mark all of the allocated registers used.
3113 for (unsigned i = RegStart; i != RegEnd; ++i) {
3114 unsigned Reg = RegClassRegs[i];
3115 Regs.push_back(Reg);
3116 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3117 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3118 }
3119
3120 return RegsForValue(Regs, *RC->vt_begin(), VT);
3121 }
3122 }
3123
3124 // Otherwise, we couldn't allocate enough registers for this.
3125 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00003126}
3127
Chris Lattner367f1092007-01-29 23:45:14 +00003128/// getConstraintGenerality - Return an integer indicating how general CT is.
3129static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3130 switch (CT) {
3131 default: assert(0 && "Unknown constraint type!");
3132 case TargetLowering::C_Other:
3133 case TargetLowering::C_Unknown:
3134 return 0;
3135 case TargetLowering::C_Register:
3136 return 1;
3137 case TargetLowering::C_RegisterClass:
3138 return 2;
3139 case TargetLowering::C_Memory:
3140 return 3;
3141 }
3142}
3143
3144static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
3145 const TargetLowering &TLI) {
3146 assert(!C.empty() && "Must have at least one constraint");
3147 if (C.size() == 1) return C[0];
3148
3149 std::string *Current = &C[0];
3150 // If we have multiple constraints, try to pick the most general one ahead
3151 // of time. This isn't a wonderful solution, but handles common cases.
Chris Lattner4234f572007-03-25 02:14:49 +00003152 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
Chris Lattner367f1092007-01-29 23:45:14 +00003153 for (unsigned j = 1, e = C.size(); j != e; ++j) {
Chris Lattner4234f572007-03-25 02:14:49 +00003154 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
Chris Lattner367f1092007-01-29 23:45:14 +00003155 if (getConstraintGenerality(ThisFlavor) >
3156 getConstraintGenerality(Flavor)) {
3157 // This constraint letter is more general than the previous one,
3158 // use it.
3159 Flavor = ThisFlavor;
3160 Current = &C[j];
3161 }
3162 }
3163 return *Current;
3164}
3165
Chris Lattner864635a2006-02-22 22:37:12 +00003166
Chris Lattnerce7518c2006-01-26 22:24:51 +00003167/// visitInlineAsm - Handle a call to an InlineAsm object.
3168///
3169void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3170 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3171
3172 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
3173 MVT::Other);
3174
Chris Lattner2cc2f662006-02-01 01:28:23 +00003175 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00003176 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003177
3178 /// AsmNodeOperands - A list of pairs. The first element is a register, the
3179 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
3180 /// if it is a def of that register.
3181 std::vector<SDOperand> AsmNodeOperands;
3182 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3183 AsmNodeOperands.push_back(AsmStr);
3184
3185 SDOperand Chain = getRoot();
3186 SDOperand Flag;
3187
Chris Lattner4e4b5762006-02-01 18:59:47 +00003188 // We fully assign registers here at isel time. This is not optimal, but
3189 // should work. For register classes that correspond to LLVM classes, we
3190 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
3191 // over the constraints, collecting fixed registers that we know we can't use.
3192 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003193 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003194 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00003195 std::string ConstraintCode =
3196 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00003197
Chris Lattner1efa40f2006-02-22 00:56:39 +00003198 MVT::ValueType OpVT;
3199
3200 // Compute the value type for each operand and add it to ConstraintVTs.
3201 switch (Constraints[i].Type) {
3202 case InlineAsm::isOutput:
3203 if (!Constraints[i].isIndirectOutput) {
3204 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3205 OpVT = TLI.getValueType(I.getType());
3206 } else {
Chris Lattner22873462006-02-27 23:45:39 +00003207 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00003208 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
3209 OpNum++; // Consumes a call operand.
3210 }
3211 break;
3212 case InlineAsm::isInput:
3213 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
3214 OpNum++; // Consumes a call operand.
3215 break;
3216 case InlineAsm::isClobber:
3217 OpVT = MVT::Other;
3218 break;
3219 }
3220
3221 ConstraintVTs.push_back(OpVT);
3222
Chris Lattner864635a2006-02-22 22:37:12 +00003223 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
3224 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003225
Chris Lattner864635a2006-02-22 22:37:12 +00003226 // Build a list of regs that this operand uses. This always has a single
3227 // element for promoted/expanded operands.
3228 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
3229 false, false,
3230 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00003231
3232 switch (Constraints[i].Type) {
3233 case InlineAsm::isOutput:
3234 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00003235 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003236 // If this is an early-clobber output, it cannot be assigned to the same
3237 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00003238 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00003239 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003240 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003241 case InlineAsm::isInput:
3242 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00003243 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00003244 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003245 case InlineAsm::isClobber:
3246 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00003247 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3248 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00003249 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00003250 }
3251 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00003252
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003253 // Loop over all of the inputs, copying the operand values into the
3254 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003255 RegsForValue RetValRegs;
3256 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003257 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003258
Chris Lattner6656dd12006-01-31 02:03:41 +00003259 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00003260 std::string ConstraintCode =
3261 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003262
Chris Lattner2cc2f662006-02-01 01:28:23 +00003263 switch (Constraints[i].Type) {
3264 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00003265 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3266 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003267 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner22873462006-02-27 23:45:39 +00003268
3269 if (CTy == TargetLowering::C_Memory) {
3270 // Memory output.
3271 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3272
3273 // Check that the operand (the address to store to) isn't a float.
3274 if (!MVT::isInteger(InOperandVal.getValueType()))
3275 assert(0 && "MATCH FAIL!");
3276
3277 if (!Constraints[i].isIndirectOutput)
3278 assert(0 && "MATCH FAIL!");
3279
3280 OpNum++; // Consumes a call operand.
3281
3282 // Extend/truncate to the right pointer type if needed.
3283 MVT::ValueType PtrType = TLI.getPointerTy();
3284 if (InOperandVal.getValueType() < PtrType)
3285 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3286 else if (InOperandVal.getValueType() > PtrType)
3287 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3288
3289 // Add information to the INLINEASM node to know about this output.
3290 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3291 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3292 AsmNodeOperands.push_back(InOperandVal);
3293 break;
3294 }
3295
3296 // Otherwise, this is a register output.
3297 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3298
Chris Lattner864635a2006-02-22 22:37:12 +00003299 // If this is an early-clobber output, or if there is an input
3300 // constraint that matches this, we need to reserve the input register
3301 // so no other inputs allocate to it.
3302 bool UsesInputRegister = false;
3303 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3304 UsesInputRegister = true;
3305
3306 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003307 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00003308 RegsForValue Regs =
3309 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3310 true, UsesInputRegister,
3311 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00003312 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003313 cerr << "Couldn't allocate output reg for contraint '"
3314 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003315 exit(1);
3316 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003317
Chris Lattner2cc2f662006-02-01 01:28:23 +00003318 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00003319 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003320 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003321 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00003322 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003323 } else {
Chris Lattner22873462006-02-27 23:45:39 +00003324 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3325 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003326 OpNum++; // Consumes a call operand.
3327 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003328
3329 // Add information to the INLINEASM node to know that this register is
3330 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003331 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003332 break;
3333 }
3334 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00003335 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00003336 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00003337
Chris Lattner2223aea2006-02-02 00:25:23 +00003338 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3339 // If this is required to match an output register we have already set,
3340 // just use its register.
3341 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003342
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003343 // Scan until we find the definition we already emitted of this operand.
3344 // When we find it, create a RegsForValue operand.
3345 unsigned CurOp = 2; // The first operand.
3346 for (; OperandNo; --OperandNo) {
3347 // Advance to the next operand.
3348 unsigned NumOps =
3349 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003350 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3351 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003352 "Skipped past definitions?");
3353 CurOp += (NumOps>>3)+1;
3354 }
3355
3356 unsigned NumOps =
3357 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003358 if ((NumOps & 7) == 2 /*REGDEF*/) {
3359 // Add NumOps>>3 registers to MatchedRegs.
3360 RegsForValue MatchedRegs;
3361 MatchedRegs.ValueVT = InOperandVal.getValueType();
3362 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3363 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3364 unsigned Reg =
3365 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3366 MatchedRegs.Regs.push_back(Reg);
3367 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003368
Chris Lattner527fae12007-02-01 01:21:12 +00003369 // Use the produced MatchedRegs object to
3370 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3371 TLI.getPointerTy());
3372 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3373 break;
3374 } else {
3375 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3376 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003377 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003378 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003379
3380 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3381 if (ConstraintCode.size() == 1) // not a physreg name.
Chris Lattner4234f572007-03-25 02:14:49 +00003382 CTy = TLI.getConstraintType(ConstraintCode);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003383
3384 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00003385 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3386 ConstraintCode[0], DAG);
3387 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00003388 cerr << "Invalid operand for inline asm constraint '"
3389 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003390 exit(1);
3391 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003392
3393 // Add information to the INLINEASM node to know about this input.
3394 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3395 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3396 AsmNodeOperands.push_back(InOperandVal);
3397 break;
3398 } else if (CTy == TargetLowering::C_Memory) {
3399 // Memory input.
3400
Chris Lattner6dfc6802007-03-08 22:29:47 +00003401 // If the operand is a float, spill to a constant pool entry to get its
3402 // address.
3403 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3404 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3405
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003406 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattner6dfc6802007-03-08 22:29:47 +00003407 cerr << "Match failed, cannot handle this yet!\n";
3408 InOperandVal.Val->dump();
Chris Lattnerb4ddac92007-03-08 07:07:03 +00003409 exit(1);
3410 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003411
3412 // Extend/truncate to the right pointer type if needed.
3413 MVT::ValueType PtrType = TLI.getPointerTy();
3414 if (InOperandVal.getValueType() < PtrType)
3415 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3416 else if (InOperandVal.getValueType() > PtrType)
3417 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3418
3419 // Add information to the INLINEASM node to know about this input.
3420 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3421 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3422 AsmNodeOperands.push_back(InOperandVal);
3423 break;
3424 }
3425
3426 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3427
3428 // Copy the input into the appropriate registers.
3429 RegsForValue InRegs =
3430 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3431 false, true, OutputRegs, InputRegs);
3432 // FIXME: should be match fail.
3433 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3434
Evan Chenga8441262006-06-15 08:11:54 +00003435 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003436
3437 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003438 break;
3439 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003440 case InlineAsm::isClobber: {
3441 RegsForValue ClobberedRegs =
3442 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3443 OutputRegs, InputRegs);
3444 // Add the clobbered value to the operand list, so that the register
3445 // allocator is aware that the physreg got clobbered.
3446 if (!ClobberedRegs.Regs.empty())
3447 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003448 break;
3449 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003450 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003451 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003452
3453 // Finish up input operands.
3454 AsmNodeOperands[0] = Chain;
3455 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3456
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003457 Chain = DAG.getNode(ISD::INLINEASM,
3458 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003459 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003460 Flag = Chain.getValue(1);
3461
Chris Lattner6656dd12006-01-31 02:03:41 +00003462 // If this asm returns a register value, copy the result from that register
3463 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003464 if (!RetValRegs.Regs.empty()) {
3465 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3466
3467 // If the result of the inline asm is a vector, it may have the wrong
3468 // width/num elts. Make sure to convert it to the right type with
3469 // vbit_convert.
3470 if (Val.getValueType() == MVT::Vector) {
3471 const VectorType *VTy = cast<VectorType>(I.getType());
3472 unsigned DesiredNumElts = VTy->getNumElements();
3473 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3474
3475 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3476 DAG.getConstant(DesiredNumElts, MVT::i32),
3477 DAG.getValueType(DesiredEltVT));
3478 }
3479
3480 setValue(&I, Val);
3481 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003482
Chris Lattner6656dd12006-01-31 02:03:41 +00003483 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3484
3485 // Process indirect outputs, first output all of the flagged copies out of
3486 // physregs.
3487 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003488 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003489 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00003490 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3491 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003492 }
3493
3494 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003495 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003496 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00003497 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003498 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003499 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003500 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003501 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3502 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003503 DAG.setRoot(Chain);
3504}
3505
3506
Chris Lattner1c08c712005-01-07 07:47:53 +00003507void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3508 SDOperand Src = getValue(I.getOperand(0));
3509
3510 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003511
3512 if (IntPtr < Src.getValueType())
3513 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3514 else if (IntPtr > Src.getValueType())
3515 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003516
3517 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003518 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003519 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3520 Src, getIntPtrConstant(ElementSize));
3521
Reid Spencer47857812006-12-31 05:55:36 +00003522 TargetLowering::ArgListTy Args;
3523 TargetLowering::ArgListEntry Entry;
3524 Entry.Node = Src;
3525 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003526 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003527
3528 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003529 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003530 DAG.getExternalSymbol("malloc", IntPtr),
3531 Args, DAG);
3532 setValue(&I, Result.first); // Pointers always fit in registers
3533 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003534}
3535
3536void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003537 TargetLowering::ArgListTy Args;
3538 TargetLowering::ArgListEntry Entry;
3539 Entry.Node = getValue(I.getOperand(0));
3540 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003541 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003542 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003543 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003544 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003545 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3546 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003547}
3548
Chris Lattner025c39b2005-08-26 20:54:47 +00003549// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3550// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3551// instructions are special in various ways, which require special support to
3552// insert. The specified MachineInstr is created but not inserted into any
3553// basic blocks, and the scheduler passes ownership of it to this method.
3554MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3555 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003556 cerr << "If a target marks an instruction with "
3557 << "'usesCustomDAGSchedInserter', it must implement "
3558 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003559 abort();
3560 return 0;
3561}
3562
Chris Lattner39ae3622005-01-09 00:00:49 +00003563void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003564 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3565 getValue(I.getOperand(1)),
3566 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003567}
3568
3569void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003570 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3571 getValue(I.getOperand(0)),
3572 DAG.getSrcValue(I.getOperand(0)));
3573 setValue(&I, V);
3574 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003575}
3576
3577void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003578 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3579 getValue(I.getOperand(1)),
3580 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003581}
3582
3583void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003584 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3585 getValue(I.getOperand(1)),
3586 getValue(I.getOperand(2)),
3587 DAG.getSrcValue(I.getOperand(1)),
3588 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003589}
3590
Evan Chengb15974a2006-12-12 07:27:38 +00003591/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3592/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3593static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3594 unsigned &i, SelectionDAG &DAG,
3595 TargetLowering &TLI) {
3596 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3597 return SDOperand(Arg, i++);
3598
3599 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3600 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3601 if (NumVals == 1) {
3602 return DAG.getNode(ISD::BIT_CONVERT, VT,
3603 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3604 } else if (NumVals == 2) {
3605 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3606 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3607 if (!TLI.isLittleEndian())
3608 std::swap(Lo, Hi);
3609 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3610 } else {
3611 // Value scalarized into many values. Unimp for now.
3612 assert(0 && "Cannot expand i64 -> i16 yet!");
3613 }
3614 return SDOperand();
3615}
3616
Chris Lattnerfdfded52006-04-12 16:20:43 +00003617/// TargetLowering::LowerArguments - This is the default LowerArguments
3618/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003619/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3620/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003621std::vector<SDOperand>
3622TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003623 const FunctionType *FTy = F.getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +00003624 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003625 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3626 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003627 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003628 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3629 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3630
3631 // Add one result value for each formal argument.
3632 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003633 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003634 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3635 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003636 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003637 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003638 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003639 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003640
Chris Lattnerddf53e42007-02-26 02:56:58 +00003641 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3642 // that is zero extended!
Reid Spencer18da0722007-04-11 02:44:20 +00003643 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003644 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer18da0722007-04-11 02:44:20 +00003645 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003646 Flags |= ISD::ParamFlags::SExt;
Reid Spencer18da0722007-04-11 02:44:20 +00003647 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003648 Flags |= ISD::ParamFlags::InReg;
Reid Spencer18da0722007-04-11 02:44:20 +00003649 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003650 Flags |= ISD::ParamFlags::StructReturn;
3651 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003652
Chris Lattnerfdfded52006-04-12 16:20:43 +00003653 switch (getTypeAction(VT)) {
3654 default: assert(0 && "Unknown type action!");
3655 case Legal:
3656 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003657 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003658 break;
3659 case Promote:
3660 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003661 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003662 break;
3663 case Expand:
3664 if (VT != MVT::Vector) {
3665 // If this is a large integer, it needs to be broken up into small
3666 // integers. Figure out what the destination type is and how many small
3667 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003668 MVT::ValueType NVT = getTypeToExpandTo(VT);
3669 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003670 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003671 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003672 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003673 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003674 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3675 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003676 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3677 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003678 } else {
3679 // Otherwise, this is a vector type. We only support legal vectors
3680 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003681 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3682 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003683
Chris Lattnerfdfded52006-04-12 16:20:43 +00003684 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003685 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003686 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3687 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3688 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003689 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003690 } else {
3691 assert(0 && "Don't support illegal by-val vector arguments yet!");
3692 }
3693 }
3694 break;
3695 }
3696 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003697
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003698 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003699
3700 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003701 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3702 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003703 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003704
3705 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003706
3707 // Set up the return result vector.
3708 Ops.clear();
3709 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003710 unsigned Idx = 1;
3711 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3712 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003713 MVT::ValueType VT = getValueType(I->getType());
3714
3715 switch (getTypeAction(VT)) {
3716 default: assert(0 && "Unknown type action!");
3717 case Legal:
3718 Ops.push_back(SDOperand(Result, i++));
3719 break;
3720 case Promote: {
3721 SDOperand Op(Result, i++);
3722 if (MVT::isInteger(VT)) {
Reid Spencer18da0722007-04-11 02:44:20 +00003723 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003724 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3725 DAG.getValueType(VT));
Reid Spencer18da0722007-04-11 02:44:20 +00003726 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003727 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3728 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003729 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3730 } else {
3731 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3732 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3733 }
3734 Ops.push_back(Op);
3735 break;
3736 }
3737 case Expand:
3738 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003739 // If this is a large integer or a floating point node that needs to be
3740 // expanded, it needs to be reassembled from small integers. Figure out
3741 // what the source elt type is and how many small integers it is.
3742 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003743 } else {
3744 // Otherwise, this is a vector type. We only support legal vectors
3745 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003746 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003747 unsigned NumElems = PTy->getNumElements();
3748 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003749
Chris Lattnerfdfded52006-04-12 16:20:43 +00003750 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003751 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003752 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003753 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003754 SDOperand N = SDOperand(Result, i++);
3755 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003756 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3757 DAG.getConstant(NumElems, MVT::i32),
3758 DAG.getValueType(getValueType(EltTy)));
3759 Ops.push_back(N);
3760 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003761 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003762 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003763 }
3764 }
3765 break;
3766 }
3767 }
3768 return Ops;
3769}
3770
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003771
Evan Chengb15974a2006-12-12 07:27:38 +00003772/// ExpandScalarCallArgs - Recursively expand call argument node by
3773/// bit_converting it or extract a pair of elements from the larger node.
3774static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003775 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003776 SmallVector<SDOperand, 32> &Ops,
3777 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003778 TargetLowering &TLI,
3779 bool isFirst = true) {
3780
Evan Chengb15974a2006-12-12 07:27:38 +00003781 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003782 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003783 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003784 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3785 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003786 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003787 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003788 return;
3789 }
3790
3791 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3792 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3793 if (NumVals == 1) {
3794 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003795 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003796 } else if (NumVals == 2) {
3797 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3798 DAG.getConstant(0, TLI.getPointerTy()));
3799 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3800 DAG.getConstant(1, TLI.getPointerTy()));
3801 if (!TLI.isLittleEndian())
3802 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003803 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3804 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003805 } else {
3806 // Value scalarized into many values. Unimp for now.
3807 assert(0 && "Cannot expand i64 -> i16 yet!");
3808 }
3809}
3810
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003811/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3812/// implementation, which just inserts an ISD::CALL node, which is later custom
3813/// lowered by the target to something concrete. FIXME: When all targets are
3814/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3815std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003816TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3817 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003818 unsigned CallingConv, bool isTailCall,
3819 SDOperand Callee,
3820 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003821 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003822 Ops.push_back(Chain); // Op#0 - Chain
3823 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3824 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3825 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3826 Ops.push_back(Callee);
3827
3828 // Handle all of the outgoing arguments.
3829 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003830 MVT::ValueType VT = getValueType(Args[i].Ty);
3831 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003832 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003833 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003834 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003835
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003836 if (Args[i].isSExt)
3837 Flags |= ISD::ParamFlags::SExt;
3838 if (Args[i].isZExt)
3839 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003840 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003841 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003842 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003843 Flags |= ISD::ParamFlags::StructReturn;
3844 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003845
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003846 switch (getTypeAction(VT)) {
3847 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003848 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003849 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003850 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003851 break;
3852 case Promote:
3853 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003854 unsigned ExtOp;
3855 if (Args[i].isSExt)
3856 ExtOp = ISD::SIGN_EXTEND;
3857 else if (Args[i].isZExt)
3858 ExtOp = ISD::ZERO_EXTEND;
3859 else
3860 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003861 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3862 } else {
3863 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3864 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3865 }
3866 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003867 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003868 break;
3869 case Expand:
3870 if (VT != MVT::Vector) {
3871 // If this is a large integer, it needs to be broken down into small
3872 // integers. Figure out what the source elt type is and how many small
3873 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003874 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003875 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003876 // Otherwise, this is a vector type. We only support legal vectors
3877 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003878 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003879 unsigned NumElems = PTy->getNumElements();
3880 const Type *EltTy = PTy->getElementType();
3881
3882 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003883 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003884 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003885 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003886 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003887 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3888 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003889 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003890 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003891 assert(0 && "Don't support illegal by-val vector call args yet!");
3892 abort();
3893 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003894 }
3895 break;
3896 }
3897 }
3898
3899 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003900 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003901
3902 if (RetTy != Type::VoidTy) {
3903 MVT::ValueType VT = getValueType(RetTy);
3904 switch (getTypeAction(VT)) {
3905 default: assert(0 && "Unknown type action!");
3906 case Legal:
3907 RetTys.push_back(VT);
3908 break;
3909 case Promote:
3910 RetTys.push_back(getTypeToTransformTo(VT));
3911 break;
3912 case Expand:
3913 if (VT != MVT::Vector) {
3914 // If this is a large integer, it needs to be reassembled from small
3915 // integers. Figure out what the source elt type is and how many small
3916 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003917 MVT::ValueType NVT = getTypeToExpandTo(VT);
3918 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003919 for (unsigned i = 0; i != NumVals; ++i)
3920 RetTys.push_back(NVT);
3921 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003922 // Otherwise, this is a vector type. We only support legal vectors
3923 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003924 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003925 unsigned NumElems = PTy->getNumElements();
3926 const Type *EltTy = PTy->getElementType();
3927
3928 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003929 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003930 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3931 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3932 RetTys.push_back(TVT);
3933 } else {
3934 assert(0 && "Don't support illegal by-val vector call results yet!");
3935 abort();
3936 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003937 }
3938 }
3939 }
3940
3941 RetTys.push_back(MVT::Other); // Always has a chain.
3942
3943 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003944 SDOperand Res = DAG.getNode(ISD::CALL,
3945 DAG.getVTList(&RetTys[0], RetTys.size()),
3946 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003947
3948 // This returns a pair of operands. The first element is the
3949 // return value for the function (if RetTy is not VoidTy). The second
3950 // element is the outgoing token chain.
3951 SDOperand ResVal;
3952 if (RetTys.size() != 1) {
3953 MVT::ValueType VT = getValueType(RetTy);
3954 if (RetTys.size() == 2) {
3955 ResVal = Res;
3956
3957 // If this value was promoted, truncate it down.
3958 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003959 if (VT == MVT::Vector) {
Chris Lattner5df99b32007-03-25 05:00:54 +00003960 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerda098e72006-05-16 23:39:44 +00003961 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003962 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3963 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003964
3965 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003966 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003967 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003968 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003969 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3970 // "N x PTyElementVT" MVT::Vector type.
3971 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003972 DAG.getConstant(NumElems, MVT::i32),
3973 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003974 } else {
3975 abort();
3976 }
3977 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003978 unsigned AssertOp = ISD::AssertSext;
3979 if (!RetTyIsSigned)
3980 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003981 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3982 DAG.getValueType(VT));
3983 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3984 } else {
3985 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003986 if (getTypeAction(VT) == Expand)
3987 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3988 else
3989 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003990 }
3991 }
3992 } else if (RetTys.size() == 3) {
3993 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3994 Res.getValue(0), Res.getValue(1));
3995
3996 } else {
3997 assert(0 && "Case not handled yet!");
3998 }
3999 }
4000
4001 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4002}
4003
Chris Lattner50381b62005-05-14 05:50:48 +00004004SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004005 assert(0 && "LowerOperation not implemented for this target!");
4006 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004007 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004008}
4009
Nate Begeman0aed7842006-01-28 03:14:31 +00004010SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4011 SelectionDAG &DAG) {
4012 assert(0 && "CustomPromoteOperation not implemented for this target!");
4013 abort();
4014 return SDOperand();
4015}
4016
Evan Cheng74d0aa92006-02-15 21:59:04 +00004017/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004018/// operand.
4019static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004020 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004021 MVT::ValueType CurVT = VT;
4022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4023 uint64_t Val = C->getValue() & 255;
4024 unsigned Shift = 8;
4025 while (CurVT != MVT::i8) {
4026 Val = (Val << Shift) | Val;
4027 Shift <<= 1;
4028 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004029 }
4030 return DAG.getConstant(Val, VT);
4031 } else {
4032 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4033 unsigned Shift = 8;
4034 while (CurVT != MVT::i8) {
4035 Value =
4036 DAG.getNode(ISD::OR, VT,
4037 DAG.getNode(ISD::SHL, VT, Value,
4038 DAG.getConstant(Shift, MVT::i8)), Value);
4039 Shift <<= 1;
4040 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004041 }
4042
4043 return Value;
4044 }
4045}
4046
Evan Cheng74d0aa92006-02-15 21:59:04 +00004047/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4048/// used when a memcpy is turned into a memset when the source is a constant
4049/// string ptr.
4050static SDOperand getMemsetStringVal(MVT::ValueType VT,
4051 SelectionDAG &DAG, TargetLowering &TLI,
4052 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004053 uint64_t Val = 0;
4054 unsigned MSB = getSizeInBits(VT) / 8;
4055 if (TLI.isLittleEndian())
4056 Offset = Offset + MSB - 1;
4057 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004058 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004059 Offset += TLI.isLittleEndian() ? -1 : 1;
4060 }
4061 return DAG.getConstant(Val, VT);
4062}
4063
Evan Cheng1db92f92006-02-14 08:22:34 +00004064/// getMemBasePlusOffset - Returns base and offset node for the
4065static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4066 SelectionDAG &DAG, TargetLowering &TLI) {
4067 MVT::ValueType VT = Base.getValueType();
4068 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4069}
4070
Evan Chengc4f8eee2006-02-14 20:12:38 +00004071/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004072/// to replace the memset / memcpy is below the threshold. It also returns the
4073/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004074static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4075 unsigned Limit, uint64_t Size,
4076 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004077 MVT::ValueType VT;
4078
4079 if (TLI.allowsUnalignedMemoryAccesses()) {
4080 VT = MVT::i64;
4081 } else {
4082 switch (Align & 7) {
4083 case 0:
4084 VT = MVT::i64;
4085 break;
4086 case 4:
4087 VT = MVT::i32;
4088 break;
4089 case 2:
4090 VT = MVT::i16;
4091 break;
4092 default:
4093 VT = MVT::i8;
4094 break;
4095 }
4096 }
4097
Evan Cheng80e89d72006-02-14 09:11:59 +00004098 MVT::ValueType LVT = MVT::i64;
4099 while (!TLI.isTypeLegal(LVT))
4100 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4101 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004102
Evan Cheng80e89d72006-02-14 09:11:59 +00004103 if (VT > LVT)
4104 VT = LVT;
4105
Evan Chengdea72452006-02-14 23:05:54 +00004106 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004107 while (Size != 0) {
4108 unsigned VTSize = getSizeInBits(VT) / 8;
4109 while (VTSize > Size) {
4110 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004111 VTSize >>= 1;
4112 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004113 assert(MVT::isInteger(VT));
4114
4115 if (++NumMemOps > Limit)
4116 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004117 MemOps.push_back(VT);
4118 Size -= VTSize;
4119 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004120
4121 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004122}
4123
Chris Lattner7041ee32005-01-11 05:56:49 +00004124void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004125 SDOperand Op1 = getValue(I.getOperand(1));
4126 SDOperand Op2 = getValue(I.getOperand(2));
4127 SDOperand Op3 = getValue(I.getOperand(3));
4128 SDOperand Op4 = getValue(I.getOperand(4));
4129 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4130 if (Align == 0) Align = 1;
4131
4132 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4133 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004134
4135 // Expand memset / memcpy to a series of load / store ops
4136 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004137 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004138 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004139 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004140 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004141 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4142 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004143 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004144 unsigned Offset = 0;
4145 for (unsigned i = 0; i < NumMemOps; i++) {
4146 MVT::ValueType VT = MemOps[i];
4147 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004148 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004149 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004150 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004151 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004152 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004153 Offset += VTSize;
4154 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004155 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004156 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004157 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004158 case ISD::MEMCPY: {
4159 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4160 Size->getValue(), Align, TLI)) {
4161 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004162 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004163 GlobalAddressSDNode *G = NULL;
4164 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004165 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004166
4167 if (Op2.getOpcode() == ISD::GlobalAddress)
4168 G = cast<GlobalAddressSDNode>(Op2);
4169 else if (Op2.getOpcode() == ISD::ADD &&
4170 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4171 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4172 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004173 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004174 }
4175 if (G) {
4176 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004177 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004178 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004179 if (!Str.empty()) {
4180 CopyFromStr = true;
4181 SrcOff += SrcDelta;
4182 }
4183 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004184 }
4185
Evan Chengc080d6f2006-02-15 01:54:51 +00004186 for (unsigned i = 0; i < NumMemOps; i++) {
4187 MVT::ValueType VT = MemOps[i];
4188 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004189 SDOperand Value, Chain, Store;
4190
Evan Chengcffbb512006-02-16 23:11:42 +00004191 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004192 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4193 Chain = getRoot();
4194 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004195 DAG.getStore(Chain, Value,
4196 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004197 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004198 } else {
4199 Value = DAG.getLoad(VT, getRoot(),
4200 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00004201 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004202 Chain = Value.getValue(1);
4203 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004204 DAG.getStore(Chain, Value,
4205 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004206 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004207 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004208 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004209 SrcOff += VTSize;
4210 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004211 }
4212 }
4213 break;
4214 }
4215 }
4216
4217 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004218 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4219 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004220 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004221 }
4222 }
4223
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004224 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00004225}
4226
Chris Lattner7041ee32005-01-11 05:56:49 +00004227//===----------------------------------------------------------------------===//
4228// SelectionDAGISel code
4229//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004230
4231unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4232 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4233}
4234
Chris Lattner495a0b52005-08-17 06:37:43 +00004235void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004236 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004237 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004238}
Chris Lattner1c08c712005-01-07 07:47:53 +00004239
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004240
Chris Lattnerbad7f482006-10-28 19:22:10 +00004241
Chris Lattner1c08c712005-01-07 07:47:53 +00004242bool SelectionDAGISel::runOnFunction(Function &Fn) {
4243 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4244 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004245 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004246
4247 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4248
4249 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4250 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004251
Evan Chengad2070c2007-02-10 02:43:39 +00004252 // Add function live-ins to entry block live-in set.
4253 BasicBlock *EntryBB = &Fn.getEntryBlock();
4254 BB = FuncInfo.MBBMap[EntryBB];
4255 if (!MF.livein_empty())
4256 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4257 E = MF.livein_end(); I != E; ++I)
4258 BB->addLiveIn(I->first);
4259
Chris Lattner1c08c712005-01-07 07:47:53 +00004260 return true;
4261}
4262
Chris Lattner571e4342006-10-27 21:36:01 +00004263SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4264 unsigned Reg) {
4265 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004266 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004267 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004268 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004269
4270 // If this type is not legal, we must make sure to not create an invalid
4271 // register use.
4272 MVT::ValueType SrcVT = Op.getValueType();
4273 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004274 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004275 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004276 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004277 // Handle copies from generic vectors to registers.
4278 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004279 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004280 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004281
Chris Lattner70c2a612006-03-31 02:06:56 +00004282 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4283 // MVT::Vector type.
4284 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4285 DAG.getConstant(NE, MVT::i32),
4286 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004287
Chris Lattner70c2a612006-03-31 02:06:56 +00004288 // Loop over all of the elements of the resultant vector,
4289 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4290 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004291 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004292 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004293 for (unsigned i = 0; i != NE; ++i) {
4294 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004295 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004296 if (PTyElementVT == PTyLegalElementVT) {
4297 // Elements are legal.
4298 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4299 } else if (PTyLegalElementVT > PTyElementVT) {
4300 // Elements are promoted.
4301 if (MVT::isFloatingPoint(PTyLegalElementVT))
4302 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4303 else
4304 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4305 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4306 } else {
4307 // Elements are expanded.
4308 // The src value is expanded into multiple registers.
4309 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004310 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004311 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004312 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004313 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4314 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4315 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004316 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004317 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4318 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004319 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004320 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004321 if (MVT::isFloatingPoint(SrcVT))
4322 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4323 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004324 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004325 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004326 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004327 DestVT = TLI.getTypeToExpandTo(SrcVT);
4328 unsigned NumVals = TLI.getNumElements(SrcVT);
4329 if (NumVals == 1)
4330 return DAG.getCopyToReg(getRoot(), Reg,
4331 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4332 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004333 // The src value is expanded into multiple registers.
4334 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004335 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004336 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004337 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004338 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004339 return DAG.getCopyToReg(Op, Reg+1, Hi);
4340 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004341}
4342
Chris Lattner068a81e2005-01-17 17:15:02 +00004343void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004344LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004345 std::vector<SDOperand> &UnorderedChains) {
4346 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004347 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004348 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004349 SDOperand OldRoot = SDL.DAG.getRoot();
4350 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004351
Chris Lattnerbf209482005-10-30 19:42:35 +00004352 unsigned a = 0;
4353 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4354 AI != E; ++AI, ++a)
4355 if (!AI->use_empty()) {
4356 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004357
Chris Lattnerbf209482005-10-30 19:42:35 +00004358 // If this argument is live outside of the entry block, insert a copy from
4359 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004360 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4361 if (VMI != FuncInfo.ValueMap.end()) {
4362 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004363 UnorderedChains.push_back(Copy);
4364 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004365 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004366
Chris Lattnerbf209482005-10-30 19:42:35 +00004367 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004368 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004369 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004370}
4371
Chris Lattner1c08c712005-01-07 07:47:53 +00004372void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4373 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004374 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004375 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004376
4377 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004378
Chris Lattnerbf209482005-10-30 19:42:35 +00004379 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004380 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004381 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004382
4383 BB = FuncInfo.MBBMap[LLVMBB];
4384 SDL.setCurrentBasicBlock(BB);
4385
4386 // Lower all of the non-terminator instructions.
4387 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4388 I != E; ++I)
4389 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004390
4391 // Lower call part of invoke.
4392 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4393 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004394
Chris Lattner1c08c712005-01-07 07:47:53 +00004395 // Ensure that all instructions which are used outside of their defining
4396 // blocks are available as virtual registers.
4397 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004398 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004399 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004400 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004401 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004402 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004403 }
4404
4405 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4406 // ensure constants are generated when needed. Remember the virtual registers
4407 // that need to be added to the Machine PHI nodes as input. We cannot just
4408 // directly add them, because expansion might result in multiple MBB's for one
4409 // BB. As such, the start of the BB might correspond to a different MBB than
4410 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004411 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004412 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004413
4414 // Emit constants only once even if used by multiple PHI nodes.
4415 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004416
Chris Lattner8c494ab2006-10-27 23:50:33 +00004417 // Vector bool would be better, but vector<bool> is really slow.
4418 std::vector<unsigned char> SuccsHandled;
4419 if (TI->getNumSuccessors())
4420 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4421
Chris Lattner1c08c712005-01-07 07:47:53 +00004422 // Check successor nodes PHI nodes that expect a constant to be available from
4423 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004424 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4425 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004426 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004427 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004428
Chris Lattner8c494ab2006-10-27 23:50:33 +00004429 // If this terminator has multiple identical successors (common for
4430 // switches), only handle each succ once.
4431 unsigned SuccMBBNo = SuccMBB->getNumber();
4432 if (SuccsHandled[SuccMBBNo]) continue;
4433 SuccsHandled[SuccMBBNo] = true;
4434
4435 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004436 PHINode *PN;
4437
4438 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4439 // nodes and Machine PHI nodes, but the incoming operands have not been
4440 // emitted yet.
4441 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004442 (PN = dyn_cast<PHINode>(I)); ++I) {
4443 // Ignore dead phi's.
4444 if (PN->use_empty()) continue;
4445
4446 unsigned Reg;
4447 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004448
Chris Lattner8c494ab2006-10-27 23:50:33 +00004449 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4450 unsigned &RegOut = ConstantsOut[C];
4451 if (RegOut == 0) {
4452 RegOut = FuncInfo.CreateRegForValue(C);
4453 UnorderedChains.push_back(
4454 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004455 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004456 Reg = RegOut;
4457 } else {
4458 Reg = FuncInfo.ValueMap[PHIOp];
4459 if (Reg == 0) {
4460 assert(isa<AllocaInst>(PHIOp) &&
4461 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4462 "Didn't codegen value into a register!??");
4463 Reg = FuncInfo.CreateRegForValue(PHIOp);
4464 UnorderedChains.push_back(
4465 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004466 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004467 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004468
4469 // Remember that this register needs to added to the machine PHI node as
4470 // the input for this MBB.
4471 MVT::ValueType VT = TLI.getValueType(PN->getType());
4472 unsigned NumElements;
4473 if (VT != MVT::Vector)
4474 NumElements = TLI.getNumElements(VT);
4475 else {
4476 MVT::ValueType VT1,VT2;
4477 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004478 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004479 VT1, VT2);
4480 }
4481 for (unsigned i = 0, e = NumElements; i != e; ++i)
4482 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4483 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004484 }
4485 ConstantsOut.clear();
4486
Chris Lattnerddb870b2005-01-13 17:59:43 +00004487 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004488 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004489 SDOperand Root = SDL.getRoot();
4490 if (Root.getOpcode() != ISD::EntryToken) {
4491 unsigned i = 0, e = UnorderedChains.size();
4492 for (; i != e; ++i) {
4493 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4494 if (UnorderedChains[i].Val->getOperand(0) == Root)
4495 break; // Don't add the root if we already indirectly depend on it.
4496 }
4497
4498 if (i == e)
4499 UnorderedChains.push_back(Root);
4500 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004501 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4502 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004503 }
4504
Chris Lattner1c08c712005-01-07 07:47:53 +00004505 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004506 if (Invoke) {
4507 // Just the branch part of invoke.
4508 SDL.visitInvoke(*Invoke, true);
4509 } else {
4510 SDL.visit(*LLVMBB->getTerminator());
4511 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004512
Nate Begemanf15485a2006-03-27 01:32:24 +00004513 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004514 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004515 SwitchCases.clear();
4516 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004517 JTCases.clear();
4518 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004519 BitTestCases.clear();
4520 BitTestCases = SDL.BitTestCases;
4521
Chris Lattnera651cf62005-01-17 19:43:36 +00004522 // Make sure the root of the DAG is up-to-date.
4523 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004524}
4525
Nate Begemanf15485a2006-03-27 01:32:24 +00004526void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004527 // Get alias analysis for load/store combining.
4528 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4529
Chris Lattneraf21d552005-10-10 16:47:10 +00004530 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004531 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004532
Bill Wendling832171c2006-12-07 20:04:42 +00004533 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004534 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004535
Chris Lattner1c08c712005-01-07 07:47:53 +00004536 // Second step, hack on the DAG until it only uses operations and types that
4537 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004538 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004539
Bill Wendling832171c2006-12-07 20:04:42 +00004540 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004541 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004542
Chris Lattneraf21d552005-10-10 16:47:10 +00004543 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004544 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004545
Evan Chenga9c20912006-01-21 02:32:06 +00004546 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004547
Chris Lattnera33ef482005-03-30 01:10:47 +00004548 // Third, instruction select all of the operations to machine code, adding the
4549 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004550 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004551
Bill Wendling832171c2006-12-07 20:04:42 +00004552 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004553 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004554}
Chris Lattner1c08c712005-01-07 07:47:53 +00004555
Nate Begemanf15485a2006-03-27 01:32:24 +00004556void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4557 FunctionLoweringInfo &FuncInfo) {
4558 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4559 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004560 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004561 CurDAG = &DAG;
4562
4563 // First step, lower LLVM code to some DAG. This DAG may use operations and
4564 // types that are not supported by the target.
4565 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4566
4567 // Second step, emit the lowered DAG as machine code.
4568 CodeGenAndEmitDAG(DAG);
4569 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004570
4571 DOUT << "Total amount of phi nodes to update: "
4572 << PHINodesToUpdate.size() << "\n";
4573 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4574 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4575 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004576
Chris Lattnera33ef482005-03-30 01:10:47 +00004577 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004578 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004579 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004580 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4581 MachineInstr *PHI = PHINodesToUpdate[i].first;
4582 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4583 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004584 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004585 PHI->addMachineBasicBlockOperand(BB);
4586 }
4587 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004588 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004589
4590 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4591 // Lower header first, if it wasn't already lowered
4592 if (!BitTestCases[i].Emitted) {
4593 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4594 CurDAG = &HSDAG;
4595 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4596 // Set the current basic block to the mbb we wish to insert the code into
4597 BB = BitTestCases[i].Parent;
4598 HSDL.setCurrentBasicBlock(BB);
4599 // Emit the code
4600 HSDL.visitBitTestHeader(BitTestCases[i]);
4601 HSDAG.setRoot(HSDL.getRoot());
4602 CodeGenAndEmitDAG(HSDAG);
4603 }
4604
4605 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4606 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4607 CurDAG = &BSDAG;
4608 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4609 // Set the current basic block to the mbb we wish to insert the code into
4610 BB = BitTestCases[i].Cases[j].ThisBB;
4611 BSDL.setCurrentBasicBlock(BB);
4612 // Emit the code
4613 if (j+1 != ej)
4614 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4615 BitTestCases[i].Reg,
4616 BitTestCases[i].Cases[j]);
4617 else
4618 BSDL.visitBitTestCase(BitTestCases[i].Default,
4619 BitTestCases[i].Reg,
4620 BitTestCases[i].Cases[j]);
4621
4622
4623 BSDAG.setRoot(BSDL.getRoot());
4624 CodeGenAndEmitDAG(BSDAG);
4625 }
4626
4627 // Update PHI Nodes
4628 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4629 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4630 MachineBasicBlock *PHIBB = PHI->getParent();
4631 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4632 "This is not a machine PHI node that we are updating!");
4633 // This is "default" BB. We have two jumps to it. From "header" BB and
4634 // from last "case" BB.
4635 if (PHIBB == BitTestCases[i].Default) {
4636 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4637 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikov8085bcf2007-04-13 06:53:51 +00004638 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004639 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4640 }
4641 // One of "cases" BB.
4642 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4643 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4644 if (cBB->succ_end() !=
4645 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4646 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4647 PHI->addMachineBasicBlockOperand(cBB);
4648 }
4649 }
4650 }
4651 }
4652
Nate Begeman9453eea2006-04-23 06:26:20 +00004653 // If the JumpTable record is filled in, then we need to emit a jump table.
4654 // Updating the PHI nodes is tricky in this case, since we need to determine
4655 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004656 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4657 // Lower header first, if it wasn't already lowered
4658 if (!JTCases[i].first.Emitted) {
4659 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4660 CurDAG = &HSDAG;
4661 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4662 // Set the current basic block to the mbb we wish to insert the code into
4663 BB = JTCases[i].first.HeaderBB;
4664 HSDL.setCurrentBasicBlock(BB);
4665 // Emit the code
4666 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4667 HSDAG.setRoot(HSDL.getRoot());
4668 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004669 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004670
4671 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4672 CurDAG = &JSDAG;
4673 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004674 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004675 BB = JTCases[i].second.MBB;
4676 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004677 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004678 JSDL.visitJumpTable(JTCases[i].second);
4679 JSDAG.setRoot(JSDL.getRoot());
4680 CodeGenAndEmitDAG(JSDAG);
4681
Nate Begeman37efe672006-04-22 18:53:45 +00004682 // Update PHI Nodes
4683 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4684 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4685 MachineBasicBlock *PHIBB = PHI->getParent();
4686 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4687 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004688 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004689 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004690 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004691 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004692 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004693 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004694 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004695 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004696 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004697 }
4698 }
Nate Begeman37efe672006-04-22 18:53:45 +00004699 }
4700
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004701 // If the switch block involved a branch to one of the actual successors, we
4702 // need to update PHI nodes in that block.
4703 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4704 MachineInstr *PHI = PHINodesToUpdate[i].first;
4705 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4706 "This is not a machine PHI node that we are updating!");
4707 if (BB->isSuccessor(PHI->getParent())) {
4708 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4709 PHI->addMachineBasicBlockOperand(BB);
4710 }
4711 }
4712
Nate Begemanf15485a2006-03-27 01:32:24 +00004713 // If we generated any switch lowering information, build and codegen any
4714 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004715 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004716 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004717 CurDAG = &SDAG;
4718 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004719
Nate Begemanf15485a2006-03-27 01:32:24 +00004720 // Set the current basic block to the mbb we wish to insert the code into
4721 BB = SwitchCases[i].ThisBB;
4722 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004723
Nate Begemanf15485a2006-03-27 01:32:24 +00004724 // Emit the code
4725 SDL.visitSwitchCase(SwitchCases[i]);
4726 SDAG.setRoot(SDL.getRoot());
4727 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004728
4729 // Handle any PHI nodes in successors of this chunk, as if we were coming
4730 // from the original BB before switch expansion. Note that PHI nodes can
4731 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4732 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004733 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004734 for (MachineBasicBlock::iterator Phi = BB->begin();
4735 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4736 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4737 for (unsigned pn = 0; ; ++pn) {
4738 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4739 if (PHINodesToUpdate[pn].first == Phi) {
4740 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4741 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4742 break;
4743 }
4744 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004745 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004746
4747 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004748 if (BB == SwitchCases[i].FalseBB)
4749 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004750
4751 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004752 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004753 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004754 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004755 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004756 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004757}
Evan Chenga9c20912006-01-21 02:32:06 +00004758
Jim Laskey13ec7022006-08-01 14:21:23 +00004759
Evan Chenga9c20912006-01-21 02:32:06 +00004760//===----------------------------------------------------------------------===//
4761/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4762/// target node in the graph.
4763void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4764 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004765
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004766 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004767
4768 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004769 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004770 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004771 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004772
Jim Laskey9ff542f2006-08-01 18:29:48 +00004773 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004774 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004775 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004776}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004777
Chris Lattner03fc53c2006-03-06 00:22:00 +00004778
Jim Laskey9ff542f2006-08-01 18:29:48 +00004779HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4780 return new HazardRecognizer();
4781}
4782
Chris Lattner75548062006-10-11 03:58:02 +00004783//===----------------------------------------------------------------------===//
4784// Helper functions used by the generated instruction selector.
4785//===----------------------------------------------------------------------===//
4786// Calls to these methods are generated by tblgen.
4787
4788/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4789/// the dag combiner simplified the 255, we still want to match. RHS is the
4790/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4791/// specified in the .td file (e.g. 255).
4792bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4793 int64_t DesiredMaskS) {
4794 uint64_t ActualMask = RHS->getValue();
4795 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4796
4797 // If the actual mask exactly matches, success!
4798 if (ActualMask == DesiredMask)
4799 return true;
4800
4801 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4802 if (ActualMask & ~DesiredMask)
4803 return false;
4804
4805 // Otherwise, the DAG Combiner may have proven that the value coming in is
4806 // either already zero or is not demanded. Check for known zero input bits.
4807 uint64_t NeededMask = DesiredMask & ~ActualMask;
4808 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4809 return true;
4810
4811 // TODO: check to see if missing bits are just not demanded.
4812
4813 // Otherwise, this pattern doesn't match.
4814 return false;
4815}
4816
4817/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4818/// the dag combiner simplified the 255, we still want to match. RHS is the
4819/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4820/// specified in the .td file (e.g. 255).
4821bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4822 int64_t DesiredMaskS) {
4823 uint64_t ActualMask = RHS->getValue();
4824 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4825
4826 // If the actual mask exactly matches, success!
4827 if (ActualMask == DesiredMask)
4828 return true;
4829
4830 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4831 if (ActualMask & ~DesiredMask)
4832 return false;
4833
4834 // Otherwise, the DAG Combiner may have proven that the value coming in is
4835 // either already zero or is not demanded. Check for known zero input bits.
4836 uint64_t NeededMask = DesiredMask & ~ActualMask;
4837
4838 uint64_t KnownZero, KnownOne;
4839 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4840
4841 // If all the missing bits in the or are already known to be set, match!
4842 if ((NeededMask & KnownOne) == NeededMask)
4843 return true;
4844
4845 // TODO: check to see if missing bits are just not demanded.
4846
4847 // Otherwise, this pattern doesn't match.
4848 return false;
4849}
4850
Jim Laskey9ff542f2006-08-01 18:29:48 +00004851
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004852/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4853/// by tblgen. Others should not call it.
4854void SelectionDAGISel::
4855SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4856 std::vector<SDOperand> InOps;
4857 std::swap(InOps, Ops);
4858
4859 Ops.push_back(InOps[0]); // input chain.
4860 Ops.push_back(InOps[1]); // input asm string.
4861
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004862 unsigned i = 2, e = InOps.size();
4863 if (InOps[e-1].getValueType() == MVT::Flag)
4864 --e; // Don't process a flag operand if it is here.
4865
4866 while (i != e) {
4867 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4868 if ((Flags & 7) != 4 /*MEM*/) {
4869 // Just skip over this operand, copying the operands verbatim.
4870 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4871 i += (Flags >> 3) + 1;
4872 } else {
4873 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4874 // Otherwise, this is a memory operand. Ask the target to select it.
4875 std::vector<SDOperand> SelOps;
4876 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004877 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004878 exit(1);
4879 }
4880
4881 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00004882 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00004883 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00004884 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004885 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4886 i += 2;
4887 }
4888 }
4889
4890 // Add the flag input back if present.
4891 if (e != InOps.size())
4892 Ops.push_back(InOps.back());
4893}