blob: 3f6a10ae44f51701a98d6e91e3778fb477893536 [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 Lattnerbf996f12007-04-30 17:29:31 +000085namespace { struct AsmOperandInfo; }
86
Chris Lattner864635a2006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000135 };
136}
Evan Cheng4ef10862006-01-23 07:01:07 +0000137
Chris Lattner1c08c712005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000175 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 }
Chris Lattner571e4342006-10-27 21:36:01 +0000185
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
190 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000191
Chris Lattner3c384492006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
198 }
199 };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattnerbf209482005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000217/// entry block, return true. This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000219static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner1c08c712005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattnerbf209482005-10-30 19:42:35 +0000231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 AI != E; ++AI)
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
237
Chris Lattner1c08c712005-01-07 07:47:53 +0000238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
240 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000247 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000248 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000250
Reid Spencerb83eb642006-10-20 07:07:24 +0000251 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000252 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000254 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000255 }
256
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000257 for (; BB != EB; ++BB)
258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
260 if (!isa<AllocaInst>(I) ||
261 !StaticAllocaMap.count(cast<AllocaInst>(I)))
262 InitializeRegForValue(I);
263
264 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
265 // also creates the initial PHI MachineInstrs, though none of the input
266 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000267 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000268 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
269 MBBMap[BB] = MBB;
270 MF.getBasicBlockList().push_back(MBB);
271
272 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
273 // appropriate.
274 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000275 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
276 if (PN->use_empty()) continue;
277
278 MVT::ValueType VT = TLI.getValueType(PN->getType());
279 unsigned NumElements;
280 if (VT != MVT::Vector)
281 NumElements = TLI.getNumElements(VT);
282 else {
283 MVT::ValueType VT1,VT2;
284 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000285 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000286 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000287 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000288 unsigned PHIReg = ValueMap[PN];
289 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000290 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000291 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000292 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000293 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000294 }
295}
296
Chris Lattner3c384492006-03-16 19:51:18 +0000297/// CreateRegForValue - Allocate the appropriate number of virtual registers of
298/// the correctly promoted or expanded types. Assign these registers
299/// consecutive vreg numbers and return the first assigned number.
300unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
301 MVT::ValueType VT = TLI.getValueType(V->getType());
302
303 // The number of multiples of registers that we need, to, e.g., split up
304 // a <2 x int64> -> 4 x i32 registers.
305 unsigned NumVectorRegs = 1;
306
Reid Spencerac9dcb92007-02-15 03:39:18 +0000307 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000308 // and how many of the elements it will use.
309 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000310 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000311 unsigned NumElts = PTy->getNumElements();
312 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Bill Wendling95b39552007-04-24 21:13:23 +0000313 MVT::ValueType VecTy = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000314
315 // Divide the input until we get to a supported size. This will always
316 // end with a scalar if the target doesn't support vectors.
Bill Wendling95b39552007-04-24 21:13:23 +0000317 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner3c384492006-03-16 19:51:18 +0000318 NumElts >>= 1;
319 NumVectorRegs <<= 1;
Evan Chengc1a35202007-04-25 18:33:21 +0000320 VecTy = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000321 }
Bill Wendling95b39552007-04-24 21:13:23 +0000322
323 // Check that VecTy isn't a 1-element vector.
324 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner6cb70042006-03-16 23:05:19 +0000325 VT = EltTy;
326 else
Bill Wendling95b39552007-04-24 21:13:23 +0000327 VT = VecTy;
Chris Lattner3c384492006-03-16 19:51:18 +0000328 }
Bill Wendling95b39552007-04-24 21:13:23 +0000329
Chris Lattner3c384492006-03-16 19:51:18 +0000330 // The common case is that we will only create one register for this
331 // value. If we have that case, create and return the virtual register.
332 unsigned NV = TLI.getNumElements(VT);
333 if (NV == 1) {
334 // If we are promoting this value, pick the next largest supported type.
335 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
336 unsigned Reg = MakeReg(PromotedType);
337 // If this is a vector of supported or promoted types (e.g. 4 x i16),
338 // create all of the registers.
339 for (unsigned i = 1; i != NumVectorRegs; ++i)
340 MakeReg(PromotedType);
341 return Reg;
342 }
343
344 // If this value is represented with multiple target registers, make sure
345 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000346 VT = TLI.getTypeToExpandTo(VT);
347 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000349 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000350 return R;
351}
Chris Lattner1c08c712005-01-07 07:47:53 +0000352
353//===----------------------------------------------------------------------===//
354/// SelectionDAGLowering - This is the common target-independent lowering
355/// implementation that is parameterized by a TargetLowering object.
356/// Also, targets can overload any lowering method.
357///
358namespace llvm {
359class SelectionDAGLowering {
360 MachineBasicBlock *CurMBB;
361
Chris Lattner0da331f2007-02-04 01:31:47 +0000362 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000363
Chris Lattnerd3948112005-01-17 22:19:26 +0000364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
365 /// them up and then emit token factor nodes when possible. This allows us to
366 /// get simple disambiguation between loads without worrying about alias
367 /// analysis.
368 std::vector<SDOperand> PendingLoads;
369
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000370 /// Case - A struct to record the Value for a switch case, and the
371 /// case's target basic block.
372 struct Case {
373 Constant* Low;
374 Constant* High;
375 MachineBasicBlock* BB;
376
377 Case() : Low(0), High(0), BB(0) { }
378 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
379 Low(low), High(high), BB(bb) { }
380 uint64_t size() const {
381 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
382 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
383 return (rHigh - rLow + 1ULL);
384 }
385 };
386
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000387 struct CaseBits {
388 uint64_t Mask;
389 MachineBasicBlock* BB;
390 unsigned Bits;
391
392 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
393 Mask(mask), BB(bb), Bits(bits) { }
394 };
395
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000396 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000397 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000398 typedef CaseVector::iterator CaseItr;
399 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000400
401 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
402 /// of conditional branches.
403 struct CaseRec {
404 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
405 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
406
407 /// CaseBB - The MBB in which to emit the compare and branch
408 MachineBasicBlock *CaseBB;
409 /// LT, GE - If nonzero, we know the current case value must be less-than or
410 /// greater-than-or-equal-to these Constants.
411 Constant *LT;
412 Constant *GE;
413 /// Range - A pair of iterators representing the range of case values to be
414 /// processed at this point in the binary search tree.
415 CaseRange Range;
416 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000417
418 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000419
420 /// The comparison function for sorting the switch case values in the vector.
421 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000422 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000423 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000424 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
425 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
426 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
427 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000428 }
429 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000430
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000431 struct CaseBitsCmp {
432 bool operator () (const CaseBits& C1, const CaseBits& C2) {
433 return C1.Bits > C2.Bits;
434 }
435 };
436
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000437 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000438
Chris Lattner1c08c712005-01-07 07:47:53 +0000439public:
440 // TLI - This is information that describes the available target features we
441 // need for lowering. This indicates when operations are unavailable,
442 // implemented with a libcall, etc.
443 TargetLowering &TLI;
444 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000445 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000446
Nate Begemanf15485a2006-03-27 01:32:24 +0000447 /// SwitchCases - Vector of CaseBlock structures used to communicate
448 /// SwitchInst code generation information.
449 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000450 /// JTCases - Vector of JumpTable structures used to communicate
451 /// SwitchInst code generation information.
452 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000453 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000454
Chris Lattner1c08c712005-01-07 07:47:53 +0000455 /// FuncInfo - Information about the function as a whole.
456 ///
457 FunctionLoweringInfo &FuncInfo;
458
459 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000460 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000461 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000462 FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000463 }
464
Chris Lattnera651cf62005-01-17 19:43:36 +0000465 /// getRoot - Return the current virtual root of the Selection DAG.
466 ///
467 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000468 if (PendingLoads.empty())
469 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000470
Chris Lattnerd3948112005-01-17 22:19:26 +0000471 if (PendingLoads.size() == 1) {
472 SDOperand Root = PendingLoads[0];
473 DAG.setRoot(Root);
474 PendingLoads.clear();
475 return Root;
476 }
477
478 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000479 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
480 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000481 PendingLoads.clear();
482 DAG.setRoot(Root);
483 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000484 }
485
Chris Lattner571e4342006-10-27 21:36:01 +0000486 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
487
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 void visit(Instruction &I) { visit(I.getOpcode(), I); }
489
490 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000491 // Note: this doesn't use InstVisitor, because it has to work with
492 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000493 switch (Opcode) {
494 default: assert(0 && "Unknown instruction type encountered!");
495 abort();
496 // Build the switch statement using the Instruction.def file.
497#define HANDLE_INST(NUM, OPCODE, CLASS) \
498 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
499#include "llvm/Instruction.def"
500 }
501 }
502
503 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
504
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000505 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000506 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000507 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000508
509 SDOperand getIntPtrConstant(uint64_t Val) {
510 return DAG.getConstant(Val, TLI.getPointerTy());
511 }
512
Chris Lattner199862b2006-03-16 19:57:50 +0000513 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000514
Chris Lattner0da331f2007-02-04 01:31:47 +0000515 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000516 SDOperand &N = NodeMap[V];
517 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000518 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000519 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000520
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000521 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
522 std::set<unsigned> &OutputRegs,
523 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000524
Chris Lattner571e4342006-10-27 21:36:01 +0000525 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
526 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
527 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000528 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000529 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000530 void LowerCallTo(Instruction &I,
531 const Type *CalledValueTy, unsigned CallingConv,
532 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey735b6f82007-02-22 15:38:06 +0000533
Chris Lattner1c08c712005-01-07 07:47:53 +0000534 // Terminator instructions.
535 void visitRet(ReturnInst &I);
536 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000537 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000538 void visitUnreachable(UnreachableInst &I) { /* noop */ }
539
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000540 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000541 bool handleSmallSwitchRange(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 handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000546 CaseRecVector& WorkList,
547 Value* SV,
548 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000549 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000550 CaseRecVector& WorkList,
551 Value* SV,
552 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000553 bool handleBitTestsSwitchCase(CaseRec& CR,
554 CaseRecVector& WorkList,
555 Value* SV,
556 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000557 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000558 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
559 void visitBitTestCase(MachineBasicBlock* NextMBB,
560 unsigned Reg,
561 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000562 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000563 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
564 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000565
Chris Lattner1c08c712005-01-07 07:47:53 +0000566 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000567 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000568 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000569 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000570
Reid Spencer24d6da52007-01-21 00:29:26 +0000571 void visitScalarBinary(User &I, unsigned OpCode);
572 void visitVectorBinary(User &I, unsigned OpCode);
573 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000574 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000575 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000576 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000577 visitVectorBinary(I, ISD::VADD);
578 else if (I.getType()->isFloatingPoint())
579 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000580 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000581 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000582 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000583 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000584 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000585 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000586 visitVectorBinary(I, ISD::VMUL);
587 else if (I.getType()->isFloatingPoint())
588 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000589 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000590 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000591 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000592 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
593 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
594 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
595 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
596 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
597 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
598 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
599 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
600 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
601 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000602 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
603 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000604 void visitICmp(User &I);
605 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000606 // Visit the conversion instructions
607 void visitTrunc(User &I);
608 void visitZExt(User &I);
609 void visitSExt(User &I);
610 void visitFPTrunc(User &I);
611 void visitFPExt(User &I);
612 void visitFPToUI(User &I);
613 void visitFPToSI(User &I);
614 void visitUIToFP(User &I);
615 void visitSIToFP(User &I);
616 void visitPtrToInt(User &I);
617 void visitIntToPtr(User &I);
618 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000619
Chris Lattner2bbd8102006-03-29 00:11:43 +0000620 void visitExtractElement(User &I);
621 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000622 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000623
Chris Lattner1c08c712005-01-07 07:47:53 +0000624 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000626
627 void visitMalloc(MallocInst &I);
628 void visitFree(FreeInst &I);
629 void visitAlloca(AllocaInst &I);
630 void visitLoad(LoadInst &I);
631 void visitStore(StoreInst &I);
632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
633 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000634 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000637
Chris Lattner1c08c712005-01-07 07:47:53 +0000638 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000639 void visitVAArg(VAArgInst &I);
640 void visitVAEnd(CallInst &I);
641 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000642
Chris Lattner7041ee32005-01-11 05:56:49 +0000643 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000644
645 void visitUserOp1(Instruction &I) {
646 assert(0 && "UserOp1 should not exist at instruction selection time!");
647 abort();
648 }
649 void visitUserOp2(Instruction &I) {
650 assert(0 && "UserOp2 should not exist at instruction selection time!");
651 abort();
652 }
653};
654} // end namespace llvm
655
Chris Lattner199862b2006-03-16 19:57:50 +0000656SDOperand SelectionDAGLowering::getValue(const Value *V) {
657 SDOperand &N = NodeMap[V];
658 if (N.Val) return N;
659
660 const Type *VTy = V->getType();
661 MVT::ValueType VT = TLI.getValueType(VTy);
662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
664 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000665 SDOperand N1 = NodeMap[V];
666 assert(N1.Val && "visit didn't populate the ValueMap!");
667 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
669 return N = DAG.getGlobalAddress(GV, VT);
670 } else if (isa<ConstantPointerNull>(C)) {
671 return N = DAG.getConstant(0, TLI.getPointerTy());
672 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000673 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000674 return N = DAG.getNode(ISD::UNDEF, VT);
675
Chris Lattnerb2827b02006-03-19 00:52:58 +0000676 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000677 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000678 unsigned NumElements = PTy->getNumElements();
679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
680
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000681 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
683
684 // Create a VConstant node with generic Vector type.
685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
686 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000687 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
688 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000689 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
690 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000691 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000692 unsigned NumElements = PTy->getNumElements();
693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000694
695 // Now that we know the number and type of the elements, push a
696 // Constant or ConstantFP node onto the ops list for each element of
697 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000698 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000699 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000700 for (unsigned i = 0; i != NumElements; ++i)
701 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000702 } else {
703 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
704 SDOperand Op;
705 if (MVT::isFloatingPoint(PVT))
706 Op = DAG.getConstantFP(0, PVT);
707 else
708 Op = DAG.getConstant(0, PVT);
709 Ops.assign(NumElements, Op);
710 }
711
Chris Lattnerb2827b02006-03-19 00:52:58 +0000712 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000713 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
714 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000715 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
716 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000717 } else {
718 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000719 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000720 }
721 }
722
723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
724 std::map<const AllocaInst*, int>::iterator SI =
725 FuncInfo.StaticAllocaMap.find(AI);
726 if (SI != FuncInfo.StaticAllocaMap.end())
727 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
728 }
729
Chris Lattner251db182007-02-25 18:40:32 +0000730 unsigned InReg = FuncInfo.ValueMap[V];
731 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000732
733 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000734 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000735 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000736 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000737 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000738 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
739 unsigned NumVals = TLI.getNumElements(VT);
740 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
741 if (NumVals == 1)
742 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
743 else {
744 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
745 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
746 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
747 }
748 } else {
749 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
750 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
751 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
752 N = MVT::isFloatingPoint(VT)
753 ? DAG.getNode(ISD::FP_ROUND, VT, N)
754 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000755 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000756 } else {
757 // Otherwise, if this is a vector, make it available as a generic vector
758 // here.
759 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000760 const VectorType *PTy = cast<VectorType>(VTy);
761 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000762 PTyLegalElementVT);
763
764 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000765 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000766 if (PTyElementVT == PTyLegalElementVT) {
767 // If the value types are legal, just VBUILD the CopyFromReg nodes.
768 for (unsigned i = 0; i != NE; ++i)
769 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
770 PTyElementVT));
771 } else if (PTyElementVT < PTyLegalElementVT) {
772 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
773 for (unsigned i = 0; i != NE; ++i) {
774 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
775 PTyElementVT);
776 if (MVT::isFloatingPoint(PTyElementVT))
777 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
778 else
779 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
780 Ops.push_back(Op);
781 }
782 } else {
783 // If the register was expanded, use BUILD_PAIR.
784 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
785 for (unsigned i = 0; i != NE/2; ++i) {
786 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
787 PTyElementVT);
788 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
789 PTyElementVT);
790 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
791 }
792 }
793
794 Ops.push_back(DAG.getConstant(NE, MVT::i32));
795 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000796 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000797
798 // Finally, use a VBIT_CONVERT to make this available as the appropriate
799 // vector type.
800 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
801 DAG.getConstant(PTy->getNumElements(),
802 MVT::i32),
803 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000804 }
805
806 return N;
807}
808
809
Chris Lattner1c08c712005-01-07 07:47:53 +0000810void SelectionDAGLowering::visitRet(ReturnInst &I) {
811 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000812 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000813 return;
814 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000815 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000816 NewValues.push_back(getRoot());
817 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
818 SDOperand RetOp = getValue(I.getOperand(i));
819
820 // If this is an integer return value, we need to promote it ourselves to
821 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
822 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000823 // FIXME: C calling convention requires the return type to be promoted to
824 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000825 if (MVT::isInteger(RetOp.getValueType()) &&
826 RetOp.getValueType() < MVT::i64) {
827 MVT::ValueType TmpVT;
828 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
829 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
830 else
831 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000832 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +0000833 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerbcca3402007-01-03 16:49:33 +0000834 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000835 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000836 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000837 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencer47857812006-12-31 05:55:36 +0000838 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000839 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000840 }
841 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000842 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000843 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000844 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
845 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000846}
847
Chris Lattner571e4342006-10-27 21:36:01 +0000848/// ExportFromCurrentBlock - If this condition isn't known to be exported from
849/// the current basic block, add it to ValueMap now so that we'll get a
850/// CopyTo/FromReg.
851void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
852 // No need to export constants.
853 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
854
855 // Already exported?
856 if (FuncInfo.isExportedInst(V)) return;
857
858 unsigned Reg = FuncInfo.InitializeRegForValue(V);
859 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
860}
861
Chris Lattner8c494ab2006-10-27 23:50:33 +0000862bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
863 const BasicBlock *FromBB) {
864 // The operands of the setcc have to be in this block. We don't know
865 // how to export them from some other block.
866 if (Instruction *VI = dyn_cast<Instruction>(V)) {
867 // Can export from current BB.
868 if (VI->getParent() == FromBB)
869 return true;
870
871 // Is already exported, noop.
872 return FuncInfo.isExportedInst(V);
873 }
874
875 // If this is an argument, we can export it if the BB is the entry block or
876 // if it is already exported.
877 if (isa<Argument>(V)) {
878 if (FromBB == &FromBB->getParent()->getEntryBlock())
879 return true;
880
881 // Otherwise, can only export this if it is already exported.
882 return FuncInfo.isExportedInst(V);
883 }
884
885 // Otherwise, constants can always be exported.
886 return true;
887}
888
Chris Lattner6a586c82006-10-29 21:01:20 +0000889static bool InBlock(const Value *V, const BasicBlock *BB) {
890 if (const Instruction *I = dyn_cast<Instruction>(V))
891 return I->getParent() == BB;
892 return true;
893}
894
Chris Lattner571e4342006-10-27 21:36:01 +0000895/// FindMergedConditions - If Cond is an expression like
896void SelectionDAGLowering::FindMergedConditions(Value *Cond,
897 MachineBasicBlock *TBB,
898 MachineBasicBlock *FBB,
899 MachineBasicBlock *CurBB,
900 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000901 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000902 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000903
Reid Spencere4d87aa2006-12-23 06:05:41 +0000904 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
905 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000906 BOp->getParent() != CurBB->getBasicBlock() ||
907 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
908 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000909 const BasicBlock *BB = CurBB->getBasicBlock();
910
Reid Spencere4d87aa2006-12-23 06:05:41 +0000911 // If the leaf of the tree is a comparison, merge the condition into
912 // the caseblock.
913 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
914 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000915 // how to export them from some other block. If this is the first block
916 // of the sequence, no exporting is needed.
917 (CurBB == CurMBB ||
918 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
919 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000920 BOp = cast<Instruction>(Cond);
921 ISD::CondCode Condition;
922 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
923 switch (IC->getPredicate()) {
924 default: assert(0 && "Unknown icmp predicate opcode!");
925 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
926 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
927 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
928 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
929 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
930 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
931 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
932 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
933 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
934 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
935 }
936 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
937 ISD::CondCode FPC, FOC;
938 switch (FC->getPredicate()) {
939 default: assert(0 && "Unknown fcmp predicate opcode!");
940 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
941 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
942 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
943 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
944 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
945 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
946 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
947 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
948 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
949 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
950 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
951 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
952 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
953 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
954 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
955 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
956 }
957 if (FiniteOnlyFPMath())
958 Condition = FOC;
959 else
960 Condition = FPC;
961 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000962 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000963 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000964 }
965
Chris Lattner571e4342006-10-27 21:36:01 +0000966 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000967 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000968 SwitchCases.push_back(CB);
969 return;
970 }
971
972 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000973 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000974 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000975 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000976 return;
977 }
978
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000979
980 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000981 MachineFunction::iterator BBI = CurBB;
982 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
983 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
984
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000985 if (Opc == Instruction::Or) {
986 // Codegen X | Y as:
987 // jmp_if_X TBB
988 // jmp TmpBB
989 // TmpBB:
990 // jmp_if_Y TBB
991 // jmp FBB
992 //
Chris Lattner571e4342006-10-27 21:36:01 +0000993
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000994 // Emit the LHS condition.
995 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
996
997 // Emit the RHS condition into TmpBB.
998 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
999 } else {
1000 assert(Opc == Instruction::And && "Unknown merge op!");
1001 // Codegen X & Y as:
1002 // jmp_if_X TmpBB
1003 // jmp FBB
1004 // TmpBB:
1005 // jmp_if_Y TBB
1006 // jmp FBB
1007 //
1008 // This requires creation of TmpBB after CurBB.
1009
1010 // Emit the LHS condition.
1011 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1012
1013 // Emit the RHS condition into TmpBB.
1014 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1015 }
Chris Lattner571e4342006-10-27 21:36:01 +00001016}
1017
Chris Lattnerdf19f272006-10-31 22:37:42 +00001018/// If the set of cases should be emitted as a series of branches, return true.
1019/// If we should emit this as a bunch of and/or'd together conditions, return
1020/// false.
1021static bool
1022ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1023 if (Cases.size() != 2) return true;
1024
Chris Lattner0ccb5002006-10-31 23:06:00 +00001025 // If this is two comparisons of the same values or'd or and'd together, they
1026 // will get folded into a single comparison, so don't emit two blocks.
1027 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1028 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1029 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1030 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1031 return false;
1032 }
1033
Chris Lattnerdf19f272006-10-31 22:37:42 +00001034 return true;
1035}
1036
Chris Lattner1c08c712005-01-07 07:47:53 +00001037void SelectionDAGLowering::visitBr(BranchInst &I) {
1038 // Update machine-CFG edges.
1039 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001040
1041 // Figure out which block is immediately after the current one.
1042 MachineBasicBlock *NextBlock = 0;
1043 MachineFunction::iterator BBI = CurMBB;
1044 if (++BBI != CurMBB->getParent()->end())
1045 NextBlock = BBI;
1046
1047 if (I.isUnconditional()) {
1048 // If this is not a fall-through branch, emit the branch.
1049 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001050 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001051 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001052
Chris Lattner57ab6592006-10-24 17:57:59 +00001053 // Update machine-CFG edges.
1054 CurMBB->addSuccessor(Succ0MBB);
1055
1056 return;
1057 }
1058
1059 // If this condition is one of the special cases we handle, do special stuff
1060 // now.
1061 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001062 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001063
1064 // If this is a series of conditions that are or'd or and'd together, emit
1065 // this as a sequence of branches instead of setcc's with and/or operations.
1066 // For example, instead of something like:
1067 // cmp A, B
1068 // C = seteq
1069 // cmp D, E
1070 // F = setle
1071 // or C, F
1072 // jnz foo
1073 // Emit:
1074 // cmp A, B
1075 // je foo
1076 // cmp D, E
1077 // jle foo
1078 //
1079 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1080 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001081 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001082 BOp->getOpcode() == Instruction::Or)) {
1083 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001084 // If the compares in later blocks need to use values not currently
1085 // exported from this block, export them now. This block should always
1086 // be the first entry.
1087 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1088
Chris Lattnerdf19f272006-10-31 22:37:42 +00001089 // Allow some cases to be rejected.
1090 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001091 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1092 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1093 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1094 }
1095
1096 // Emit the branch for this block.
1097 visitSwitchCase(SwitchCases[0]);
1098 SwitchCases.erase(SwitchCases.begin());
1099 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001100 }
1101
Chris Lattner0ccb5002006-10-31 23:06:00 +00001102 // Okay, we decided not to do this, remove any inserted MBB's and clear
1103 // SwitchCases.
1104 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1105 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1106
Chris Lattnerdf19f272006-10-31 22:37:42 +00001107 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001108 }
1109 }
Chris Lattner24525952006-10-24 18:07:37 +00001110
1111 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001112 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001113 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001114 // Use visitSwitchCase to actually insert the fast branch sequence for this
1115 // cond branch.
1116 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001117}
1118
Nate Begemanf15485a2006-03-27 01:32:24 +00001119/// visitSwitchCase - Emits the necessary code to represent a single node in
1120/// the binary search tree resulting from lowering a switch instruction.
1121void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001122 SDOperand Cond;
1123 SDOperand CondLHS = getValue(CB.CmpLHS);
1124
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001125 // Build the setcc now.
1126 if (CB.CmpMHS == NULL) {
1127 // Fold "(X == true)" to X and "(X == false)" to !X to
1128 // handle common cases produced by branch lowering.
1129 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1130 Cond = CondLHS;
1131 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1132 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1133 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1134 } else
1135 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1136 } else {
1137 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001138
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001139 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1140 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1141
1142 SDOperand CmpOp = getValue(CB.CmpMHS);
1143 MVT::ValueType VT = CmpOp.getValueType();
1144
1145 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1146 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1147 } else {
1148 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1149 Cond = DAG.getSetCC(MVT::i1, SUB,
1150 DAG.getConstant(High-Low, VT), ISD::SETULE);
1151 }
1152
1153 }
1154
Nate Begemanf15485a2006-03-27 01:32:24 +00001155 // Set NextBlock to be the MBB immediately after the current one, if any.
1156 // This is used to avoid emitting unnecessary branches to the next block.
1157 MachineBasicBlock *NextBlock = 0;
1158 MachineFunction::iterator BBI = CurMBB;
1159 if (++BBI != CurMBB->getParent()->end())
1160 NextBlock = BBI;
1161
1162 // If the lhs block is the next block, invert the condition so that we can
1163 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001164 if (CB.TrueBB == NextBlock) {
1165 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001166 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1167 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1168 }
1169 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001170 DAG.getBasicBlock(CB.TrueBB));
1171 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001172 DAG.setRoot(BrCond);
1173 else
1174 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001175 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001176 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001177 CurMBB->addSuccessor(CB.TrueBB);
1178 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001179}
1180
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001181/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001182void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001183 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001184 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001185 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001186 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1187 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1188 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1189 Table, Index));
1190 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001191}
1192
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001193/// visitJumpTableHeader - This function emits necessary code to produce index
1194/// in the JumpTable from switch case.
1195void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1196 SelectionDAGISel::JumpTableHeader &JTH) {
1197 // Subtract the lowest switch case value from the value being switched on
1198 // and conditional branch to default mbb if the result is greater than the
1199 // difference between smallest and largest cases.
1200 SDOperand SwitchOp = getValue(JTH.SValue);
1201 MVT::ValueType VT = SwitchOp.getValueType();
1202 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1203 DAG.getConstant(JTH.First, VT));
1204
1205 // The SDNode we just created, which holds the value being switched on
1206 // minus the the smallest case value, needs to be copied to a virtual
1207 // register so it can be used as an index into the jump table in a
1208 // subsequent basic block. This value may be smaller or larger than the
1209 // target's pointer type, and therefore require extension or truncating.
1210 if (VT > TLI.getPointerTy())
1211 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1212 else
1213 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1214
1215 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1216 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1217 JT.Reg = JumpTableReg;
1218
1219 // Emit the range check for the jump table, and branch to the default
1220 // block for the switch statement if the value being switched on exceeds
1221 // the largest case in the switch.
1222 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1223 DAG.getConstant(JTH.Last-JTH.First,VT),
1224 ISD::SETUGT);
1225
1226 // Set NextBlock to be the MBB immediately after the current one, if any.
1227 // This is used to avoid emitting unnecessary branches to the next block.
1228 MachineBasicBlock *NextBlock = 0;
1229 MachineFunction::iterator BBI = CurMBB;
1230 if (++BBI != CurMBB->getParent()->end())
1231 NextBlock = BBI;
1232
1233 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1234 DAG.getBasicBlock(JT.Default));
1235
1236 if (JT.MBB == NextBlock)
1237 DAG.setRoot(BrCond);
1238 else
1239 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001240 DAG.getBasicBlock(JT.MBB)));
1241
1242 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001243}
1244
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001245/// visitBitTestHeader - This function emits necessary code to produce value
1246/// suitable for "bit tests"
1247void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1248 // Subtract the minimum value
1249 SDOperand SwitchOp = getValue(B.SValue);
1250 MVT::ValueType VT = SwitchOp.getValueType();
1251 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1252 DAG.getConstant(B.First, VT));
1253
1254 // Check range
1255 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1256 DAG.getConstant(B.Range, VT),
1257 ISD::SETUGT);
1258
1259 SDOperand ShiftOp;
1260 if (VT > TLI.getShiftAmountTy())
1261 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1262 else
1263 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1264
1265 // Make desired shift
1266 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1267 DAG.getConstant(1, TLI.getPointerTy()),
1268 ShiftOp);
1269
1270 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1271 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1272 B.Reg = SwitchReg;
1273
1274 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1275 DAG.getBasicBlock(B.Default));
1276
1277 // Set NextBlock to be the MBB immediately after the current one, if any.
1278 // This is used to avoid emitting unnecessary branches to the next block.
1279 MachineBasicBlock *NextBlock = 0;
1280 MachineFunction::iterator BBI = CurMBB;
1281 if (++BBI != CurMBB->getParent()->end())
1282 NextBlock = BBI;
1283
1284 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1285 if (MBB == NextBlock)
1286 DAG.setRoot(BrRange);
1287 else
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1289 DAG.getBasicBlock(MBB)));
1290
1291 CurMBB->addSuccessor(B.Default);
1292 CurMBB->addSuccessor(MBB);
1293
1294 return;
1295}
1296
1297/// visitBitTestCase - this function produces one "bit test"
1298void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1299 unsigned Reg,
1300 SelectionDAGISel::BitTestCase &B) {
1301 // Emit bit tests and jumps
1302 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1303
1304 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1305 SwitchVal,
1306 DAG.getConstant(B.Mask,
1307 TLI.getPointerTy()));
1308 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1309 DAG.getConstant(0, TLI.getPointerTy()),
1310 ISD::SETNE);
1311 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1312 AndCmp, DAG.getBasicBlock(B.TargetBB));
1313
1314 // Set NextBlock to be the MBB immediately after the current one, if any.
1315 // This is used to avoid emitting unnecessary branches to the next block.
1316 MachineBasicBlock *NextBlock = 0;
1317 MachineFunction::iterator BBI = CurMBB;
1318 if (++BBI != CurMBB->getParent()->end())
1319 NextBlock = BBI;
1320
1321 if (NextMBB == NextBlock)
1322 DAG.setRoot(BrAnd);
1323 else
1324 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1325 DAG.getBasicBlock(NextMBB)));
1326
1327 CurMBB->addSuccessor(B.TargetBB);
1328 CurMBB->addSuccessor(NextMBB);
1329
1330 return;
1331}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001332
Jim Laskeyb180aa12007-02-21 22:53:45 +00001333void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001334 assert(0 && "Should never be visited directly");
1335}
1336void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001337 // Retrieve successors.
1338 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1339 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1340
Jim Laskey183f47f2007-02-25 21:43:59 +00001341 if (!AsTerminator) {
1342 // Mark landing pad so that it doesn't get deleted in branch folding.
1343 LandingPad->setIsLandingPad();
1344
1345 // Insert a label before the invoke call to mark the try range.
1346 // This can be used to detect deletion of the invoke via the
1347 // MachineModuleInfo.
1348 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1349 unsigned BeginLabel = MMI->NextLabelID();
1350 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1351 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001352
Jim Laskey183f47f2007-02-25 21:43:59 +00001353 LowerCallTo(I, I.getCalledValue()->getType(),
1354 I.getCallingConv(),
1355 false,
1356 getValue(I.getOperand(0)),
1357 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001358
Jim Laskey183f47f2007-02-25 21:43:59 +00001359 // Insert a label before the invoke call to mark the try range.
1360 // This can be used to detect deletion of the invoke via the
1361 // MachineModuleInfo.
1362 unsigned EndLabel = MMI->NextLabelID();
1363 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1364 DAG.getConstant(EndLabel, MVT::i32)));
1365
1366 // Inform MachineModuleInfo of range.
1367 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1368
1369 // Update successor info
1370 CurMBB->addSuccessor(Return);
1371 CurMBB->addSuccessor(LandingPad);
1372 } else {
1373 // Drop into normal successor.
1374 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1375 DAG.getBasicBlock(Return)));
1376 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001377}
1378
1379void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1380}
1381
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001382/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001383/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001384bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001385 CaseRecVector& WorkList,
1386 Value* SV,
1387 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001388 Case& BackCase = *(CR.Range.second-1);
1389
1390 // Size is the number of Cases represented by this range.
1391 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001392 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001393 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001394
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001395 // Get the MachineFunction which holds the current MBB. This is used when
1396 // inserting any additional MBBs necessary to represent the switch.
1397 MachineFunction *CurMF = CurMBB->getParent();
1398
1399 // Figure out which block is immediately after the current one.
1400 MachineBasicBlock *NextBlock = 0;
1401 MachineFunction::iterator BBI = CR.CaseBB;
1402
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001403 if (++BBI != CurMBB->getParent()->end())
1404 NextBlock = BBI;
1405
1406 // TODO: If any two of the cases has the same destination, and if one value
1407 // is the same as the other, but has one bit unset that the other has set,
1408 // use bit manipulation to do two compares at once. For example:
1409 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1410
1411 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001412 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001413 // The last case block won't fall through into 'NextBlock' if we emit the
1414 // branches in this order. See if rearranging a case value would help.
1415 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001416 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001417 std::swap(*I, BackCase);
1418 break;
1419 }
1420 }
1421 }
1422
1423 // Create a CaseBlock record representing a conditional branch to
1424 // the Case's target mbb if the value being switched on SV is equal
1425 // to C.
1426 MachineBasicBlock *CurBlock = CR.CaseBB;
1427 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1428 MachineBasicBlock *FallThrough;
1429 if (I != E-1) {
1430 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1431 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1432 } else {
1433 // If the last case doesn't match, go to the default block.
1434 FallThrough = Default;
1435 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001436
1437 Value *RHS, *LHS, *MHS;
1438 ISD::CondCode CC;
1439 if (I->High == I->Low) {
1440 // This is just small small case range :) containing exactly 1 case
1441 CC = ISD::SETEQ;
1442 LHS = SV; RHS = I->High; MHS = NULL;
1443 } else {
1444 CC = ISD::SETLE;
1445 LHS = I->Low; MHS = SV; RHS = I->High;
1446 }
1447 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1448 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001449
1450 // If emitting the first comparison, just call visitSwitchCase to emit the
1451 // code into the current block. Otherwise, push the CaseBlock onto the
1452 // vector to be later processed by SDISel, and insert the node's MBB
1453 // before the next MBB.
1454 if (CurBlock == CurMBB)
1455 visitSwitchCase(CB);
1456 else
1457 SwitchCases.push_back(CB);
1458
1459 CurBlock = FallThrough;
1460 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001461
1462 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001463}
1464
1465/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001466bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001467 CaseRecVector& WorkList,
1468 Value* SV,
1469 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001470 Case& FrontCase = *CR.Range.first;
1471 Case& BackCase = *(CR.Range.second-1);
1472
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001473 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1474 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1475
1476 uint64_t TSize = 0;
1477 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1478 I!=E; ++I)
1479 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001480
1481 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1482 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001483 TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001484 return false;
1485
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001486 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1487 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001488 return false;
1489
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001490 DOUT << "Lowering jump table\n"
1491 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001492 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001493
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001494 // Get the MachineFunction which holds the current MBB. This is used when
1495 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001496 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001497
1498 // Figure out which block is immediately after the current one.
1499 MachineBasicBlock *NextBlock = 0;
1500 MachineFunction::iterator BBI = CR.CaseBB;
1501
1502 if (++BBI != CurMBB->getParent()->end())
1503 NextBlock = BBI;
1504
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001505 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1506
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001507 // Create a new basic block to hold the code for loading the address
1508 // of the jump table, and jumping to it. Update successor information;
1509 // we will either branch to the default case for the switch, or the jump
1510 // table.
1511 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1512 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1513 CR.CaseBB->addSuccessor(Default);
1514 CR.CaseBB->addSuccessor(JumpTableBB);
1515
1516 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001517 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001518 // a case statement, push the case's BB onto the vector, otherwise, push
1519 // the default BB.
1520 std::vector<MachineBasicBlock*> DestBBs;
1521 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001522 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1523 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1524 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1525
1526 if ((Low <= TEI) && (TEI <= High)) {
1527 DestBBs.push_back(I->BB);
1528 if (TEI==High)
1529 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001530 } else {
1531 DestBBs.push_back(Default);
1532 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001533 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001534
1535 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001536 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001537 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1538 E = DestBBs.end(); I != E; ++I) {
1539 if (!SuccsHandled[(*I)->getNumber()]) {
1540 SuccsHandled[(*I)->getNumber()] = true;
1541 JumpTableBB->addSuccessor(*I);
1542 }
1543 }
1544
1545 // Create a jump table index for this jump table, or return an existing
1546 // one.
1547 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1548
1549 // Set the jump table information so that we can codegen it as a second
1550 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001551 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001552 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1553 (CR.CaseBB == CurMBB));
1554 if (CR.CaseBB == CurMBB)
1555 visitJumpTableHeader(JT, JTH);
1556
1557 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001558
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001559 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001560}
1561
1562/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1563/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001564bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001565 CaseRecVector& WorkList,
1566 Value* SV,
1567 MachineBasicBlock* Default) {
1568 // Get the MachineFunction which holds the current MBB. This is used when
1569 // inserting any additional MBBs necessary to represent the switch.
1570 MachineFunction *CurMF = CurMBB->getParent();
1571
1572 // Figure out which block is immediately after the current one.
1573 MachineBasicBlock *NextBlock = 0;
1574 MachineFunction::iterator BBI = CR.CaseBB;
1575
1576 if (++BBI != CurMBB->getParent()->end())
1577 NextBlock = BBI;
1578
1579 Case& FrontCase = *CR.Range.first;
1580 Case& BackCase = *(CR.Range.second-1);
1581 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1582
1583 // Size is the number of Cases represented by this range.
1584 unsigned Size = CR.Range.second - CR.Range.first;
1585
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001586 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1587 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001588 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001589 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001590
1591 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1592 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001593 uint64_t TSize = 0;
1594 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1595 I!=E; ++I)
1596 TSize += I->size();
1597
1598 uint64_t LSize = FrontCase.size();
1599 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001600 DOUT << "Selecting best pivot: \n"
1601 << "First: " << First << ", Last: " << Last <<"\n"
1602 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001603 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001604 J!=E; ++I, ++J) {
1605 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1606 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001607 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001608 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1609 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001610 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001611 // Should always split in some non-trivial place
1612 DOUT <<"=>Step\n"
1613 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1614 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1615 << "Metric: " << Metric << "\n";
1616 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001617 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001618 FMetric = Metric;
1619 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001620 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001621
1622 LSize += J->size();
1623 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001624 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001625 // If our case is dense we *really* should handle it earlier!
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001626 assert((FMetric > 0) && "Should handle dense range earlier!");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001627
1628 CaseRange LHSR(CR.Range.first, Pivot);
1629 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001630 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001631 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1632
1633 // We know that we branch to the LHS if the Value being switched on is
1634 // less than the Pivot value, C. We use this to optimize our binary
1635 // tree a bit, by recognizing that if SV is greater than or equal to the
1636 // LHS's Case Value, and that Case Value is exactly one less than the
1637 // Pivot's Value, then we can branch directly to the LHS's Target,
1638 // rather than creating a leaf node for it.
1639 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001640 LHSR.first->High == CR.GE &&
1641 cast<ConstantInt>(C)->getSExtValue() ==
1642 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1643 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001644 } else {
1645 TrueBB = new MachineBasicBlock(LLVMBB);
1646 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1647 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1648 }
1649
1650 // Similar to the optimization above, if the Value being switched on is
1651 // known to be less than the Constant CR.LT, and the current Case Value
1652 // is CR.LT - 1, then we can branch directly to the target block for
1653 // the current Case Value, rather than emitting a RHS leaf node for it.
1654 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001655 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1656 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1657 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001658 } else {
1659 FalseBB = new MachineBasicBlock(LLVMBB);
1660 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1661 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1662 }
1663
1664 // Create a CaseBlock record representing a conditional branch to
1665 // the LHS node if the value being switched on SV is less than C.
1666 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001667 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1668 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001669
1670 if (CR.CaseBB == CurMBB)
1671 visitSwitchCase(CB);
1672 else
1673 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001674
1675 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001676}
1677
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001678/// handleBitTestsSwitchCase - if current case range has few destination and
1679/// range span less, than machine word bitwidth, encode case range into series
1680/// of masks and emit bit tests with these masks.
1681bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1682 CaseRecVector& WorkList,
1683 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001684 MachineBasicBlock* Default){
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001685 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1686
1687 Case& FrontCase = *CR.Range.first;
1688 Case& BackCase = *(CR.Range.second-1);
1689
1690 // Get the MachineFunction which holds the current MBB. This is used when
1691 // inserting any additional MBBs necessary to represent the switch.
1692 MachineFunction *CurMF = CurMBB->getParent();
1693
1694 unsigned numCmps = 0;
1695 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1696 I!=E; ++I) {
1697 // Single case counts one, case range - two.
1698 if (I->Low == I->High)
1699 numCmps +=1;
1700 else
1701 numCmps +=2;
1702 }
1703
1704 // Count unique destinations
1705 SmallSet<MachineBasicBlock*, 4> Dests;
1706 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1707 Dests.insert(I->BB);
1708 if (Dests.size() > 3)
1709 // Don't bother the code below, if there are too much unique destinations
1710 return false;
1711 }
1712 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1713 << "Total number of comparisons: " << numCmps << "\n";
1714
1715 // Compute span of values.
1716 Constant* minValue = FrontCase.Low;
1717 Constant* maxValue = BackCase.High;
1718 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1719 cast<ConstantInt>(minValue)->getSExtValue();
1720 DOUT << "Compare range: " << range << "\n"
1721 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1722 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1723
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00001724 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001725 (!(Dests.size() == 1 && numCmps >= 3) &&
1726 !(Dests.size() == 2 && numCmps >= 5) &&
1727 !(Dests.size() >= 3 && numCmps >= 6)))
1728 return false;
1729
1730 DOUT << "Emitting bit tests\n";
1731 int64_t lowBound = 0;
1732
1733 // Optimize the case where all the case values fit in a
1734 // word without having to subtract minValue. In this case,
1735 // we can optimize away the subtraction.
1736 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001737 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001738 range = cast<ConstantInt>(maxValue)->getSExtValue();
1739 } else {
1740 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1741 }
1742
1743 CaseBitsVector CasesBits;
1744 unsigned i, count = 0;
1745
1746 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1747 MachineBasicBlock* Dest = I->BB;
1748 for (i = 0; i < count; ++i)
1749 if (Dest == CasesBits[i].BB)
1750 break;
1751
1752 if (i == count) {
1753 assert((count < 3) && "Too much destinations to test!");
1754 CasesBits.push_back(CaseBits(0, Dest, 0));
1755 count++;
1756 }
1757
1758 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1759 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1760
1761 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001762 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001763 CasesBits[i].Bits++;
1764 }
1765
1766 }
1767 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1768
1769 SelectionDAGISel::BitTestInfo BTC;
1770
1771 // Figure out which block is immediately after the current one.
1772 MachineFunction::iterator BBI = CR.CaseBB;
1773 ++BBI;
1774
1775 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1776
1777 DOUT << "Cases:\n";
1778 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1779 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1780 << ", BB: " << CasesBits[i].BB << "\n";
1781
1782 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1783 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1784 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1785 CaseBB,
1786 CasesBits[i].BB));
1787 }
1788
1789 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00001790 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001791 CR.CaseBB, Default, BTC);
1792
1793 if (CR.CaseBB == CurMBB)
1794 visitBitTestHeader(BTB);
1795
1796 BitTestCases.push_back(BTB);
1797
1798 return true;
1799}
1800
1801
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001802// Clusterify - Transform simple list of Cases into list of CaseRange's
1803unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1804 const SwitchInst& SI) {
1805 unsigned numCmps = 0;
1806
1807 // Start with "simple" cases
1808 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1809 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1810 Cases.push_back(Case(SI.getSuccessorValue(i),
1811 SI.getSuccessorValue(i),
1812 SMBB));
1813 }
1814 sort(Cases.begin(), Cases.end(), CaseCmp());
1815
1816 // Merge case into clusters
1817 if (Cases.size()>=2)
1818 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1819 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1820 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1821 MachineBasicBlock* nextBB = J->BB;
1822 MachineBasicBlock* currentBB = I->BB;
1823
1824 // If the two neighboring cases go to the same destination, merge them
1825 // into a single case.
1826 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1827 I->High = J->High;
1828 J = Cases.erase(J);
1829 } else {
1830 I = J++;
1831 }
1832 }
1833
1834 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1835 if (I->Low != I->High)
1836 // A range counts double, since it requires two compares.
1837 ++numCmps;
1838 }
1839
1840 return numCmps;
1841}
1842
1843void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001844 // Figure out which block is immediately after the current one.
1845 MachineBasicBlock *NextBlock = 0;
1846 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001847
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001848 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001849
Nate Begemanf15485a2006-03-27 01:32:24 +00001850 // If there is only the default destination, branch to it if it is not the
1851 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001852 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001853 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001854
Nate Begemanf15485a2006-03-27 01:32:24 +00001855 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001856 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001857 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001858 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001859
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001860 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001861 return;
1862 }
1863
1864 // If there are any non-default case statements, create a vector of Cases
1865 // representing each one, and sort the vector so that we can efficiently
1866 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001867 CaseVector Cases;
1868 unsigned numCmps = Clusterify(Cases, SI);
1869 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1870 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001871
Nate Begemanf15485a2006-03-27 01:32:24 +00001872 // Get the Value to be switched on and default basic blocks, which will be
1873 // inserted into CaseBlock records, representing basic blocks in the binary
1874 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001875 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001876
Nate Begemanf15485a2006-03-27 01:32:24 +00001877 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001878 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001879 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1880
1881 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001882 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001883 CaseRec CR = WorkList.back();
1884 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001885
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001886 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1887 continue;
1888
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001889 // If the range has few cases (two or less) emit a series of specific
1890 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001891 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1892 continue;
1893
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001894 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001895 // target supports indirect branches, then emit a jump table rather than
1896 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001897 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1898 continue;
1899
1900 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1901 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1902 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001903 }
1904}
1905
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001906
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001907void SelectionDAGLowering::visitSub(User &I) {
1908 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001909 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001910 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001911 visitVectorBinary(I, ISD::VSUB);
1912 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001913 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1914 if (CFP->isExactlyValue(-0.0)) {
1915 SDOperand Op2 = getValue(I.getOperand(1));
1916 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1917 return;
1918 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001919 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001920 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001921 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001922}
1923
Reid Spencer24d6da52007-01-21 00:29:26 +00001924void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001925 SDOperand Op1 = getValue(I.getOperand(0));
1926 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001927
1928 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001929}
1930
Reid Spencer24d6da52007-01-21 00:29:26 +00001931void
1932SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001933 assert(isa<VectorType>(I.getType()));
1934 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001935 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001936
Reid Spencer24d6da52007-01-21 00:29:26 +00001937 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1938 getValue(I.getOperand(0)),
1939 getValue(I.getOperand(1)),
1940 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1941 Typ));
1942}
1943
1944void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1945 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001946 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001947 visitVectorBinary(I, VectorOp);
1948 else
1949 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001950}
Chris Lattner2c49f272005-01-19 22:31:21 +00001951
Nate Begemane21ea612005-11-18 07:42:56 +00001952void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1953 SDOperand Op1 = getValue(I.getOperand(0));
1954 SDOperand Op2 = getValue(I.getOperand(1));
1955
Reid Spencer832254e2007-02-02 02:16:23 +00001956 if (TLI.getShiftAmountTy() < Op2.getValueType())
1957 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1958 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1959 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001960
Chris Lattner1c08c712005-01-07 07:47:53 +00001961 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1962}
1963
Reid Spencer45fb3f32006-11-20 01:22:35 +00001964void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001965 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1966 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1967 predicate = IC->getPredicate();
1968 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1969 predicate = ICmpInst::Predicate(IC->getPredicate());
1970 SDOperand Op1 = getValue(I.getOperand(0));
1971 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001972 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001973 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001974 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1975 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1976 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1977 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1978 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1979 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1980 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1981 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1982 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1983 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1984 default:
1985 assert(!"Invalid ICmp predicate value");
1986 Opcode = ISD::SETEQ;
1987 break;
1988 }
1989 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1990}
1991
1992void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001993 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1994 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1995 predicate = FC->getPredicate();
1996 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1997 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001998 SDOperand Op1 = getValue(I.getOperand(0));
1999 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000 ISD::CondCode Condition, FOC, FPC;
2001 switch (predicate) {
2002 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2003 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2004 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2005 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2006 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2007 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2008 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2009 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2010 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2011 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2012 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2013 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2014 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2015 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2016 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2017 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2018 default:
2019 assert(!"Invalid FCmp predicate value");
2020 FOC = FPC = ISD::SETFALSE;
2021 break;
2022 }
2023 if (FiniteOnlyFPMath())
2024 Condition = FOC;
2025 else
2026 Condition = FPC;
2027 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002028}
2029
2030void SelectionDAGLowering::visitSelect(User &I) {
2031 SDOperand Cond = getValue(I.getOperand(0));
2032 SDOperand TrueVal = getValue(I.getOperand(1));
2033 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00002034 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00002035 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2036 TrueVal, FalseVal));
2037 } else {
2038 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2039 *(TrueVal.Val->op_end()-2),
2040 *(TrueVal.Val->op_end()-1)));
2041 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002042}
2043
Reid Spencer3da59db2006-11-27 01:05:10 +00002044
2045void SelectionDAGLowering::visitTrunc(User &I) {
2046 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2047 SDOperand N = getValue(I.getOperand(0));
2048 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2049 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2050}
2051
2052void SelectionDAGLowering::visitZExt(User &I) {
2053 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2054 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2055 SDOperand N = getValue(I.getOperand(0));
2056 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2057 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2058}
2059
2060void SelectionDAGLowering::visitSExt(User &I) {
2061 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2062 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2063 SDOperand N = getValue(I.getOperand(0));
2064 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2065 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2066}
2067
2068void SelectionDAGLowering::visitFPTrunc(User &I) {
2069 // FPTrunc is never a no-op cast, no need to check
2070 SDOperand N = getValue(I.getOperand(0));
2071 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2072 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2073}
2074
2075void SelectionDAGLowering::visitFPExt(User &I){
2076 // FPTrunc is never a no-op cast, no need to check
2077 SDOperand N = getValue(I.getOperand(0));
2078 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2079 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2080}
2081
2082void SelectionDAGLowering::visitFPToUI(User &I) {
2083 // FPToUI is never a no-op cast, no need to check
2084 SDOperand N = getValue(I.getOperand(0));
2085 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2086 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2087}
2088
2089void SelectionDAGLowering::visitFPToSI(User &I) {
2090 // FPToSI is never a no-op cast, no need to check
2091 SDOperand N = getValue(I.getOperand(0));
2092 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2093 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2094}
2095
2096void SelectionDAGLowering::visitUIToFP(User &I) {
2097 // UIToFP is never a no-op cast, no need to check
2098 SDOperand N = getValue(I.getOperand(0));
2099 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2100 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2101}
2102
2103void SelectionDAGLowering::visitSIToFP(User &I){
2104 // UIToFP is never a no-op cast, no need to check
2105 SDOperand N = getValue(I.getOperand(0));
2106 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2107 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2108}
2109
2110void SelectionDAGLowering::visitPtrToInt(User &I) {
2111 // What to do depends on the size of the integer and the size of the pointer.
2112 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002113 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002114 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002115 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002116 SDOperand Result;
2117 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2118 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2119 else
2120 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2121 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2122 setValue(&I, Result);
2123}
Chris Lattner1c08c712005-01-07 07:47:53 +00002124
Reid Spencer3da59db2006-11-27 01:05:10 +00002125void SelectionDAGLowering::visitIntToPtr(User &I) {
2126 // What to do depends on the size of the integer and the size of the pointer.
2127 // We can either truncate, zero extend, or no-op, accordingly.
2128 SDOperand N = getValue(I.getOperand(0));
2129 MVT::ValueType SrcVT = N.getValueType();
2130 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2131 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2132 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2133 else
2134 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2135 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2136}
2137
2138void SelectionDAGLowering::visitBitCast(User &I) {
2139 SDOperand N = getValue(I.getOperand(0));
2140 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002141 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002142 // This is a cast to a vector from something else.
2143 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002144 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002145 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2146 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2147 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2148 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002149 return;
2150 }
2151 MVT::ValueType SrcVT = N.getValueType();
2152 if (SrcVT == MVT::Vector) {
2153 // This is a cast from a vctor to something else.
2154 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00002155 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00002156 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002157 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002158
2159 // BitCast assures us that source and destination are the same size so this
2160 // is either a BIT_CONVERT or a no-op.
2161 if (DestVT != N.getValueType())
2162 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2163 else
2164 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002165}
2166
Chris Lattner2bbd8102006-03-29 00:11:43 +00002167void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002168 SDOperand InVec = getValue(I.getOperand(0));
2169 SDOperand InVal = getValue(I.getOperand(1));
2170 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2171 getValue(I.getOperand(2)));
2172
Chris Lattner2332b9f2006-03-19 01:17:20 +00002173 SDOperand Num = *(InVec.Val->op_end()-2);
2174 SDOperand Typ = *(InVec.Val->op_end()-1);
2175 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2176 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00002177}
2178
Chris Lattner2bbd8102006-03-29 00:11:43 +00002179void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002180 SDOperand InVec = getValue(I.getOperand(0));
2181 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2182 getValue(I.getOperand(1)));
2183 SDOperand Typ = *(InVec.Val->op_end()-1);
2184 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2185 TLI.getValueType(I.getType()), InVec, InIdx));
2186}
Chris Lattnerc7029802006-03-18 01:44:44 +00002187
Chris Lattner3e104b12006-04-08 04:15:24 +00002188void SelectionDAGLowering::visitShuffleVector(User &I) {
2189 SDOperand V1 = getValue(I.getOperand(0));
2190 SDOperand V2 = getValue(I.getOperand(1));
2191 SDOperand Mask = getValue(I.getOperand(2));
2192
2193 SDOperand Num = *(V1.Val->op_end()-2);
2194 SDOperand Typ = *(V2.Val->op_end()-1);
2195 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2196 V1, V2, Mask, Num, Typ));
2197}
2198
2199
Chris Lattner1c08c712005-01-07 07:47:53 +00002200void SelectionDAGLowering::visitGetElementPtr(User &I) {
2201 SDOperand N = getValue(I.getOperand(0));
2202 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002203
2204 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2205 OI != E; ++OI) {
2206 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002207 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002208 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002209 if (Field) {
2210 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002211 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002212 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00002213 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002214 }
2215 Ty = StTy->getElementType(Field);
2216 } else {
2217 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002218
Chris Lattner7c0104b2005-11-09 04:45:33 +00002219 // If this is a constant subscript, handle it quickly.
2220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002221 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002222 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00002223 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00002224 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2225 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002226 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002227
2228 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00002229 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002230 SDOperand IdxN = getValue(Idx);
2231
2232 // If the index is smaller or larger than intptr_t, truncate or extend
2233 // it.
2234 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002235 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002236 } else if (IdxN.getValueType() > N.getValueType())
2237 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2238
2239 // If this is a multiply by a power of two, turn it into a shl
2240 // immediately. This is a very common case.
2241 if (isPowerOf2_64(ElementSize)) {
2242 unsigned Amt = Log2_64(ElementSize);
2243 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002244 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002245 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2246 continue;
2247 }
2248
2249 SDOperand Scale = getIntPtrConstant(ElementSize);
2250 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2251 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002252 }
2253 }
2254 setValue(&I, N);
2255}
2256
2257void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2258 // If this is a fixed sized alloca in the entry block of the function,
2259 // allocate it statically on the stack.
2260 if (FuncInfo.StaticAllocaMap.count(&I))
2261 return; // getValue will auto-populate this.
2262
2263 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00002264 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002265 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002266 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002267 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002268
2269 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002270 MVT::ValueType IntPtr = TLI.getPointerTy();
2271 if (IntPtr < AllocSize.getValueType())
2272 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2273 else if (IntPtr > AllocSize.getValueType())
2274 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002275
Chris Lattner68cd65e2005-01-22 23:04:37 +00002276 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00002277 getIntPtrConstant(TySize));
2278
2279 // Handle alignment. If the requested alignment is less than or equal to the
2280 // stack alignment, ignore it and round the size of the allocation up to the
2281 // stack alignment size. If the size is greater than the stack alignment, we
2282 // note this in the DYNAMIC_STACKALLOC node.
2283 unsigned StackAlign =
2284 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2285 if (Align <= StackAlign) {
2286 Align = 0;
2287 // Add SA-1 to the size.
2288 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2289 getIntPtrConstant(StackAlign-1));
2290 // Mask out the low bits for alignment purposes.
2291 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2292 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2293 }
2294
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002295 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002296 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2297 MVT::Other);
2298 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002299 setValue(&I, DSA);
2300 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002301
2302 // Inform the Frame Information that we have just allocated a variable-sized
2303 // object.
2304 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2305}
2306
Chris Lattner1c08c712005-01-07 07:47:53 +00002307void SelectionDAGLowering::visitLoad(LoadInst &I) {
2308 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002309
Chris Lattnerd3948112005-01-17 22:19:26 +00002310 SDOperand Root;
2311 if (I.isVolatile())
2312 Root = getRoot();
2313 else {
2314 // Do not serialize non-volatile loads against each other.
2315 Root = DAG.getRoot();
2316 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002317
Evan Cheng466685d2006-10-09 20:57:25 +00002318 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002319 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002320}
2321
2322SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002323 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002324 bool isVolatile,
2325 unsigned Alignment) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002326 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002327 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00002328 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00002329 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2330 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002331 } else {
Christopher Lamb95c218a2007-04-22 23:15:30 +00002332 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2333 isVolatile, Alignment);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002334 }
Chris Lattnerd3948112005-01-17 22:19:26 +00002335
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002336 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002337 DAG.setRoot(L.getValue(1));
2338 else
2339 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002340
2341 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002342}
2343
2344
2345void SelectionDAGLowering::visitStore(StoreInst &I) {
2346 Value *SrcV = I.getOperand(0);
2347 SDOperand Src = getValue(SrcV);
2348 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002349 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002350 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002351}
2352
Chris Lattner0eade312006-03-24 02:22:33 +00002353/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2354/// access memory and has no other side effects at all.
2355static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2356#define GET_NO_MEMORY_INTRINSICS
2357#include "llvm/Intrinsics.gen"
2358#undef GET_NO_MEMORY_INTRINSICS
2359 return false;
2360}
2361
Chris Lattnere58a7802006-04-02 03:41:14 +00002362// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2363// have any side-effects or if it only reads memory.
2364static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2365#define GET_SIDE_EFFECT_INFO
2366#include "llvm/Intrinsics.gen"
2367#undef GET_SIDE_EFFECT_INFO
2368 return false;
2369}
2370
Chris Lattner0eade312006-03-24 02:22:33 +00002371/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2372/// node.
2373void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2374 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00002375 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002376 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002377
2378 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002379 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002380 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2381 if (OnlyLoad) {
2382 // We don't need to serialize loads against other loads.
2383 Ops.push_back(DAG.getRoot());
2384 } else {
2385 Ops.push_back(getRoot());
2386 }
2387 }
Chris Lattner0eade312006-03-24 02:22:33 +00002388
2389 // Add the intrinsic ID as an integer operand.
2390 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2391
2392 // Add all operands of the call to the operand list.
2393 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2394 SDOperand Op = getValue(I.getOperand(i));
2395
Reid Spencerac9dcb92007-02-15 03:39:18 +00002396 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00002397 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002398 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002399 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2400
2401 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2402 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2403 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2404 }
2405
2406 assert(TLI.isTypeLegal(Op.getValueType()) &&
2407 "Intrinsic uses a non-legal type?");
2408 Ops.push_back(Op);
2409 }
2410
2411 std::vector<MVT::ValueType> VTs;
2412 if (I.getType() != Type::VoidTy) {
2413 MVT::ValueType VT = TLI.getValueType(I.getType());
2414 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002415 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002416 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2417
2418 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2419 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2420 }
2421
2422 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2423 VTs.push_back(VT);
2424 }
2425 if (HasChain)
2426 VTs.push_back(MVT::Other);
2427
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002428 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2429
Chris Lattner0eade312006-03-24 02:22:33 +00002430 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002431 SDOperand Result;
2432 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002433 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2434 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002435 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002436 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2437 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002438 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002439 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2440 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002441
Chris Lattnere58a7802006-04-02 03:41:14 +00002442 if (HasChain) {
2443 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2444 if (OnlyLoad)
2445 PendingLoads.push_back(Chain);
2446 else
2447 DAG.setRoot(Chain);
2448 }
Chris Lattner0eade312006-03-24 02:22:33 +00002449 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002450 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00002451 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2452 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2453 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2454 DAG.getValueType(EVT));
2455 }
2456 setValue(&I, Result);
2457 }
2458}
2459
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002460/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2461/// we want to emit this as a call to a named external function, return the name
2462/// otherwise lower it and return null.
2463const char *
2464SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2465 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002466 default:
2467 // By default, turn this into a target intrinsic node.
2468 visitTargetIntrinsic(I, Intrinsic);
2469 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002470 case Intrinsic::vastart: visitVAStart(I); return 0;
2471 case Intrinsic::vaend: visitVAEnd(I); return 0;
2472 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002473 case Intrinsic::returnaddress:
2474 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2475 getValue(I.getOperand(1))));
2476 return 0;
2477 case Intrinsic::frameaddress:
2478 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2479 getValue(I.getOperand(1))));
2480 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002481 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002482 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002483 break;
2484 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002485 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002486 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002487 case Intrinsic::memcpy_i32:
2488 case Intrinsic::memcpy_i64:
2489 visitMemIntrinsic(I, ISD::MEMCPY);
2490 return 0;
2491 case Intrinsic::memset_i32:
2492 case Intrinsic::memset_i64:
2493 visitMemIntrinsic(I, ISD::MEMSET);
2494 return 0;
2495 case Intrinsic::memmove_i32:
2496 case Intrinsic::memmove_i64:
2497 visitMemIntrinsic(I, ISD::MEMMOVE);
2498 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002499
Chris Lattner86cb6432005-12-13 17:40:33 +00002500 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002501 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002502 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002503 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002504 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002505
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002506 Ops[0] = getRoot();
2507 Ops[1] = getValue(SPI.getLineValue());
2508 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002509
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002510 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002511 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002512 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2513
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002514 Ops[3] = DAG.getString(CompileUnit->getFileName());
2515 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002516
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002517 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002518 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002519
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002520 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002521 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002522 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002523 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002524 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002525 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2526 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002527 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002528 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002529 }
2530
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002531 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002532 }
2533 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002534 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002535 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002536 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2537 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002538 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002539 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002540 }
2541
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002542 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002543 }
2544 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002545 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002546 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002547 if (MMI && FSI.getSubprogram() &&
2548 MMI->Verify(FSI.getSubprogram())) {
2549 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002550 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002551 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002552 }
2553
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002554 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002555 }
2556 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002557 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002558 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002559 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002560 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002561 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002562 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002563 }
2564
2565 return 0;
2566 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002567
Jim Laskeyb180aa12007-02-21 22:53:45 +00002568 case Intrinsic::eh_exception: {
2569 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2570
Jim Laskey735b6f82007-02-22 15:38:06 +00002571 if (MMI) {
2572 // Add a label to mark the beginning of the landing pad. Deletion of the
2573 // landing pad can thus be detected via the MachineModuleInfo.
2574 unsigned LabelID = MMI->addLandingPad(CurMBB);
2575 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2576 DAG.getConstant(LabelID, MVT::i32)));
2577
2578 // Mark exception register as live in.
2579 unsigned Reg = TLI.getExceptionAddressRegister();
2580 if (Reg) CurMBB->addLiveIn(Reg);
2581
2582 // Insert the EXCEPTIONADDR instruction.
2583 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2584 SDOperand Ops[1];
2585 Ops[0] = DAG.getRoot();
2586 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2587 setValue(&I, Op);
2588 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002589 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002590 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002591 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002592 return 0;
2593 }
2594
Jim Laskey0b4711b2007-03-01 20:24:30 +00002595 case Intrinsic::eh_selector:
2596 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002597 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2598
Jim Laskey735b6f82007-02-22 15:38:06 +00002599 if (MMI) {
2600 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002601 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2602 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2603 isa<Function>(CE->getOperand(0)) &&
2604 "Personality should be a function");
2605 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey0b4711b2007-03-01 20:24:30 +00002606 if (Intrinsic == Intrinsic::eh_filter)
2607 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002608
Jim Laskey735b6f82007-02-22 15:38:06 +00002609 // Gather all the type infos for this landing pad and pass them along to
2610 // MachineModuleInfo.
2611 std::vector<GlobalVariable *> TyInfo;
2612 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Chris Lattner99f9a772007-04-27 01:20:11 +00002613 Constant *C = cast<Constant>(I.getOperand(i));
2614 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
2615 TyInfo.push_back(GV);
2616 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2617 assert(CE->getOpcode() == Instruction::BitCast &&
2618 isa<GlobalVariable>(CE->getOperand(0))
2619 && "TypeInfo must be a global variable or NULL");
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002620 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2621 } else {
Chris Lattner99f9a772007-04-27 01:20:11 +00002622 ConstantInt *CI = dyn_cast<ConstantInt>(C);
2623 assert(CI && CI->isNullValue() &&
2624 "TypeInfo must be a global variable or NULL");
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002625 TyInfo.push_back(NULL);
Jim Laskey735b6f82007-02-22 15:38:06 +00002626 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002627 }
2628 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2629
2630 // Mark exception selector register as live in.
2631 unsigned Reg = TLI.getExceptionSelectorRegister();
2632 if (Reg) CurMBB->addLiveIn(Reg);
2633
2634 // Insert the EHSELECTION instruction.
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002635 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002636 SDOperand Ops[2];
2637 Ops[0] = getValue(I.getOperand(1));
2638 Ops[1] = getRoot();
2639 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2640 setValue(&I, Op);
2641 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002642 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002643 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002644 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002645
2646 return 0;
2647 }
2648
2649 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002650 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002651
Jim Laskey735b6f82007-02-22 15:38:06 +00002652 if (MMI) {
2653 // Find the type id for the given typeinfo.
2654 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002655 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2656 if (CE && CE->getOpcode() == Instruction::BitCast &&
2657 isa<GlobalVariable>(CE->getOperand(0))) {
2658 GV = cast<GlobalVariable>(CE->getOperand(0));
2659 } else {
2660 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2661 assert(CI && CI->getZExtValue() == 0 &&
2662 "TypeInfo must be a global variable typeinfo or NULL");
2663 GV = NULL;
Jim Laskey735b6f82007-02-22 15:38:06 +00002664 }
2665
2666 unsigned TypeID = MMI->getTypeIDFor(GV);
2667 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002668 } else {
2669 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002670 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002671
2672 return 0;
2673 }
2674
Reid Spencer0b118202006-01-16 21:12:35 +00002675 case Intrinsic::sqrt_f32:
2676 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002677 setValue(&I, DAG.getNode(ISD::FSQRT,
2678 getValue(I.getOperand(1)).getValueType(),
2679 getValue(I.getOperand(1))));
2680 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002681 case Intrinsic::powi_f32:
2682 case Intrinsic::powi_f64:
2683 setValue(&I, DAG.getNode(ISD::FPOWI,
2684 getValue(I.getOperand(1)).getValueType(),
2685 getValue(I.getOperand(1)),
2686 getValue(I.getOperand(2))));
2687 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002688 case Intrinsic::pcmarker: {
2689 SDOperand Tmp = getValue(I.getOperand(1));
2690 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2691 return 0;
2692 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002693 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002694 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002695 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2696 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2697 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002698 setValue(&I, Tmp);
2699 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002700 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002701 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00002702 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002703 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00002704 assert(0 && "part_select intrinsic not implemented");
2705 abort();
2706 }
2707 case Intrinsic::part_set: {
2708 // Currently not implemented: just abort
2709 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00002710 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002711 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002712 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002713 setValue(&I, DAG.getNode(ISD::BSWAP,
2714 getValue(I.getOperand(1)).getValueType(),
2715 getValue(I.getOperand(1))));
2716 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002717 case Intrinsic::cttz: {
2718 SDOperand Arg = getValue(I.getOperand(1));
2719 MVT::ValueType Ty = Arg.getValueType();
2720 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2721 if (Ty < MVT::i32)
2722 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2723 else if (Ty > MVT::i32)
2724 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2725 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002726 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002727 }
2728 case Intrinsic::ctlz: {
2729 SDOperand Arg = getValue(I.getOperand(1));
2730 MVT::ValueType Ty = Arg.getValueType();
2731 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2732 if (Ty < MVT::i32)
2733 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2734 else if (Ty > MVT::i32)
2735 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2736 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002737 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002738 }
2739 case Intrinsic::ctpop: {
2740 SDOperand Arg = getValue(I.getOperand(1));
2741 MVT::ValueType Ty = Arg.getValueType();
2742 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2743 if (Ty < MVT::i32)
2744 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2745 else if (Ty > MVT::i32)
2746 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2747 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002748 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002749 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002750 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002751 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002752 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2753 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002754 setValue(&I, Tmp);
2755 DAG.setRoot(Tmp.getValue(1));
2756 return 0;
2757 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002758 case Intrinsic::stackrestore: {
2759 SDOperand Tmp = getValue(I.getOperand(1));
2760 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002761 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002762 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002763 case Intrinsic::prefetch:
2764 // FIXME: Currently discarding prefetches.
2765 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002766 }
2767}
2768
2769
Jim Laskey1da20a72007-02-23 21:45:01 +00002770void SelectionDAGLowering::LowerCallTo(Instruction &I,
2771 const Type *CalledValueTy,
2772 unsigned CallingConv,
2773 bool IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002774 SDOperand Callee, unsigned OpIdx) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002775 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002776 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer5694b6e2007-04-09 06:17:21 +00002777 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey735b6f82007-02-22 15:38:06 +00002778
2779 TargetLowering::ArgListTy Args;
2780 TargetLowering::ArgListEntry Entry;
2781 Args.reserve(I.getNumOperands());
2782 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2783 Value *Arg = I.getOperand(i);
2784 SDOperand ArgNode = getValue(Arg);
2785 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencer18da0722007-04-11 02:44:20 +00002786 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2787 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2788 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2789 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
Jim Laskey735b6f82007-02-22 15:38:06 +00002790 Args.push_back(Entry);
2791 }
2792
2793 std::pair<SDOperand,SDOperand> Result =
2794 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer18da0722007-04-11 02:44:20 +00002795 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey1da20a72007-02-23 21:45:01 +00002796 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002797 Callee, Args, DAG);
2798 if (I.getType() != Type::VoidTy)
2799 setValue(&I, Result.first);
2800 DAG.setRoot(Result.second);
2801}
2802
2803
Chris Lattner1c08c712005-01-07 07:47:53 +00002804void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002805 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002806 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002807 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002808 if (unsigned IID = F->getIntrinsicID()) {
2809 RenameFn = visitIntrinsicCall(I, IID);
2810 if (!RenameFn)
2811 return;
2812 } else { // Not an LLVM intrinsic.
2813 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002814 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2815 if (I.getNumOperands() == 3 && // Basic sanity checks.
2816 I.getOperand(1)->getType()->isFloatingPoint() &&
2817 I.getType() == I.getOperand(1)->getType() &&
2818 I.getType() == I.getOperand(2)->getType()) {
2819 SDOperand LHS = getValue(I.getOperand(1));
2820 SDOperand RHS = getValue(I.getOperand(2));
2821 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2822 LHS, RHS));
2823 return;
2824 }
2825 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002826 if (I.getNumOperands() == 2 && // Basic sanity checks.
2827 I.getOperand(1)->getType()->isFloatingPoint() &&
2828 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002829 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002830 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2831 return;
2832 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002833 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002834 if (I.getNumOperands() == 2 && // Basic sanity checks.
2835 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002836 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002837 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002838 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2839 return;
2840 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002841 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002842 if (I.getNumOperands() == 2 && // Basic sanity checks.
2843 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002844 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002845 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002846 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2847 return;
2848 }
2849 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002850 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002851 } else if (isa<InlineAsm>(I.getOperand(0))) {
2852 visitInlineAsm(I);
2853 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002854 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002855
Chris Lattner64e14b12005-01-08 22:48:57 +00002856 SDOperand Callee;
2857 if (!RenameFn)
2858 Callee = getValue(I.getOperand(0));
2859 else
2860 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002861
Jim Laskey1da20a72007-02-23 21:45:01 +00002862 LowerCallTo(I, I.getCalledValue()->getType(),
2863 I.getCallingConv(),
2864 I.isTailCall(),
2865 Callee,
2866 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002867}
2868
Jim Laskey735b6f82007-02-22 15:38:06 +00002869
Chris Lattner864635a2006-02-22 22:37:12 +00002870SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002871 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002872 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2873 Chain = Val.getValue(1);
2874 Flag = Val.getValue(2);
2875
2876 // If the result was expanded, copy from the top part.
2877 if (Regs.size() > 1) {
2878 assert(Regs.size() == 2 &&
2879 "Cannot expand to more than 2 elts yet!");
2880 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002881 Chain = Hi.getValue(1);
2882 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002883 if (DAG.getTargetLoweringInfo().isLittleEndian())
2884 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2885 else
2886 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002887 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002888
Chris Lattnercf752aa2006-06-08 18:22:48 +00002889 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002890 // appropriate type.
2891 if (RegVT == ValueVT)
2892 return Val;
2893
Chris Lattner5df99b32007-03-25 05:00:54 +00002894 if (MVT::isVector(RegVT)) {
2895 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2896 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2897 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2898 MVT::i32),
2899 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2900 }
2901
Chris Lattnercf752aa2006-06-08 18:22:48 +00002902 if (MVT::isInteger(RegVT)) {
2903 if (ValueVT < RegVT)
2904 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2905 else
2906 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002907 }
Chris Lattner5df99b32007-03-25 05:00:54 +00002908
2909 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2910 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002911}
2912
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002913/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2914/// specified value into the registers specified by this object. This uses
2915/// Chain/Flag as the input and updates them for the output Chain/Flag.
2916void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002917 SDOperand &Chain, SDOperand &Flag,
2918 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002919 if (Regs.size() == 1) {
2920 // If there is a single register and the types differ, this must be
2921 // a promotion.
2922 if (RegVT != ValueVT) {
Chris Lattner5df99b32007-03-25 05:00:54 +00002923 if (MVT::isVector(RegVT)) {
2924 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2925 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002926 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002927 if (RegVT < ValueVT)
2928 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2929 else
2930 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002931 } else if (MVT::isFloatingPoint(RegVT) &&
2932 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002933 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002934 } else if (MVT::getSizeInBits(RegVT) ==
2935 MVT::getSizeInBits(Val.getValueType())) {
2936 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2937 } else {
2938 assert(0 && "Unknown mismatch!");
2939 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002940 }
2941 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2942 Flag = Chain.getValue(1);
2943 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002944 std::vector<unsigned> R(Regs);
2945 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2946 std::reverse(R.begin(), R.end());
2947
2948 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002949 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002950 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002951 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002952 Flag = Chain.getValue(1);
2953 }
2954 }
2955}
Chris Lattner864635a2006-02-22 22:37:12 +00002956
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002957/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2958/// operand list. This adds the code marker and includes the number of
2959/// values added into it.
2960void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002961 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00002962 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2963 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002964 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2965 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2966}
Chris Lattner864635a2006-02-22 22:37:12 +00002967
2968/// isAllocatableRegister - If the specified register is safe to allocate,
2969/// i.e. it isn't a stack pointer or some other special register, return the
2970/// register class for the register. Otherwise, return null.
2971static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002972isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2973 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002974 MVT::ValueType FoundVT = MVT::Other;
2975 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002976 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2977 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002978 MVT::ValueType ThisVT = MVT::Other;
2979
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002980 const TargetRegisterClass *RC = *RCI;
2981 // If none of the the value types for this register class are valid, we
2982 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002983 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2984 I != E; ++I) {
2985 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002986 // If we have already found this register in a different register class,
2987 // choose the one with the largest VT specified. For example, on
2988 // PowerPC, we favor f64 register classes over f32.
2989 if (FoundVT == MVT::Other ||
2990 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2991 ThisVT = *I;
2992 break;
2993 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002994 }
2995 }
2996
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002997 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002998
Chris Lattner864635a2006-02-22 22:37:12 +00002999 // NOTE: This isn't ideal. In particular, this might allocate the
3000 // frame pointer in functions that need it (due to them not being taken
3001 // out of allocation, because a variable sized allocation hasn't been seen
3002 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003003 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3004 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003005 if (*I == Reg) {
3006 // We found a matching register class. Keep looking at others in case
3007 // we find one with larger registers that this physreg is also in.
3008 FoundRC = RC;
3009 FoundVT = ThisVT;
3010 break;
3011 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003012 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003013 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003014}
3015
Chris Lattner4e4b5762006-02-01 18:59:47 +00003016
Chris Lattner0c583402007-04-28 20:49:53 +00003017namespace {
3018/// AsmOperandInfo - This contains information for each constraint that we are
3019/// lowering.
3020struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3021 /// ConstraintCode - This contains the actual string for the code, like "m".
3022 std::string ConstraintCode;
Chris Lattner2a600be2007-04-28 21:01:43 +00003023
3024 /// ConstraintType - Information about the constraint code, e.g. Register,
3025 /// RegisterClass, Memory, Other, Unknown.
3026 TargetLowering::ConstraintType ConstraintType;
Chris Lattner0c583402007-04-28 20:49:53 +00003027
3028 /// CallOperand/CallOperandval - If this is the result output operand or a
3029 /// clobber, this is null, otherwise it is the incoming operand to the
3030 /// CallInst. This gets modified as the asm is processed.
3031 SDOperand CallOperand;
3032 Value *CallOperandVal;
3033
3034 /// ConstraintVT - The ValueType for the operand value.
3035 MVT::ValueType ConstraintVT;
3036
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003037 /// AssignedRegs - If this is a register or register class operand, this
3038 /// contains the set of register corresponding to the operand.
3039 RegsForValue AssignedRegs;
3040
Chris Lattner0c583402007-04-28 20:49:53 +00003041 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattner2a600be2007-04-28 21:01:43 +00003042 : InlineAsm::ConstraintInfo(info),
3043 ConstraintType(TargetLowering::C_Unknown),
Chris Lattner0c583402007-04-28 20:49:53 +00003044 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3045 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003046
3047 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003048
3049 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3050 /// busy in OutputRegs/InputRegs.
3051 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3052 std::set<unsigned> &OutputRegs,
3053 std::set<unsigned> &InputRegs) const {
3054 if (isOutReg)
3055 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3056 if (isInReg)
3057 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3058 }
Chris Lattner0c583402007-04-28 20:49:53 +00003059};
3060} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003061
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003062/// getConstraintGenerality - Return an integer indicating how general CT is.
3063static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3064 switch (CT) {
3065 default: assert(0 && "Unknown constraint type!");
3066 case TargetLowering::C_Other:
3067 case TargetLowering::C_Unknown:
3068 return 0;
3069 case TargetLowering::C_Register:
3070 return 1;
3071 case TargetLowering::C_RegisterClass:
3072 return 2;
3073 case TargetLowering::C_Memory:
3074 return 3;
3075 }
3076}
3077
3078void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3079 assert(!Codes.empty() && "Must have at least one constraint");
3080
3081 std::string *Current = &Codes[0];
3082 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3083 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3084 ConstraintCode = *Current;
3085 ConstraintType = CurType;
3086 return;
3087 }
3088
3089 unsigned CurGenerality = getConstraintGenerality(CurType);
3090
3091 // If we have multiple constraints, try to pick the most general one ahead
3092 // of time. This isn't a wonderful solution, but handles common cases.
3093 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3094 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3095 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3096 if (ThisGenerality > CurGenerality) {
3097 // This constraint letter is more general than the previous one,
3098 // use it.
3099 CurType = ThisType;
3100 Current = &Codes[j];
3101 CurGenerality = ThisGenerality;
3102 }
3103 }
3104
3105 ConstraintCode = *Current;
3106 ConstraintType = CurType;
3107}
3108
3109
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003110void SelectionDAGLowering::
3111GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003112 std::set<unsigned> &OutputRegs,
3113 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003114 // Compute whether this value requires an input register, an output register,
3115 // or both.
3116 bool isOutReg = false;
3117 bool isInReg = false;
3118 switch (OpInfo.Type) {
3119 case InlineAsm::isOutput:
3120 isOutReg = true;
3121
3122 // If this is an early-clobber output, or if there is an input
3123 // constraint that matches this, we need to reserve the input register
3124 // so no other inputs allocate to it.
3125 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3126 break;
3127 case InlineAsm::isInput:
3128 isInReg = true;
3129 isOutReg = false;
3130 break;
3131 case InlineAsm::isClobber:
3132 isOutReg = true;
3133 isInReg = true;
3134 break;
3135 }
3136
3137
3138 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003139 std::vector<unsigned> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003140
3141 // If this is a constraint for a single physreg, or a constraint for a
3142 // register class, find it.
3143 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3144 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3145 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003146
3147 unsigned NumRegs = 1;
3148 if (OpInfo.ConstraintVT != MVT::Other)
3149 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3150 MVT::ValueType RegVT;
3151 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3152
Chris Lattnerbf996f12007-04-30 17:29:31 +00003153
3154 // If this is a constraint for a specific physical register, like {r17},
3155 // assign it now.
3156 if (PhysReg.first) {
3157 if (OpInfo.ConstraintVT == MVT::Other)
3158 ValueVT = *PhysReg.second->vt_begin();
3159
3160 // Get the actual register value type. This is important, because the user
3161 // may have asked for (e.g.) the AX register in i32 type. We need to
3162 // remember that AX is actually i16 to get the right extension.
3163 RegVT = *PhysReg.second->vt_begin();
3164
3165 // This is a explicit reference to a physical register.
3166 Regs.push_back(PhysReg.first);
3167
3168 // If this is an expanded reference, add the rest of the regs to Regs.
3169 if (NumRegs != 1) {
3170 TargetRegisterClass::iterator I = PhysReg.second->begin();
3171 TargetRegisterClass::iterator E = PhysReg.second->end();
3172 for (; *I != PhysReg.first; ++I)
3173 assert(I != E && "Didn't find reg!");
3174
3175 // Already added the first reg.
3176 --NumRegs; ++I;
3177 for (; NumRegs; --NumRegs, ++I) {
3178 assert(I != E && "Ran out of registers to allocate!");
3179 Regs.push_back(*I);
3180 }
3181 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003182 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3183 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3184 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003185 }
3186
3187 // Otherwise, if this was a reference to an LLVM register class, create vregs
3188 // for this reference.
3189 std::vector<unsigned> RegClassRegs;
3190 if (PhysReg.second) {
3191 // If this is an early clobber or tied register, our regalloc doesn't know
3192 // how to maintain the constraint. If it isn't, go ahead and create vreg
3193 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003194 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3195 // If there is some other early clobber and this is an input register,
3196 // then we are forced to pre-allocate the input reg so it doesn't
3197 // conflict with the earlyclobber.
3198 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003199 RegVT = *PhysReg.second->vt_begin();
3200
3201 if (OpInfo.ConstraintVT == MVT::Other)
3202 ValueVT = RegVT;
3203
3204 // Create the appropriate number of virtual registers.
3205 SSARegMap *RegMap = MF.getSSARegMap();
3206 for (; NumRegs; --NumRegs)
3207 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3208
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003209 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3210 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3211 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003212 }
3213
3214 // Otherwise, we can't allocate it. Let the code below figure out how to
3215 // maintain these constraints.
3216 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3217
3218 } else {
3219 // This is a reference to a register class that doesn't directly correspond
3220 // to an LLVM register class. Allocate NumRegs consecutive, available,
3221 // registers from the class.
3222 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3223 OpInfo.ConstraintVT);
3224 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003225
Chris Lattnerbf996f12007-04-30 17:29:31 +00003226 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3227 unsigned NumAllocated = 0;
3228 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3229 unsigned Reg = RegClassRegs[i];
3230 // See if this register is available.
3231 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3232 (isInReg && InputRegs.count(Reg))) { // Already used.
3233 // Make sure we find consecutive registers.
3234 NumAllocated = 0;
3235 continue;
3236 }
3237
3238 // Check to see if this register is allocatable (i.e. don't give out the
3239 // stack pointer).
3240 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3241 if (!RC) {
3242 // Make sure we find consecutive registers.
3243 NumAllocated = 0;
3244 continue;
3245 }
3246
3247 // Okay, this register is good, we can use it.
3248 ++NumAllocated;
3249
3250 // If we allocated enough consecutive registers, succeed.
3251 if (NumAllocated == NumRegs) {
3252 unsigned RegStart = (i-NumAllocated)+1;
3253 unsigned RegEnd = i+1;
3254 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003255 for (unsigned i = RegStart; i != RegEnd; ++i)
3256 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003257
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003258 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3259 OpInfo.ConstraintVT);
3260 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3261 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003262 }
3263 }
3264
3265 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003266 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003267}
3268
3269
Chris Lattnerce7518c2006-01-26 22:24:51 +00003270/// visitInlineAsm - Handle a call to an InlineAsm object.
3271///
3272void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3273 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattnerce7518c2006-01-26 22:24:51 +00003274
Chris Lattner0c583402007-04-28 20:49:53 +00003275 /// ConstraintOperands - Information about all of the constraints.
3276 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003277
3278 SDOperand Chain = getRoot();
3279 SDOperand Flag;
3280
Chris Lattner4e4b5762006-02-01 18:59:47 +00003281 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003282
Chris Lattner0c583402007-04-28 20:49:53 +00003283 // Do a prepass over the constraints, canonicalizing them, and building up the
3284 // ConstraintOperands list.
3285 std::vector<InlineAsm::ConstraintInfo>
3286 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003287
3288 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3289 // constraint. If so, we can't let the register allocator allocate any input
3290 // registers, because it will not know to avoid the earlyclobbered output reg.
3291 bool SawEarlyClobber = false;
3292
3293 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattner0c583402007-04-28 20:49:53 +00003294 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3295 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3296 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3297
Chris Lattner0c583402007-04-28 20:49:53 +00003298 MVT::ValueType OpVT = MVT::Other;
3299
3300 // Compute the value type for each operand.
3301 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003302 case InlineAsm::isOutput:
Chris Lattner0c583402007-04-28 20:49:53 +00003303 if (!OpInfo.isIndirect) {
3304 // The return value of the call is this value. As such, there is no
3305 // corresponding argument.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003306 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3307 OpVT = TLI.getValueType(I.getType());
3308 } else {
Chris Lattner0c583402007-04-28 20:49:53 +00003309 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003310 }
3311 break;
3312 case InlineAsm::isInput:
Chris Lattner0c583402007-04-28 20:49:53 +00003313 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003314 break;
3315 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003316 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003317 break;
3318 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003319
Chris Lattner0c583402007-04-28 20:49:53 +00003320 // If this is an input or an indirect output, process the call argument.
3321 if (OpInfo.CallOperandVal) {
3322 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3323 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner6995cf62007-04-29 18:58:03 +00003324 // If this is an indirect operand, the operand is a pointer to the
3325 // accessed type.
3326 if (OpInfo.isIndirect)
3327 OpTy = cast<PointerType>(OpTy)->getElementType();
3328
3329 // If OpTy is not a first-class value, it may be a struct/union that we
3330 // can tile with integers.
3331 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3332 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3333 switch (BitSize) {
3334 default: break;
3335 case 1:
3336 case 8:
3337 case 16:
3338 case 32:
3339 case 64:
3340 OpTy = IntegerType::get(BitSize);
3341 break;
3342 }
Chris Lattner0c583402007-04-28 20:49:53 +00003343 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003344
3345 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003346 }
3347
3348 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003349
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003350 // Compute the constraint code and ConstraintType to use.
3351 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattner0c583402007-04-28 20:49:53 +00003352
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003353 // Keep track of whether we see an earlyclobber.
3354 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003355
3356 // If this is a memory input, and if the operand is not indirect, do what we
3357 // need to to provide an address for the memory input.
3358 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3359 !OpInfo.isIndirect) {
3360 assert(OpInfo.Type == InlineAsm::isInput &&
3361 "Can only indirectify direct input operands!");
3362
3363 // Memory operands really want the address of the value. If we don't have
3364 // an indirect input, put it in the constpool if we can, otherwise spill
3365 // it to a stack slot.
3366
3367 // If the operand is a float, integer, or vector constant, spill to a
3368 // constant pool entry to get its address.
3369 Value *OpVal = OpInfo.CallOperandVal;
3370 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3371 isa<ConstantVector>(OpVal)) {
3372 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3373 TLI.getPointerTy());
3374 } else {
3375 // Otherwise, create a stack slot and emit a store to it before the
3376 // asm.
3377 const Type *Ty = OpVal->getType();
3378 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3379 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3380 MachineFunction &MF = DAG.getMachineFunction();
3381 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3382 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3383 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3384 OpInfo.CallOperand = StackSlot;
3385 }
3386
3387 // There is no longer a Value* corresponding to this operand.
3388 OpInfo.CallOperandVal = 0;
3389 // It is now an indirect operand.
3390 OpInfo.isIndirect = true;
3391 }
3392
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003393 // If this constraint is for a specific register, allocate it before
3394 // anything else.
3395 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3396 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003397 }
Chris Lattner0c583402007-04-28 20:49:53 +00003398 ConstraintInfos.clear();
3399
3400
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003401 // Second pass - Loop over all of the operands, assigning virtual or physregs
3402 // to registerclass operands.
3403 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3404 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3405
3406 // C_Register operands have already been allocated, Other/Memory don't need
3407 // to be.
3408 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3409 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3410 }
3411
Chris Lattner0c583402007-04-28 20:49:53 +00003412 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3413 std::vector<SDOperand> AsmNodeOperands;
3414 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3415 AsmNodeOperands.push_back(
3416 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3417
Chris Lattner2cc2f662006-02-01 01:28:23 +00003418
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003419 // Loop over all of the inputs, copying the operand values into the
3420 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003421 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003422
Chris Lattner0c583402007-04-28 20:49:53 +00003423 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3424 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3425
3426 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3427 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003428
Chris Lattner0c583402007-04-28 20:49:53 +00003429 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003430 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003431 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3432 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003433 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003434 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003435
Chris Lattner22873462006-02-27 23:45:39 +00003436 // Add information to the INLINEASM node to know about this output.
3437 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3438 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003439 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003440 break;
3441 }
3442
Chris Lattner2a600be2007-04-28 21:01:43 +00003443 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003444
Chris Lattner864635a2006-02-22 22:37:12 +00003445 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003446 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003447 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003448 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003449 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003450 exit(1);
3451 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003452
Chris Lattner0c583402007-04-28 20:49:53 +00003453 if (!OpInfo.isIndirect) {
3454 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003455 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003456 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003457 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003458 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003459 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003460 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003461 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003462 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003463
3464 // Add information to the INLINEASM node to know that this register is
3465 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003466 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3467 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003468 break;
3469 }
3470 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003471 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003472
Chris Lattner0c583402007-04-28 20:49:53 +00003473 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003474 // If this is required to match an output register we have already set,
3475 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003476 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003477
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003478 // Scan until we find the definition we already emitted of this operand.
3479 // When we find it, create a RegsForValue operand.
3480 unsigned CurOp = 2; // The first operand.
3481 for (; OperandNo; --OperandNo) {
3482 // Advance to the next operand.
3483 unsigned NumOps =
3484 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003485 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3486 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003487 "Skipped past definitions?");
3488 CurOp += (NumOps>>3)+1;
3489 }
3490
3491 unsigned NumOps =
3492 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003493 if ((NumOps & 7) == 2 /*REGDEF*/) {
3494 // Add NumOps>>3 registers to MatchedRegs.
3495 RegsForValue MatchedRegs;
3496 MatchedRegs.ValueVT = InOperandVal.getValueType();
3497 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3498 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3499 unsigned Reg =
3500 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3501 MatchedRegs.Regs.push_back(Reg);
3502 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003503
Chris Lattner527fae12007-02-01 01:21:12 +00003504 // Use the produced MatchedRegs object to
3505 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3506 TLI.getPointerTy());
3507 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3508 break;
3509 } else {
3510 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3511 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003512 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003513 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003514
Chris Lattner2a600be2007-04-28 21:01:43 +00003515 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00003516 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003517 "Don't know how to handle indirect other inputs yet!");
3518
Chris Lattner53069fb2006-10-31 19:41:18 +00003519 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattner0c583402007-04-28 20:49:53 +00003520 OpInfo.ConstraintCode[0],
3521 DAG);
Chris Lattner53069fb2006-10-31 19:41:18 +00003522 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00003523 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003524 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003525 exit(1);
3526 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003527
3528 // Add information to the INLINEASM node to know about this input.
3529 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3530 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3531 AsmNodeOperands.push_back(InOperandVal);
3532 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00003533 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003534 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00003535 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3536 "Memory operands expect pointer values");
3537
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003538 // Add information to the INLINEASM node to know about this input.
3539 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3540 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3541 AsmNodeOperands.push_back(InOperandVal);
3542 break;
3543 }
3544
Chris Lattner2a600be2007-04-28 21:01:43 +00003545 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3546 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3547 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00003548 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003549 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003550
3551 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003552 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3553 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003554
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003555 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3556 TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003557
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003558 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3559 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003560 break;
3561 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003562 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003563 // Add the clobbered value to the operand list, so that the register
3564 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003565 if (!OpInfo.AssignedRegs.Regs.empty())
3566 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3567 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003568 break;
3569 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003570 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003571 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003572
3573 // Finish up input operands.
3574 AsmNodeOperands[0] = Chain;
3575 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3576
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003577 Chain = DAG.getNode(ISD::INLINEASM,
3578 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003579 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003580 Flag = Chain.getValue(1);
3581
Chris Lattner6656dd12006-01-31 02:03:41 +00003582 // If this asm returns a register value, copy the result from that register
3583 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003584 if (!RetValRegs.Regs.empty()) {
3585 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3586
3587 // If the result of the inline asm is a vector, it may have the wrong
3588 // width/num elts. Make sure to convert it to the right type with
3589 // vbit_convert.
3590 if (Val.getValueType() == MVT::Vector) {
3591 const VectorType *VTy = cast<VectorType>(I.getType());
3592 unsigned DesiredNumElts = VTy->getNumElements();
3593 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3594
3595 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3596 DAG.getConstant(DesiredNumElts, MVT::i32),
3597 DAG.getValueType(DesiredEltVT));
3598 }
3599
3600 setValue(&I, Val);
3601 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003602
Chris Lattner6656dd12006-01-31 02:03:41 +00003603 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3604
3605 // Process indirect outputs, first output all of the flagged copies out of
3606 // physregs.
3607 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003608 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003609 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00003610 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3611 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003612 }
3613
3614 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003615 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003616 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00003617 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003618 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003619 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003620 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003621 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3622 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003623 DAG.setRoot(Chain);
3624}
3625
3626
Chris Lattner1c08c712005-01-07 07:47:53 +00003627void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3628 SDOperand Src = getValue(I.getOperand(0));
3629
3630 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003631
3632 if (IntPtr < Src.getValueType())
3633 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3634 else if (IntPtr > Src.getValueType())
3635 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003636
3637 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003638 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003639 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3640 Src, getIntPtrConstant(ElementSize));
3641
Reid Spencer47857812006-12-31 05:55:36 +00003642 TargetLowering::ArgListTy Args;
3643 TargetLowering::ArgListEntry Entry;
3644 Entry.Node = Src;
3645 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003646 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003647
3648 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003649 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003650 DAG.getExternalSymbol("malloc", IntPtr),
3651 Args, DAG);
3652 setValue(&I, Result.first); // Pointers always fit in registers
3653 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003654}
3655
3656void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003657 TargetLowering::ArgListTy Args;
3658 TargetLowering::ArgListEntry Entry;
3659 Entry.Node = getValue(I.getOperand(0));
3660 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003661 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003662 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003663 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003664 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003665 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3666 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003667}
3668
Chris Lattner025c39b2005-08-26 20:54:47 +00003669// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3670// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3671// instructions are special in various ways, which require special support to
3672// insert. The specified MachineInstr is created but not inserted into any
3673// basic blocks, and the scheduler passes ownership of it to this method.
3674MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3675 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003676 cerr << "If a target marks an instruction with "
3677 << "'usesCustomDAGSchedInserter', it must implement "
3678 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003679 abort();
3680 return 0;
3681}
3682
Chris Lattner39ae3622005-01-09 00:00:49 +00003683void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003684 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3685 getValue(I.getOperand(1)),
3686 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003687}
3688
3689void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003690 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3691 getValue(I.getOperand(0)),
3692 DAG.getSrcValue(I.getOperand(0)));
3693 setValue(&I, V);
3694 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003695}
3696
3697void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003698 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3699 getValue(I.getOperand(1)),
3700 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003701}
3702
3703void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003704 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3705 getValue(I.getOperand(1)),
3706 getValue(I.getOperand(2)),
3707 DAG.getSrcValue(I.getOperand(1)),
3708 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003709}
3710
Evan Chengb15974a2006-12-12 07:27:38 +00003711/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3712/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3713static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3714 unsigned &i, SelectionDAG &DAG,
3715 TargetLowering &TLI) {
3716 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3717 return SDOperand(Arg, i++);
3718
3719 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3720 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3721 if (NumVals == 1) {
3722 return DAG.getNode(ISD::BIT_CONVERT, VT,
3723 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3724 } else if (NumVals == 2) {
3725 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3726 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3727 if (!TLI.isLittleEndian())
3728 std::swap(Lo, Hi);
3729 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3730 } else {
3731 // Value scalarized into many values. Unimp for now.
3732 assert(0 && "Cannot expand i64 -> i16 yet!");
3733 }
3734 return SDOperand();
3735}
3736
Chris Lattnerfdfded52006-04-12 16:20:43 +00003737/// TargetLowering::LowerArguments - This is the default LowerArguments
3738/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003739/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3740/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003741std::vector<SDOperand>
3742TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003743 const FunctionType *FTy = F.getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +00003744 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003745 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3746 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003747 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003748 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3749 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3750
3751 // Add one result value for each formal argument.
3752 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003753 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003754 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3755 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003756 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003757 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003758 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003759 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003760
Chris Lattnerddf53e42007-02-26 02:56:58 +00003761 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3762 // that is zero extended!
Reid Spencer18da0722007-04-11 02:44:20 +00003763 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003764 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer18da0722007-04-11 02:44:20 +00003765 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003766 Flags |= ISD::ParamFlags::SExt;
Reid Spencer18da0722007-04-11 02:44:20 +00003767 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003768 Flags |= ISD::ParamFlags::InReg;
Reid Spencer18da0722007-04-11 02:44:20 +00003769 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003770 Flags |= ISD::ParamFlags::StructReturn;
3771 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003772
Chris Lattnerfdfded52006-04-12 16:20:43 +00003773 switch (getTypeAction(VT)) {
3774 default: assert(0 && "Unknown type action!");
3775 case Legal:
3776 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003777 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003778 break;
3779 case Promote:
3780 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003781 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003782 break;
3783 case Expand:
3784 if (VT != MVT::Vector) {
3785 // If this is a large integer, it needs to be broken up into small
3786 // integers. Figure out what the destination type is and how many small
3787 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003788 MVT::ValueType NVT = getTypeToExpandTo(VT);
3789 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003790 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003791 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003792 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003793 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003794 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3795 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003796 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3797 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003798 } else {
3799 // Otherwise, this is a vector type. We only support legal vectors
3800 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003801 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3802 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003803
Chris Lattnerfdfded52006-04-12 16:20:43 +00003804 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003805 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003806 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3807 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3808 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003809 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003810 } else {
3811 assert(0 && "Don't support illegal by-val vector arguments yet!");
3812 }
3813 }
3814 break;
3815 }
3816 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003817
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003818 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003819
3820 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003821 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3822 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003823 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003824
3825 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003826
3827 // Set up the return result vector.
3828 Ops.clear();
3829 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003830 unsigned Idx = 1;
3831 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3832 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003833 MVT::ValueType VT = getValueType(I->getType());
3834
3835 switch (getTypeAction(VT)) {
3836 default: assert(0 && "Unknown type action!");
3837 case Legal:
3838 Ops.push_back(SDOperand(Result, i++));
3839 break;
3840 case Promote: {
3841 SDOperand Op(Result, i++);
3842 if (MVT::isInteger(VT)) {
Reid Spencer18da0722007-04-11 02:44:20 +00003843 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003844 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3845 DAG.getValueType(VT));
Reid Spencer18da0722007-04-11 02:44:20 +00003846 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003847 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3848 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003849 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3850 } else {
3851 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3852 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3853 }
3854 Ops.push_back(Op);
3855 break;
3856 }
3857 case Expand:
3858 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003859 // If this is a large integer or a floating point node that needs to be
3860 // expanded, it needs to be reassembled from small integers. Figure out
3861 // what the source elt type is and how many small integers it is.
3862 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003863 } else {
3864 // Otherwise, this is a vector type. We only support legal vectors
3865 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003866 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003867 unsigned NumElems = PTy->getNumElements();
3868 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003869
Chris Lattnerfdfded52006-04-12 16:20:43 +00003870 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003871 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003872 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003873 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003874 SDOperand N = SDOperand(Result, i++);
3875 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003876 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3877 DAG.getConstant(NumElems, MVT::i32),
3878 DAG.getValueType(getValueType(EltTy)));
3879 Ops.push_back(N);
3880 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003881 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003882 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003883 }
3884 }
3885 break;
3886 }
3887 }
3888 return Ops;
3889}
3890
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003891
Evan Chengb15974a2006-12-12 07:27:38 +00003892/// ExpandScalarCallArgs - Recursively expand call argument node by
3893/// bit_converting it or extract a pair of elements from the larger node.
3894static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003895 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003896 SmallVector<SDOperand, 32> &Ops,
3897 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003898 TargetLowering &TLI,
3899 bool isFirst = true) {
3900
Evan Chengb15974a2006-12-12 07:27:38 +00003901 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003902 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003903 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003904 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3905 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003906 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003907 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003908 return;
3909 }
3910
3911 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3912 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3913 if (NumVals == 1) {
3914 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003915 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003916 } else if (NumVals == 2) {
3917 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3918 DAG.getConstant(0, TLI.getPointerTy()));
3919 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3920 DAG.getConstant(1, TLI.getPointerTy()));
3921 if (!TLI.isLittleEndian())
3922 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003923 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3924 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003925 } else {
3926 // Value scalarized into many values. Unimp for now.
3927 assert(0 && "Cannot expand i64 -> i16 yet!");
3928 }
3929}
3930
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003931/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3932/// implementation, which just inserts an ISD::CALL node, which is later custom
3933/// lowered by the target to something concrete. FIXME: When all targets are
3934/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3935std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003936TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3937 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003938 unsigned CallingConv, bool isTailCall,
3939 SDOperand Callee,
3940 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003941 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003942 Ops.push_back(Chain); // Op#0 - Chain
3943 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3944 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3945 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3946 Ops.push_back(Callee);
3947
3948 // Handle all of the outgoing arguments.
3949 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003950 MVT::ValueType VT = getValueType(Args[i].Ty);
3951 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003952 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003953 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003954 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003955
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003956 if (Args[i].isSExt)
3957 Flags |= ISD::ParamFlags::SExt;
3958 if (Args[i].isZExt)
3959 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003960 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003961 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003962 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003963 Flags |= ISD::ParamFlags::StructReturn;
3964 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003965
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003966 switch (getTypeAction(VT)) {
3967 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003968 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003969 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003970 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003971 break;
3972 case Promote:
3973 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003974 unsigned ExtOp;
3975 if (Args[i].isSExt)
3976 ExtOp = ISD::SIGN_EXTEND;
3977 else if (Args[i].isZExt)
3978 ExtOp = ISD::ZERO_EXTEND;
3979 else
3980 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003981 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3982 } else {
3983 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3984 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3985 }
3986 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003987 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003988 break;
3989 case Expand:
3990 if (VT != MVT::Vector) {
3991 // If this is a large integer, it needs to be broken down into small
3992 // integers. Figure out what the source elt type is and how many small
3993 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003994 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003995 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003996 // Otherwise, this is a vector type. We only support legal vectors
3997 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003998 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003999 unsigned NumElems = PTy->getNumElements();
4000 const Type *EltTy = PTy->getElementType();
4001
4002 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004003 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00004004 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00004005 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00004006 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00004007 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4008 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004009 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00004010 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00004011 assert(0 && "Don't support illegal by-val vector call args yet!");
4012 abort();
4013 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004014 }
4015 break;
4016 }
4017 }
4018
4019 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00004020 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004021
4022 if (RetTy != Type::VoidTy) {
4023 MVT::ValueType VT = getValueType(RetTy);
4024 switch (getTypeAction(VT)) {
4025 default: assert(0 && "Unknown type action!");
4026 case Legal:
4027 RetTys.push_back(VT);
4028 break;
4029 case Promote:
4030 RetTys.push_back(getTypeToTransformTo(VT));
4031 break;
4032 case Expand:
4033 if (VT != MVT::Vector) {
4034 // If this is a large integer, it needs to be reassembled from small
4035 // integers. Figure out what the source elt type is and how many small
4036 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00004037 MVT::ValueType NVT = getTypeToExpandTo(VT);
4038 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004039 for (unsigned i = 0; i != NumVals; ++i)
4040 RetTys.push_back(NVT);
4041 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00004042 // Otherwise, this is a vector type. We only support legal vectors
4043 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004044 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00004045 unsigned NumElems = PTy->getNumElements();
4046 const Type *EltTy = PTy->getElementType();
4047
4048 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004049 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00004050 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4051 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4052 RetTys.push_back(TVT);
4053 } else {
4054 assert(0 && "Don't support illegal by-val vector call results yet!");
4055 abort();
4056 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004057 }
4058 }
4059 }
4060
4061 RetTys.push_back(MVT::Other); // Always has a chain.
4062
4063 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004064 SDOperand Res = DAG.getNode(ISD::CALL,
4065 DAG.getVTList(&RetTys[0], RetTys.size()),
4066 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004067
4068 // This returns a pair of operands. The first element is the
4069 // return value for the function (if RetTy is not VoidTy). The second
4070 // element is the outgoing token chain.
4071 SDOperand ResVal;
4072 if (RetTys.size() != 1) {
4073 MVT::ValueType VT = getValueType(RetTy);
4074 if (RetTys.size() == 2) {
4075 ResVal = Res;
4076
4077 // If this value was promoted, truncate it down.
4078 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00004079 if (VT == MVT::Vector) {
Chris Lattner5df99b32007-03-25 05:00:54 +00004080 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerda098e72006-05-16 23:39:44 +00004081 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004082 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4083 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00004084
4085 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004086 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00004087 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00004088 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00004089 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4090 // "N x PTyElementVT" MVT::Vector type.
4091 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00004092 DAG.getConstant(NumElems, MVT::i32),
4093 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00004094 } else {
4095 abort();
4096 }
4097 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00004098 unsigned AssertOp = ISD::AssertSext;
4099 if (!RetTyIsSigned)
4100 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004101 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4102 DAG.getValueType(VT));
4103 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4104 } else {
4105 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00004106 if (getTypeAction(VT) == Expand)
4107 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4108 else
4109 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004110 }
4111 }
4112 } else if (RetTys.size() == 3) {
4113 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4114 Res.getValue(0), Res.getValue(1));
4115
4116 } else {
4117 assert(0 && "Case not handled yet!");
4118 }
4119 }
4120
4121 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4122}
4123
Chris Lattner50381b62005-05-14 05:50:48 +00004124SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004125 assert(0 && "LowerOperation not implemented for this target!");
4126 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004127 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004128}
4129
Nate Begeman0aed7842006-01-28 03:14:31 +00004130SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4131 SelectionDAG &DAG) {
4132 assert(0 && "CustomPromoteOperation not implemented for this target!");
4133 abort();
4134 return SDOperand();
4135}
4136
Evan Cheng74d0aa92006-02-15 21:59:04 +00004137/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004138/// operand.
4139static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004140 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004141 MVT::ValueType CurVT = VT;
4142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4143 uint64_t Val = C->getValue() & 255;
4144 unsigned Shift = 8;
4145 while (CurVT != MVT::i8) {
4146 Val = (Val << Shift) | Val;
4147 Shift <<= 1;
4148 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004149 }
4150 return DAG.getConstant(Val, VT);
4151 } else {
4152 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4153 unsigned Shift = 8;
4154 while (CurVT != MVT::i8) {
4155 Value =
4156 DAG.getNode(ISD::OR, VT,
4157 DAG.getNode(ISD::SHL, VT, Value,
4158 DAG.getConstant(Shift, MVT::i8)), Value);
4159 Shift <<= 1;
4160 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004161 }
4162
4163 return Value;
4164 }
4165}
4166
Evan Cheng74d0aa92006-02-15 21:59:04 +00004167/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4168/// used when a memcpy is turned into a memset when the source is a constant
4169/// string ptr.
4170static SDOperand getMemsetStringVal(MVT::ValueType VT,
4171 SelectionDAG &DAG, TargetLowering &TLI,
4172 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004173 uint64_t Val = 0;
4174 unsigned MSB = getSizeInBits(VT) / 8;
4175 if (TLI.isLittleEndian())
4176 Offset = Offset + MSB - 1;
4177 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004178 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004179 Offset += TLI.isLittleEndian() ? -1 : 1;
4180 }
4181 return DAG.getConstant(Val, VT);
4182}
4183
Evan Cheng1db92f92006-02-14 08:22:34 +00004184/// getMemBasePlusOffset - Returns base and offset node for the
4185static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4186 SelectionDAG &DAG, TargetLowering &TLI) {
4187 MVT::ValueType VT = Base.getValueType();
4188 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4189}
4190
Evan Chengc4f8eee2006-02-14 20:12:38 +00004191/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004192/// to replace the memset / memcpy is below the threshold. It also returns the
4193/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004194static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4195 unsigned Limit, uint64_t Size,
4196 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004197 MVT::ValueType VT;
4198
4199 if (TLI.allowsUnalignedMemoryAccesses()) {
4200 VT = MVT::i64;
4201 } else {
4202 switch (Align & 7) {
4203 case 0:
4204 VT = MVT::i64;
4205 break;
4206 case 4:
4207 VT = MVT::i32;
4208 break;
4209 case 2:
4210 VT = MVT::i16;
4211 break;
4212 default:
4213 VT = MVT::i8;
4214 break;
4215 }
4216 }
4217
Evan Cheng80e89d72006-02-14 09:11:59 +00004218 MVT::ValueType LVT = MVT::i64;
4219 while (!TLI.isTypeLegal(LVT))
4220 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4221 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004222
Evan Cheng80e89d72006-02-14 09:11:59 +00004223 if (VT > LVT)
4224 VT = LVT;
4225
Evan Chengdea72452006-02-14 23:05:54 +00004226 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004227 while (Size != 0) {
4228 unsigned VTSize = getSizeInBits(VT) / 8;
4229 while (VTSize > Size) {
4230 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004231 VTSize >>= 1;
4232 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004233 assert(MVT::isInteger(VT));
4234
4235 if (++NumMemOps > Limit)
4236 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004237 MemOps.push_back(VT);
4238 Size -= VTSize;
4239 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004240
4241 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004242}
4243
Chris Lattner7041ee32005-01-11 05:56:49 +00004244void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004245 SDOperand Op1 = getValue(I.getOperand(1));
4246 SDOperand Op2 = getValue(I.getOperand(2));
4247 SDOperand Op3 = getValue(I.getOperand(3));
4248 SDOperand Op4 = getValue(I.getOperand(4));
4249 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4250 if (Align == 0) Align = 1;
4251
4252 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4253 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004254
4255 // Expand memset / memcpy to a series of load / store ops
4256 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004257 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004258 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004259 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004260 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004261 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4262 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004263 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004264 unsigned Offset = 0;
4265 for (unsigned i = 0; i < NumMemOps; i++) {
4266 MVT::ValueType VT = MemOps[i];
4267 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004268 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004269 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004270 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004271 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004272 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004273 Offset += VTSize;
4274 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004275 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004276 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004277 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004278 case ISD::MEMCPY: {
4279 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4280 Size->getValue(), Align, TLI)) {
4281 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004282 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004283 GlobalAddressSDNode *G = NULL;
4284 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004285 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004286
4287 if (Op2.getOpcode() == ISD::GlobalAddress)
4288 G = cast<GlobalAddressSDNode>(Op2);
4289 else if (Op2.getOpcode() == ISD::ADD &&
4290 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4291 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4292 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004293 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004294 }
4295 if (G) {
4296 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004297 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004298 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004299 if (!Str.empty()) {
4300 CopyFromStr = true;
4301 SrcOff += SrcDelta;
4302 }
4303 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004304 }
4305
Evan Chengc080d6f2006-02-15 01:54:51 +00004306 for (unsigned i = 0; i < NumMemOps; i++) {
4307 MVT::ValueType VT = MemOps[i];
4308 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004309 SDOperand Value, Chain, Store;
4310
Evan Chengcffbb512006-02-16 23:11:42 +00004311 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004312 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4313 Chain = getRoot();
4314 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004315 DAG.getStore(Chain, Value,
4316 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004317 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004318 } else {
4319 Value = DAG.getLoad(VT, getRoot(),
4320 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00004321 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004322 Chain = Value.getValue(1);
4323 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004324 DAG.getStore(Chain, Value,
4325 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004326 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004327 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004328 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004329 SrcOff += VTSize;
4330 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004331 }
4332 }
4333 break;
4334 }
4335 }
4336
4337 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004338 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4339 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004340 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004341 }
4342 }
4343
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004344 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00004345}
4346
Chris Lattner7041ee32005-01-11 05:56:49 +00004347//===----------------------------------------------------------------------===//
4348// SelectionDAGISel code
4349//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004350
4351unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4352 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4353}
4354
Chris Lattner495a0b52005-08-17 06:37:43 +00004355void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004356 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004357 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004358}
Chris Lattner1c08c712005-01-07 07:47:53 +00004359
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004360
Chris Lattnerbad7f482006-10-28 19:22:10 +00004361
Chris Lattner1c08c712005-01-07 07:47:53 +00004362bool SelectionDAGISel::runOnFunction(Function &Fn) {
4363 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4364 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004365 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004366
4367 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4368
4369 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4370 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004371
Evan Chengad2070c2007-02-10 02:43:39 +00004372 // Add function live-ins to entry block live-in set.
4373 BasicBlock *EntryBB = &Fn.getEntryBlock();
4374 BB = FuncInfo.MBBMap[EntryBB];
4375 if (!MF.livein_empty())
4376 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4377 E = MF.livein_end(); I != E; ++I)
4378 BB->addLiveIn(I->first);
4379
Chris Lattner1c08c712005-01-07 07:47:53 +00004380 return true;
4381}
4382
Chris Lattner571e4342006-10-27 21:36:01 +00004383SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4384 unsigned Reg) {
4385 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004386 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004387 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004388 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004389
4390 // If this type is not legal, we must make sure to not create an invalid
4391 // register use.
4392 MVT::ValueType SrcVT = Op.getValueType();
4393 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004394 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004395 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004396 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004397 // Handle copies from generic vectors to registers.
4398 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004399 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004400 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004401
Chris Lattner70c2a612006-03-31 02:06:56 +00004402 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4403 // MVT::Vector type.
4404 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4405 DAG.getConstant(NE, MVT::i32),
4406 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004407
Chris Lattner70c2a612006-03-31 02:06:56 +00004408 // Loop over all of the elements of the resultant vector,
4409 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4410 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004411 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004412 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004413 for (unsigned i = 0; i != NE; ++i) {
4414 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004415 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004416 if (PTyElementVT == PTyLegalElementVT) {
4417 // Elements are legal.
4418 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4419 } else if (PTyLegalElementVT > PTyElementVT) {
4420 // Elements are promoted.
4421 if (MVT::isFloatingPoint(PTyLegalElementVT))
4422 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4423 else
4424 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4425 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4426 } else {
4427 // Elements are expanded.
4428 // The src value is expanded into multiple registers.
4429 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004430 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004431 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004432 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004433 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4434 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4435 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004436 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004437 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4438 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004439 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004440 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004441 if (MVT::isFloatingPoint(SrcVT))
4442 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4443 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004444 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004445 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004446 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004447 DestVT = TLI.getTypeToExpandTo(SrcVT);
4448 unsigned NumVals = TLI.getNumElements(SrcVT);
4449 if (NumVals == 1)
4450 return DAG.getCopyToReg(getRoot(), Reg,
4451 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4452 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004453 // The src value is expanded into multiple registers.
4454 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004455 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004456 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004457 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004458 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004459 return DAG.getCopyToReg(Op, Reg+1, Hi);
4460 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004461}
4462
Chris Lattner068a81e2005-01-17 17:15:02 +00004463void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004464LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004465 std::vector<SDOperand> &UnorderedChains) {
4466 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004467 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004468 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004469 SDOperand OldRoot = SDL.DAG.getRoot();
4470 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004471
Chris Lattnerbf209482005-10-30 19:42:35 +00004472 unsigned a = 0;
4473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4474 AI != E; ++AI, ++a)
4475 if (!AI->use_empty()) {
4476 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004477
Chris Lattnerbf209482005-10-30 19:42:35 +00004478 // If this argument is live outside of the entry block, insert a copy from
4479 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004480 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4481 if (VMI != FuncInfo.ValueMap.end()) {
4482 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004483 UnorderedChains.push_back(Copy);
4484 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004485 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004486
Chris Lattnerbf209482005-10-30 19:42:35 +00004487 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004488 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004489 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004490}
4491
Chris Lattner1c08c712005-01-07 07:47:53 +00004492void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4493 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004494 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004495 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004496
4497 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004498
Chris Lattnerbf209482005-10-30 19:42:35 +00004499 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004500 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004501 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004502
4503 BB = FuncInfo.MBBMap[LLVMBB];
4504 SDL.setCurrentBasicBlock(BB);
4505
4506 // Lower all of the non-terminator instructions.
4507 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4508 I != E; ++I)
4509 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004510
4511 // Lower call part of invoke.
4512 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4513 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004514
Chris Lattner1c08c712005-01-07 07:47:53 +00004515 // Ensure that all instructions which are used outside of their defining
4516 // blocks are available as virtual registers.
4517 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004518 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004519 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004520 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004521 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004522 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004523 }
4524
4525 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4526 // ensure constants are generated when needed. Remember the virtual registers
4527 // that need to be added to the Machine PHI nodes as input. We cannot just
4528 // directly add them, because expansion might result in multiple MBB's for one
4529 // BB. As such, the start of the BB might correspond to a different MBB than
4530 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004531 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004532 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004533
4534 // Emit constants only once even if used by multiple PHI nodes.
4535 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004536
Chris Lattner8c494ab2006-10-27 23:50:33 +00004537 // Vector bool would be better, but vector<bool> is really slow.
4538 std::vector<unsigned char> SuccsHandled;
4539 if (TI->getNumSuccessors())
4540 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4541
Chris Lattner1c08c712005-01-07 07:47:53 +00004542 // Check successor nodes PHI nodes that expect a constant to be available from
4543 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004544 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4545 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004546 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004547 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004548
Chris Lattner8c494ab2006-10-27 23:50:33 +00004549 // If this terminator has multiple identical successors (common for
4550 // switches), only handle each succ once.
4551 unsigned SuccMBBNo = SuccMBB->getNumber();
4552 if (SuccsHandled[SuccMBBNo]) continue;
4553 SuccsHandled[SuccMBBNo] = true;
4554
4555 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004556 PHINode *PN;
4557
4558 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4559 // nodes and Machine PHI nodes, but the incoming operands have not been
4560 // emitted yet.
4561 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004562 (PN = dyn_cast<PHINode>(I)); ++I) {
4563 // Ignore dead phi's.
4564 if (PN->use_empty()) continue;
4565
4566 unsigned Reg;
4567 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004568
Chris Lattner8c494ab2006-10-27 23:50:33 +00004569 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4570 unsigned &RegOut = ConstantsOut[C];
4571 if (RegOut == 0) {
4572 RegOut = FuncInfo.CreateRegForValue(C);
4573 UnorderedChains.push_back(
4574 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004575 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004576 Reg = RegOut;
4577 } else {
4578 Reg = FuncInfo.ValueMap[PHIOp];
4579 if (Reg == 0) {
4580 assert(isa<AllocaInst>(PHIOp) &&
4581 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4582 "Didn't codegen value into a register!??");
4583 Reg = FuncInfo.CreateRegForValue(PHIOp);
4584 UnorderedChains.push_back(
4585 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004586 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004587 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004588
4589 // Remember that this register needs to added to the machine PHI node as
4590 // the input for this MBB.
4591 MVT::ValueType VT = TLI.getValueType(PN->getType());
4592 unsigned NumElements;
4593 if (VT != MVT::Vector)
4594 NumElements = TLI.getNumElements(VT);
4595 else {
4596 MVT::ValueType VT1,VT2;
4597 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004598 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004599 VT1, VT2);
4600 }
4601 for (unsigned i = 0, e = NumElements; i != e; ++i)
4602 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4603 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004604 }
4605 ConstantsOut.clear();
4606
Chris Lattnerddb870b2005-01-13 17:59:43 +00004607 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004608 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004609 SDOperand Root = SDL.getRoot();
4610 if (Root.getOpcode() != ISD::EntryToken) {
4611 unsigned i = 0, e = UnorderedChains.size();
4612 for (; i != e; ++i) {
4613 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4614 if (UnorderedChains[i].Val->getOperand(0) == Root)
4615 break; // Don't add the root if we already indirectly depend on it.
4616 }
4617
4618 if (i == e)
4619 UnorderedChains.push_back(Root);
4620 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004621 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4622 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004623 }
4624
Chris Lattner1c08c712005-01-07 07:47:53 +00004625 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004626 if (Invoke) {
4627 // Just the branch part of invoke.
4628 SDL.visitInvoke(*Invoke, true);
4629 } else {
4630 SDL.visit(*LLVMBB->getTerminator());
4631 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004632
Nate Begemanf15485a2006-03-27 01:32:24 +00004633 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004634 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004635 SwitchCases.clear();
4636 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004637 JTCases.clear();
4638 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004639 BitTestCases.clear();
4640 BitTestCases = SDL.BitTestCases;
4641
Chris Lattnera651cf62005-01-17 19:43:36 +00004642 // Make sure the root of the DAG is up-to-date.
4643 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004644}
4645
Nate Begemanf15485a2006-03-27 01:32:24 +00004646void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004647 // Get alias analysis for load/store combining.
4648 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4649
Chris Lattneraf21d552005-10-10 16:47:10 +00004650 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004651 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004652
Bill Wendling832171c2006-12-07 20:04:42 +00004653 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004654 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004655
Chris Lattner1c08c712005-01-07 07:47:53 +00004656 // Second step, hack on the DAG until it only uses operations and types that
4657 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004658 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004659
Bill Wendling832171c2006-12-07 20:04:42 +00004660 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004661 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004662
Chris Lattneraf21d552005-10-10 16:47:10 +00004663 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004664 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004665
Evan Chenga9c20912006-01-21 02:32:06 +00004666 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004667
Chris Lattnera33ef482005-03-30 01:10:47 +00004668 // Third, instruction select all of the operations to machine code, adding the
4669 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004670 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004671
Bill Wendling832171c2006-12-07 20:04:42 +00004672 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004673 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004674}
Chris Lattner1c08c712005-01-07 07:47:53 +00004675
Nate Begemanf15485a2006-03-27 01:32:24 +00004676void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4677 FunctionLoweringInfo &FuncInfo) {
4678 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4679 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004680 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004681 CurDAG = &DAG;
4682
4683 // First step, lower LLVM code to some DAG. This DAG may use operations and
4684 // types that are not supported by the target.
4685 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4686
4687 // Second step, emit the lowered DAG as machine code.
4688 CodeGenAndEmitDAG(DAG);
4689 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004690
4691 DOUT << "Total amount of phi nodes to update: "
4692 << PHINodesToUpdate.size() << "\n";
4693 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4694 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4695 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004696
Chris Lattnera33ef482005-03-30 01:10:47 +00004697 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004698 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004699 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004700 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4701 MachineInstr *PHI = PHINodesToUpdate[i].first;
4702 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4703 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004704 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004705 PHI->addMachineBasicBlockOperand(BB);
4706 }
4707 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004708 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004709
4710 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4711 // Lower header first, if it wasn't already lowered
4712 if (!BitTestCases[i].Emitted) {
4713 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4714 CurDAG = &HSDAG;
4715 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4716 // Set the current basic block to the mbb we wish to insert the code into
4717 BB = BitTestCases[i].Parent;
4718 HSDL.setCurrentBasicBlock(BB);
4719 // Emit the code
4720 HSDL.visitBitTestHeader(BitTestCases[i]);
4721 HSDAG.setRoot(HSDL.getRoot());
4722 CodeGenAndEmitDAG(HSDAG);
4723 }
4724
4725 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4726 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4727 CurDAG = &BSDAG;
4728 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4729 // Set the current basic block to the mbb we wish to insert the code into
4730 BB = BitTestCases[i].Cases[j].ThisBB;
4731 BSDL.setCurrentBasicBlock(BB);
4732 // Emit the code
4733 if (j+1 != ej)
4734 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4735 BitTestCases[i].Reg,
4736 BitTestCases[i].Cases[j]);
4737 else
4738 BSDL.visitBitTestCase(BitTestCases[i].Default,
4739 BitTestCases[i].Reg,
4740 BitTestCases[i].Cases[j]);
4741
4742
4743 BSDAG.setRoot(BSDL.getRoot());
4744 CodeGenAndEmitDAG(BSDAG);
4745 }
4746
4747 // Update PHI Nodes
4748 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4749 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4750 MachineBasicBlock *PHIBB = PHI->getParent();
4751 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4752 "This is not a machine PHI node that we are updating!");
4753 // This is "default" BB. We have two jumps to it. From "header" BB and
4754 // from last "case" BB.
4755 if (PHIBB == BitTestCases[i].Default) {
4756 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4757 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikov8085bcf2007-04-13 06:53:51 +00004758 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004759 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4760 }
4761 // One of "cases" BB.
4762 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4763 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4764 if (cBB->succ_end() !=
4765 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4766 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4767 PHI->addMachineBasicBlockOperand(cBB);
4768 }
4769 }
4770 }
4771 }
4772
Nate Begeman9453eea2006-04-23 06:26:20 +00004773 // If the JumpTable record is filled in, then we need to emit a jump table.
4774 // Updating the PHI nodes is tricky in this case, since we need to determine
4775 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004776 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4777 // Lower header first, if it wasn't already lowered
4778 if (!JTCases[i].first.Emitted) {
4779 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4780 CurDAG = &HSDAG;
4781 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4782 // Set the current basic block to the mbb we wish to insert the code into
4783 BB = JTCases[i].first.HeaderBB;
4784 HSDL.setCurrentBasicBlock(BB);
4785 // Emit the code
4786 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4787 HSDAG.setRoot(HSDL.getRoot());
4788 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004789 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004790
4791 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4792 CurDAG = &JSDAG;
4793 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004794 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004795 BB = JTCases[i].second.MBB;
4796 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004797 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004798 JSDL.visitJumpTable(JTCases[i].second);
4799 JSDAG.setRoot(JSDL.getRoot());
4800 CodeGenAndEmitDAG(JSDAG);
4801
Nate Begeman37efe672006-04-22 18:53:45 +00004802 // Update PHI Nodes
4803 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4804 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4805 MachineBasicBlock *PHIBB = PHI->getParent();
4806 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4807 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004808 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004809 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004810 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004811 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004812 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004813 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004814 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004815 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004816 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004817 }
4818 }
Nate Begeman37efe672006-04-22 18:53:45 +00004819 }
4820
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004821 // If the switch block involved a branch to one of the actual successors, we
4822 // need to update PHI nodes in that block.
4823 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4824 MachineInstr *PHI = PHINodesToUpdate[i].first;
4825 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4826 "This is not a machine PHI node that we are updating!");
4827 if (BB->isSuccessor(PHI->getParent())) {
4828 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4829 PHI->addMachineBasicBlockOperand(BB);
4830 }
4831 }
4832
Nate Begemanf15485a2006-03-27 01:32:24 +00004833 // If we generated any switch lowering information, build and codegen any
4834 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004835 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004836 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004837 CurDAG = &SDAG;
4838 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004839
Nate Begemanf15485a2006-03-27 01:32:24 +00004840 // Set the current basic block to the mbb we wish to insert the code into
4841 BB = SwitchCases[i].ThisBB;
4842 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004843
Nate Begemanf15485a2006-03-27 01:32:24 +00004844 // Emit the code
4845 SDL.visitSwitchCase(SwitchCases[i]);
4846 SDAG.setRoot(SDL.getRoot());
4847 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004848
4849 // Handle any PHI nodes in successors of this chunk, as if we were coming
4850 // from the original BB before switch expansion. Note that PHI nodes can
4851 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4852 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004853 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004854 for (MachineBasicBlock::iterator Phi = BB->begin();
4855 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4856 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4857 for (unsigned pn = 0; ; ++pn) {
4858 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4859 if (PHINodesToUpdate[pn].first == Phi) {
4860 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4861 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4862 break;
4863 }
4864 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004865 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004866
4867 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004868 if (BB == SwitchCases[i].FalseBB)
4869 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004870
4871 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004872 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004873 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004874 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004875 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004876 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004877}
Evan Chenga9c20912006-01-21 02:32:06 +00004878
Jim Laskey13ec7022006-08-01 14:21:23 +00004879
Evan Chenga9c20912006-01-21 02:32:06 +00004880//===----------------------------------------------------------------------===//
4881/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4882/// target node in the graph.
4883void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4884 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004885
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004886 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004887
4888 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004889 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004890 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004891 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004892
Jim Laskey9ff542f2006-08-01 18:29:48 +00004893 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004894 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004895 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004896}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004897
Chris Lattner03fc53c2006-03-06 00:22:00 +00004898
Jim Laskey9ff542f2006-08-01 18:29:48 +00004899HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4900 return new HazardRecognizer();
4901}
4902
Chris Lattner75548062006-10-11 03:58:02 +00004903//===----------------------------------------------------------------------===//
4904// Helper functions used by the generated instruction selector.
4905//===----------------------------------------------------------------------===//
4906// Calls to these methods are generated by tblgen.
4907
4908/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4909/// the dag combiner simplified the 255, we still want to match. RHS is the
4910/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4911/// specified in the .td file (e.g. 255).
4912bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4913 int64_t DesiredMaskS) {
4914 uint64_t ActualMask = RHS->getValue();
4915 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4916
4917 // If the actual mask exactly matches, success!
4918 if (ActualMask == DesiredMask)
4919 return true;
4920
4921 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4922 if (ActualMask & ~DesiredMask)
4923 return false;
4924
4925 // Otherwise, the DAG Combiner may have proven that the value coming in is
4926 // either already zero or is not demanded. Check for known zero input bits.
4927 uint64_t NeededMask = DesiredMask & ~ActualMask;
4928 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4929 return true;
4930
4931 // TODO: check to see if missing bits are just not demanded.
4932
4933 // Otherwise, this pattern doesn't match.
4934 return false;
4935}
4936
4937/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4938/// the dag combiner simplified the 255, we still want to match. RHS is the
4939/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4940/// specified in the .td file (e.g. 255).
4941bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4942 int64_t DesiredMaskS) {
4943 uint64_t ActualMask = RHS->getValue();
4944 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4945
4946 // If the actual mask exactly matches, success!
4947 if (ActualMask == DesiredMask)
4948 return true;
4949
4950 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4951 if (ActualMask & ~DesiredMask)
4952 return false;
4953
4954 // Otherwise, the DAG Combiner may have proven that the value coming in is
4955 // either already zero or is not demanded. Check for known zero input bits.
4956 uint64_t NeededMask = DesiredMask & ~ActualMask;
4957
4958 uint64_t KnownZero, KnownOne;
4959 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4960
4961 // If all the missing bits in the or are already known to be set, match!
4962 if ((NeededMask & KnownOne) == NeededMask)
4963 return true;
4964
4965 // TODO: check to see if missing bits are just not demanded.
4966
4967 // Otherwise, this pattern doesn't match.
4968 return false;
4969}
4970
Jim Laskey9ff542f2006-08-01 18:29:48 +00004971
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004972/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4973/// by tblgen. Others should not call it.
4974void SelectionDAGISel::
4975SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4976 std::vector<SDOperand> InOps;
4977 std::swap(InOps, Ops);
4978
4979 Ops.push_back(InOps[0]); // input chain.
4980 Ops.push_back(InOps[1]); // input asm string.
4981
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004982 unsigned i = 2, e = InOps.size();
4983 if (InOps[e-1].getValueType() == MVT::Flag)
4984 --e; // Don't process a flag operand if it is here.
4985
4986 while (i != e) {
4987 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4988 if ((Flags & 7) != 4 /*MEM*/) {
4989 // Just skip over this operand, copying the operands verbatim.
4990 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4991 i += (Flags >> 3) + 1;
4992 } else {
4993 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4994 // Otherwise, this is a memory operand. Ask the target to select it.
4995 std::vector<SDOperand> SelOps;
4996 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004997 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004998 exit(1);
4999 }
5000
5001 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005002 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005003 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005004 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005005 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5006 i += 2;
5007 }
5008 }
5009
5010 // Add the flag input back if present.
5011 if (e != InOps.size())
5012 Ops.push_back(InOps.back());
5013}
Devang Patel794fd752007-05-01 21:15:47 +00005014
Devang Patel3e15bf32007-05-02 21:39:20 +00005015const char SelectionDAGISel::ID = 0;