blob: cfdf6d0ea571bd9ecc602ae72fb5f5a6268d816a [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());
Dan Gohmanb55757e2007-05-18 17:52:13 +0000313 MVT::ValueType VecTy = MVT::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;
Dan Gohmanb55757e2007-05-18 17:52:13 +0000320 VecTy = MVT::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,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000532 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
533 MachineBasicBlock *LandingPad = NULL);
534
Chris Lattner1c08c712005-01-07 07:47:53 +0000535 // Terminator instructions.
536 void visitRet(ReturnInst &I);
537 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000538 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000539 void visitUnreachable(UnreachableInst &I) { /* noop */ }
540
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000541 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000542 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000543 CaseRecVector& WorkList,
544 Value* SV,
545 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000546 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000547 CaseRecVector& WorkList,
548 Value* SV,
549 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000550 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000551 CaseRecVector& WorkList,
552 Value* SV,
553 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000554 bool handleBitTestsSwitchCase(CaseRec& CR,
555 CaseRecVector& WorkList,
556 Value* SV,
557 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000558 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000559 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
560 void visitBitTestCase(MachineBasicBlock* NextMBB,
561 unsigned Reg,
562 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000563 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000564 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
565 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000566
Chris Lattner1c08c712005-01-07 07:47:53 +0000567 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000568 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000569 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000570 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000571
Reid Spencer24d6da52007-01-21 00:29:26 +0000572 void visitScalarBinary(User &I, unsigned OpCode);
573 void visitVectorBinary(User &I, unsigned OpCode);
574 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000575 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000576 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000577 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000578 visitVectorBinary(I, ISD::VADD);
579 else if (I.getType()->isFloatingPoint())
580 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000581 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000582 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000583 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000584 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000585 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000586 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000587 visitVectorBinary(I, ISD::VMUL);
588 else if (I.getType()->isFloatingPoint())
589 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000590 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000591 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000592 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000593 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
594 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
595 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
596 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
597 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
598 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
599 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
600 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
601 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
602 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000603 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
604 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000605 void visitICmp(User &I);
606 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000607 // Visit the conversion instructions
608 void visitTrunc(User &I);
609 void visitZExt(User &I);
610 void visitSExt(User &I);
611 void visitFPTrunc(User &I);
612 void visitFPExt(User &I);
613 void visitFPToUI(User &I);
614 void visitFPToSI(User &I);
615 void visitUIToFP(User &I);
616 void visitSIToFP(User &I);
617 void visitPtrToInt(User &I);
618 void visitIntToPtr(User &I);
619 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000620
Chris Lattner2bbd8102006-03-29 00:11:43 +0000621 void visitExtractElement(User &I);
622 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000623 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000624
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000626 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000627
628 void visitMalloc(MallocInst &I);
629 void visitFree(FreeInst &I);
630 void visitAlloca(AllocaInst &I);
631 void visitLoad(LoadInst &I);
632 void visitStore(StoreInst &I);
633 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
634 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000635 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000636 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000637 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000638
Chris Lattner1c08c712005-01-07 07:47:53 +0000639 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000640 void visitVAArg(VAArgInst &I);
641 void visitVAEnd(CallInst &I);
642 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000643
Chris Lattner7041ee32005-01-11 05:56:49 +0000644 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000645
646 void visitUserOp1(Instruction &I) {
647 assert(0 && "UserOp1 should not exist at instruction selection time!");
648 abort();
649 }
650 void visitUserOp2(Instruction &I) {
651 assert(0 && "UserOp2 should not exist at instruction selection time!");
652 abort();
653 }
654};
655} // end namespace llvm
656
Chris Lattner199862b2006-03-16 19:57:50 +0000657SDOperand SelectionDAGLowering::getValue(const Value *V) {
658 SDOperand &N = NodeMap[V];
659 if (N.Val) return N;
660
661 const Type *VTy = V->getType();
662 MVT::ValueType VT = TLI.getValueType(VTy);
663 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
664 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
665 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000666 SDOperand N1 = NodeMap[V];
667 assert(N1.Val && "visit didn't populate the ValueMap!");
668 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000669 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
670 return N = DAG.getGlobalAddress(GV, VT);
671 } else if (isa<ConstantPointerNull>(C)) {
672 return N = DAG.getConstant(0, TLI.getPointerTy());
673 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000674 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000675 return N = DAG.getNode(ISD::UNDEF, VT);
676
Chris Lattnerb2827b02006-03-19 00:52:58 +0000677 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000678 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000679 unsigned NumElements = PTy->getNumElements();
680 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
681
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000682 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000683 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
684
685 // Create a VConstant node with generic Vector type.
686 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
687 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000688 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
689 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000690 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
691 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000692 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000693 unsigned NumElements = PTy->getNumElements();
694 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000695
696 // Now that we know the number and type of the elements, push a
697 // Constant or ConstantFP node onto the ops list for each element of
698 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000699 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000700 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000701 for (unsigned i = 0; i != NumElements; ++i)
702 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000703 } else {
704 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
705 SDOperand Op;
706 if (MVT::isFloatingPoint(PVT))
707 Op = DAG.getConstantFP(0, PVT);
708 else
709 Op = DAG.getConstant(0, PVT);
710 Ops.assign(NumElements, Op);
711 }
712
Chris Lattnerb2827b02006-03-19 00:52:58 +0000713 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000714 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
715 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000716 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
717 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000718 } else {
719 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000720 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000721 }
722 }
723
724 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
725 std::map<const AllocaInst*, int>::iterator SI =
726 FuncInfo.StaticAllocaMap.find(AI);
727 if (SI != FuncInfo.StaticAllocaMap.end())
728 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
729 }
730
Chris Lattner251db182007-02-25 18:40:32 +0000731 unsigned InReg = FuncInfo.ValueMap[V];
732 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000733
734 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000735 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000736 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000737 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000738 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000739 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
740 unsigned NumVals = TLI.getNumElements(VT);
741 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
742 if (NumVals == 1)
743 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
744 else {
745 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
746 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
747 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
748 }
749 } else {
750 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
751 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
752 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
753 N = MVT::isFloatingPoint(VT)
754 ? DAG.getNode(ISD::FP_ROUND, VT, N)
755 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000756 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000757 } else {
758 // Otherwise, if this is a vector, make it available as a generic vector
759 // here.
760 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000761 const VectorType *PTy = cast<VectorType>(VTy);
762 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000763 PTyLegalElementVT);
764
765 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000766 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000767 if (PTyElementVT == PTyLegalElementVT) {
768 // If the value types are legal, just VBUILD the CopyFromReg nodes.
769 for (unsigned i = 0; i != NE; ++i)
770 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
771 PTyElementVT));
772 } else if (PTyElementVT < PTyLegalElementVT) {
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000773 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner70c2a612006-03-31 02:06:56 +0000774 for (unsigned i = 0; i != NE; ++i) {
775 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
776 PTyElementVT);
777 if (MVT::isFloatingPoint(PTyElementVT))
778 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
779 else
780 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
781 Ops.push_back(Op);
782 }
783 } else {
784 // If the register was expanded, use BUILD_PAIR.
785 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
786 for (unsigned i = 0; i != NE/2; ++i) {
787 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
788 PTyElementVT);
789 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
790 PTyElementVT);
791 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
792 }
793 }
794
795 Ops.push_back(DAG.getConstant(NE, MVT::i32));
796 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000797 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000798
799 // Finally, use a VBIT_CONVERT to make this available as the appropriate
800 // vector type.
801 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
802 DAG.getConstant(PTy->getNumElements(),
803 MVT::i32),
804 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000805 }
806
807 return N;
808}
809
810
Chris Lattner1c08c712005-01-07 07:47:53 +0000811void SelectionDAGLowering::visitRet(ReturnInst &I) {
812 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000813 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000814 return;
815 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000816 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000817 NewValues.push_back(getRoot());
818 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
819 SDOperand RetOp = getValue(I.getOperand(i));
820
821 // If this is an integer return value, we need to promote it ourselves to
822 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
823 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000824 // FIXME: C calling convention requires the return type to be promoted to
825 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000826 if (MVT::isInteger(RetOp.getValueType()) &&
827 RetOp.getValueType() < MVT::i64) {
828 MVT::ValueType TmpVT;
829 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
830 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
831 else
832 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000833 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +0000834 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerbcca3402007-01-03 16:49:33 +0000835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000836 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000837 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000838 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencer47857812006-12-31 05:55:36 +0000839 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000840 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000841 }
842 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000843 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000844 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000845 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
846 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000847}
848
Chris Lattner571e4342006-10-27 21:36:01 +0000849/// ExportFromCurrentBlock - If this condition isn't known to be exported from
850/// the current basic block, add it to ValueMap now so that we'll get a
851/// CopyTo/FromReg.
852void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
853 // No need to export constants.
854 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
855
856 // Already exported?
857 if (FuncInfo.isExportedInst(V)) return;
858
859 unsigned Reg = FuncInfo.InitializeRegForValue(V);
860 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
861}
862
Chris Lattner8c494ab2006-10-27 23:50:33 +0000863bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
864 const BasicBlock *FromBB) {
865 // The operands of the setcc have to be in this block. We don't know
866 // how to export them from some other block.
867 if (Instruction *VI = dyn_cast<Instruction>(V)) {
868 // Can export from current BB.
869 if (VI->getParent() == FromBB)
870 return true;
871
872 // Is already exported, noop.
873 return FuncInfo.isExportedInst(V);
874 }
875
876 // If this is an argument, we can export it if the BB is the entry block or
877 // if it is already exported.
878 if (isa<Argument>(V)) {
879 if (FromBB == &FromBB->getParent()->getEntryBlock())
880 return true;
881
882 // Otherwise, can only export this if it is already exported.
883 return FuncInfo.isExportedInst(V);
884 }
885
886 // Otherwise, constants can always be exported.
887 return true;
888}
889
Chris Lattner6a586c82006-10-29 21:01:20 +0000890static bool InBlock(const Value *V, const BasicBlock *BB) {
891 if (const Instruction *I = dyn_cast<Instruction>(V))
892 return I->getParent() == BB;
893 return true;
894}
895
Chris Lattner571e4342006-10-27 21:36:01 +0000896/// FindMergedConditions - If Cond is an expression like
897void SelectionDAGLowering::FindMergedConditions(Value *Cond,
898 MachineBasicBlock *TBB,
899 MachineBasicBlock *FBB,
900 MachineBasicBlock *CurBB,
901 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000902 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000903 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000904
Reid Spencere4d87aa2006-12-23 06:05:41 +0000905 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
906 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000907 BOp->getParent() != CurBB->getBasicBlock() ||
908 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
909 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000910 const BasicBlock *BB = CurBB->getBasicBlock();
911
Reid Spencere4d87aa2006-12-23 06:05:41 +0000912 // If the leaf of the tree is a comparison, merge the condition into
913 // the caseblock.
914 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
915 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000916 // how to export them from some other block. If this is the first block
917 // of the sequence, no exporting is needed.
918 (CurBB == CurMBB ||
919 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
920 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000921 BOp = cast<Instruction>(Cond);
922 ISD::CondCode Condition;
923 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
924 switch (IC->getPredicate()) {
925 default: assert(0 && "Unknown icmp predicate opcode!");
926 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
927 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
928 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
929 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
930 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
931 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
932 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
933 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
934 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
935 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
936 }
937 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
938 ISD::CondCode FPC, FOC;
939 switch (FC->getPredicate()) {
940 default: assert(0 && "Unknown fcmp predicate opcode!");
941 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
942 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
943 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
944 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
945 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
946 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
947 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
948 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
949 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
950 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
951 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
952 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
953 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
954 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
955 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
956 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
957 }
958 if (FiniteOnlyFPMath())
959 Condition = FOC;
960 else
961 Condition = FPC;
962 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000963 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000964 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000965 }
966
Chris Lattner571e4342006-10-27 21:36:01 +0000967 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000968 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000969 SwitchCases.push_back(CB);
970 return;
971 }
972
973 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000974 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000975 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000976 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000977 return;
978 }
979
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000980
981 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000982 MachineFunction::iterator BBI = CurBB;
983 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
984 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
985
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000986 if (Opc == Instruction::Or) {
987 // Codegen X | Y as:
988 // jmp_if_X TBB
989 // jmp TmpBB
990 // TmpBB:
991 // jmp_if_Y TBB
992 // jmp FBB
993 //
Chris Lattner571e4342006-10-27 21:36:01 +0000994
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000995 // Emit the LHS condition.
996 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
997
998 // Emit the RHS condition into TmpBB.
999 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1000 } else {
1001 assert(Opc == Instruction::And && "Unknown merge op!");
1002 // Codegen X & Y as:
1003 // jmp_if_X TmpBB
1004 // jmp FBB
1005 // TmpBB:
1006 // jmp_if_Y TBB
1007 // jmp FBB
1008 //
1009 // This requires creation of TmpBB after CurBB.
1010
1011 // Emit the LHS condition.
1012 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1013
1014 // Emit the RHS condition into TmpBB.
1015 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1016 }
Chris Lattner571e4342006-10-27 21:36:01 +00001017}
1018
Chris Lattnerdf19f272006-10-31 22:37:42 +00001019/// If the set of cases should be emitted as a series of branches, return true.
1020/// If we should emit this as a bunch of and/or'd together conditions, return
1021/// false.
1022static bool
1023ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1024 if (Cases.size() != 2) return true;
1025
Chris Lattner0ccb5002006-10-31 23:06:00 +00001026 // If this is two comparisons of the same values or'd or and'd together, they
1027 // will get folded into a single comparison, so don't emit two blocks.
1028 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1029 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1030 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1031 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1032 return false;
1033 }
1034
Chris Lattnerdf19f272006-10-31 22:37:42 +00001035 return true;
1036}
1037
Chris Lattner1c08c712005-01-07 07:47:53 +00001038void SelectionDAGLowering::visitBr(BranchInst &I) {
1039 // Update machine-CFG edges.
1040 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001041
1042 // Figure out which block is immediately after the current one.
1043 MachineBasicBlock *NextBlock = 0;
1044 MachineFunction::iterator BBI = CurMBB;
1045 if (++BBI != CurMBB->getParent()->end())
1046 NextBlock = BBI;
1047
1048 if (I.isUnconditional()) {
1049 // If this is not a fall-through branch, emit the branch.
1050 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001051 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001052 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001053
Chris Lattner57ab6592006-10-24 17:57:59 +00001054 // Update machine-CFG edges.
1055 CurMBB->addSuccessor(Succ0MBB);
1056
1057 return;
1058 }
1059
1060 // If this condition is one of the special cases we handle, do special stuff
1061 // now.
1062 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001063 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001064
1065 // If this is a series of conditions that are or'd or and'd together, emit
1066 // this as a sequence of branches instead of setcc's with and/or operations.
1067 // For example, instead of something like:
1068 // cmp A, B
1069 // C = seteq
1070 // cmp D, E
1071 // F = setle
1072 // or C, F
1073 // jnz foo
1074 // Emit:
1075 // cmp A, B
1076 // je foo
1077 // cmp D, E
1078 // jle foo
1079 //
1080 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1081 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001082 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001083 BOp->getOpcode() == Instruction::Or)) {
1084 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001085 // If the compares in later blocks need to use values not currently
1086 // exported from this block, export them now. This block should always
1087 // be the first entry.
1088 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1089
Chris Lattnerdf19f272006-10-31 22:37:42 +00001090 // Allow some cases to be rejected.
1091 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001092 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1093 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1094 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1095 }
1096
1097 // Emit the branch for this block.
1098 visitSwitchCase(SwitchCases[0]);
1099 SwitchCases.erase(SwitchCases.begin());
1100 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001101 }
1102
Chris Lattner0ccb5002006-10-31 23:06:00 +00001103 // Okay, we decided not to do this, remove any inserted MBB's and clear
1104 // SwitchCases.
1105 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1106 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1107
Chris Lattnerdf19f272006-10-31 22:37:42 +00001108 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001109 }
1110 }
Chris Lattner24525952006-10-24 18:07:37 +00001111
1112 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001113 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001114 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001115 // Use visitSwitchCase to actually insert the fast branch sequence for this
1116 // cond branch.
1117 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001118}
1119
Nate Begemanf15485a2006-03-27 01:32:24 +00001120/// visitSwitchCase - Emits the necessary code to represent a single node in
1121/// the binary search tree resulting from lowering a switch instruction.
1122void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001123 SDOperand Cond;
1124 SDOperand CondLHS = getValue(CB.CmpLHS);
1125
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001126 // Build the setcc now.
1127 if (CB.CmpMHS == NULL) {
1128 // Fold "(X == true)" to X and "(X == false)" to !X to
1129 // handle common cases produced by branch lowering.
1130 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1131 Cond = CondLHS;
1132 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1133 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1134 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1135 } else
1136 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1137 } else {
1138 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001139
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001140 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1141 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1142
1143 SDOperand CmpOp = getValue(CB.CmpMHS);
1144 MVT::ValueType VT = CmpOp.getValueType();
1145
1146 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1147 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1148 } else {
1149 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1150 Cond = DAG.getSetCC(MVT::i1, SUB,
1151 DAG.getConstant(High-Low, VT), ISD::SETULE);
1152 }
1153
1154 }
1155
Nate Begemanf15485a2006-03-27 01:32:24 +00001156 // Set NextBlock to be the MBB immediately after the current one, if any.
1157 // This is used to avoid emitting unnecessary branches to the next block.
1158 MachineBasicBlock *NextBlock = 0;
1159 MachineFunction::iterator BBI = CurMBB;
1160 if (++BBI != CurMBB->getParent()->end())
1161 NextBlock = BBI;
1162
1163 // If the lhs block is the next block, invert the condition so that we can
1164 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001165 if (CB.TrueBB == NextBlock) {
1166 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001167 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1168 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1169 }
1170 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001171 DAG.getBasicBlock(CB.TrueBB));
1172 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001173 DAG.setRoot(BrCond);
1174 else
1175 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001176 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001177 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001178 CurMBB->addSuccessor(CB.TrueBB);
1179 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001180}
1181
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001182/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001183void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001184 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001185 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001186 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001187 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1188 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1189 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1190 Table, Index));
1191 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001192}
1193
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001194/// visitJumpTableHeader - This function emits necessary code to produce index
1195/// in the JumpTable from switch case.
1196void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1197 SelectionDAGISel::JumpTableHeader &JTH) {
1198 // Subtract the lowest switch case value from the value being switched on
1199 // and conditional branch to default mbb if the result is greater than the
1200 // difference between smallest and largest cases.
1201 SDOperand SwitchOp = getValue(JTH.SValue);
1202 MVT::ValueType VT = SwitchOp.getValueType();
1203 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1204 DAG.getConstant(JTH.First, VT));
1205
1206 // The SDNode we just created, which holds the value being switched on
1207 // minus the the smallest case value, needs to be copied to a virtual
1208 // register so it can be used as an index into the jump table in a
1209 // subsequent basic block. This value may be smaller or larger than the
1210 // target's pointer type, and therefore require extension or truncating.
1211 if (VT > TLI.getPointerTy())
1212 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1213 else
1214 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1215
1216 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1217 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1218 JT.Reg = JumpTableReg;
1219
1220 // Emit the range check for the jump table, and branch to the default
1221 // block for the switch statement if the value being switched on exceeds
1222 // the largest case in the switch.
1223 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1224 DAG.getConstant(JTH.Last-JTH.First,VT),
1225 ISD::SETUGT);
1226
1227 // Set NextBlock to be the MBB immediately after the current one, if any.
1228 // This is used to avoid emitting unnecessary branches to the next block.
1229 MachineBasicBlock *NextBlock = 0;
1230 MachineFunction::iterator BBI = CurMBB;
1231 if (++BBI != CurMBB->getParent()->end())
1232 NextBlock = BBI;
1233
1234 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1235 DAG.getBasicBlock(JT.Default));
1236
1237 if (JT.MBB == NextBlock)
1238 DAG.setRoot(BrCond);
1239 else
1240 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001241 DAG.getBasicBlock(JT.MBB)));
1242
1243 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001244}
1245
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001246/// visitBitTestHeader - This function emits necessary code to produce value
1247/// suitable for "bit tests"
1248void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1249 // Subtract the minimum value
1250 SDOperand SwitchOp = getValue(B.SValue);
1251 MVT::ValueType VT = SwitchOp.getValueType();
1252 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1253 DAG.getConstant(B.First, VT));
1254
1255 // Check range
1256 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1257 DAG.getConstant(B.Range, VT),
1258 ISD::SETUGT);
1259
1260 SDOperand ShiftOp;
1261 if (VT > TLI.getShiftAmountTy())
1262 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1263 else
1264 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1265
1266 // Make desired shift
1267 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1268 DAG.getConstant(1, TLI.getPointerTy()),
1269 ShiftOp);
1270
1271 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1272 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1273 B.Reg = SwitchReg;
1274
1275 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1276 DAG.getBasicBlock(B.Default));
1277
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1283 NextBlock = BBI;
1284
1285 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1286 if (MBB == NextBlock)
1287 DAG.setRoot(BrRange);
1288 else
1289 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1290 DAG.getBasicBlock(MBB)));
1291
1292 CurMBB->addSuccessor(B.Default);
1293 CurMBB->addSuccessor(MBB);
1294
1295 return;
1296}
1297
1298/// visitBitTestCase - this function produces one "bit test"
1299void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1300 unsigned Reg,
1301 SelectionDAGISel::BitTestCase &B) {
1302 // Emit bit tests and jumps
1303 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1304
1305 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1306 SwitchVal,
1307 DAG.getConstant(B.Mask,
1308 TLI.getPointerTy()));
1309 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1310 DAG.getConstant(0, TLI.getPointerTy()),
1311 ISD::SETNE);
1312 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1313 AndCmp, DAG.getBasicBlock(B.TargetBB));
1314
1315 // Set NextBlock to be the MBB immediately after the current one, if any.
1316 // This is used to avoid emitting unnecessary branches to the next block.
1317 MachineBasicBlock *NextBlock = 0;
1318 MachineFunction::iterator BBI = CurMBB;
1319 if (++BBI != CurMBB->getParent()->end())
1320 NextBlock = BBI;
1321
1322 if (NextMBB == NextBlock)
1323 DAG.setRoot(BrAnd);
1324 else
1325 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1326 DAG.getBasicBlock(NextMBB)));
1327
1328 CurMBB->addSuccessor(B.TargetBB);
1329 CurMBB->addSuccessor(NextMBB);
1330
1331 return;
1332}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001333
Jim Laskeyb180aa12007-02-21 22:53:45 +00001334void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001335 assert(0 && "Should never be visited directly");
1336}
1337void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001338 // Retrieve successors.
1339 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1340 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1341
Jim Laskey183f47f2007-02-25 21:43:59 +00001342 if (!AsTerminator) {
1343 // Mark landing pad so that it doesn't get deleted in branch folding.
1344 LandingPad->setIsLandingPad();
Anton Korobeynikov070280e2007-05-23 11:08:31 +00001345
Jim Laskey183f47f2007-02-25 21:43:59 +00001346 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov070280e2007-05-23 11:08:31 +00001347 I.getCallingConv(),
1348 false,
1349 getValue(I.getOperand(0)),
1350 3, LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001351
Jim Laskey183f47f2007-02-25 21:43:59 +00001352 // Update successor info
1353 CurMBB->addSuccessor(Return);
1354 CurMBB->addSuccessor(LandingPad);
1355 } else {
1356 // Drop into normal successor.
1357 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1358 DAG.getBasicBlock(Return)));
1359 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001360}
1361
1362void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1363}
1364
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001365/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001366/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001367bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001368 CaseRecVector& WorkList,
1369 Value* SV,
1370 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001371 Case& BackCase = *(CR.Range.second-1);
1372
1373 // Size is the number of Cases represented by this range.
1374 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001375 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001376 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001377
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001378 // Get the MachineFunction which holds the current MBB. This is used when
1379 // inserting any additional MBBs necessary to represent the switch.
1380 MachineFunction *CurMF = CurMBB->getParent();
1381
1382 // Figure out which block is immediately after the current one.
1383 MachineBasicBlock *NextBlock = 0;
1384 MachineFunction::iterator BBI = CR.CaseBB;
1385
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001386 if (++BBI != CurMBB->getParent()->end())
1387 NextBlock = BBI;
1388
1389 // TODO: If any two of the cases has the same destination, and if one value
1390 // is the same as the other, but has one bit unset that the other has set,
1391 // use bit manipulation to do two compares at once. For example:
1392 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1393
1394 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001395 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001396 // The last case block won't fall through into 'NextBlock' if we emit the
1397 // branches in this order. See if rearranging a case value would help.
1398 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001399 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001400 std::swap(*I, BackCase);
1401 break;
1402 }
1403 }
1404 }
1405
1406 // Create a CaseBlock record representing a conditional branch to
1407 // the Case's target mbb if the value being switched on SV is equal
1408 // to C.
1409 MachineBasicBlock *CurBlock = CR.CaseBB;
1410 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1411 MachineBasicBlock *FallThrough;
1412 if (I != E-1) {
1413 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1414 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1415 } else {
1416 // If the last case doesn't match, go to the default block.
1417 FallThrough = Default;
1418 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001419
1420 Value *RHS, *LHS, *MHS;
1421 ISD::CondCode CC;
1422 if (I->High == I->Low) {
1423 // This is just small small case range :) containing exactly 1 case
1424 CC = ISD::SETEQ;
1425 LHS = SV; RHS = I->High; MHS = NULL;
1426 } else {
1427 CC = ISD::SETLE;
1428 LHS = I->Low; MHS = SV; RHS = I->High;
1429 }
1430 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1431 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001432
1433 // If emitting the first comparison, just call visitSwitchCase to emit the
1434 // code into the current block. Otherwise, push the CaseBlock onto the
1435 // vector to be later processed by SDISel, and insert the node's MBB
1436 // before the next MBB.
1437 if (CurBlock == CurMBB)
1438 visitSwitchCase(CB);
1439 else
1440 SwitchCases.push_back(CB);
1441
1442 CurBlock = FallThrough;
1443 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001444
1445 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001446}
1447
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001448static inline bool areJTsAllowed(const TargetLowering &TLI) {
1449 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1450 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1451}
1452
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001453/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001454bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001455 CaseRecVector& WorkList,
1456 Value* SV,
1457 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001458 Case& FrontCase = *CR.Range.first;
1459 Case& BackCase = *(CR.Range.second-1);
1460
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001461 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1462 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1463
1464 uint64_t TSize = 0;
1465 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1466 I!=E; ++I)
1467 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001468
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001469 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001470 return false;
1471
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001472 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1473 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001474 return false;
1475
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001476 DOUT << "Lowering jump table\n"
1477 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001478 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001479
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001480 // Get the MachineFunction which holds the current MBB. This is used when
1481 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001482 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001483
1484 // Figure out which block is immediately after the current one.
1485 MachineBasicBlock *NextBlock = 0;
1486 MachineFunction::iterator BBI = CR.CaseBB;
1487
1488 if (++BBI != CurMBB->getParent()->end())
1489 NextBlock = BBI;
1490
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001491 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1492
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001493 // Create a new basic block to hold the code for loading the address
1494 // of the jump table, and jumping to it. Update successor information;
1495 // we will either branch to the default case for the switch, or the jump
1496 // table.
1497 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1498 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1499 CR.CaseBB->addSuccessor(Default);
1500 CR.CaseBB->addSuccessor(JumpTableBB);
1501
1502 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001503 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001504 // a case statement, push the case's BB onto the vector, otherwise, push
1505 // the default BB.
1506 std::vector<MachineBasicBlock*> DestBBs;
1507 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001508 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1509 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1510 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1511
1512 if ((Low <= TEI) && (TEI <= High)) {
1513 DestBBs.push_back(I->BB);
1514 if (TEI==High)
1515 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001516 } else {
1517 DestBBs.push_back(Default);
1518 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001519 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001520
1521 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001522 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001523 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1524 E = DestBBs.end(); I != E; ++I) {
1525 if (!SuccsHandled[(*I)->getNumber()]) {
1526 SuccsHandled[(*I)->getNumber()] = true;
1527 JumpTableBB->addSuccessor(*I);
1528 }
1529 }
1530
1531 // Create a jump table index for this jump table, or return an existing
1532 // one.
1533 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1534
1535 // Set the jump table information so that we can codegen it as a second
1536 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001537 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001538 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1539 (CR.CaseBB == CurMBB));
1540 if (CR.CaseBB == CurMBB)
1541 visitJumpTableHeader(JT, JTH);
1542
1543 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001544
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001545 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001546}
1547
1548/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1549/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001550bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001551 CaseRecVector& WorkList,
1552 Value* SV,
1553 MachineBasicBlock* Default) {
1554 // Get the MachineFunction which holds the current MBB. This is used when
1555 // inserting any additional MBBs necessary to represent the switch.
1556 MachineFunction *CurMF = CurMBB->getParent();
1557
1558 // Figure out which block is immediately after the current one.
1559 MachineBasicBlock *NextBlock = 0;
1560 MachineFunction::iterator BBI = CR.CaseBB;
1561
1562 if (++BBI != CurMBB->getParent()->end())
1563 NextBlock = BBI;
1564
1565 Case& FrontCase = *CR.Range.first;
1566 Case& BackCase = *(CR.Range.second-1);
1567 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1568
1569 // Size is the number of Cases represented by this range.
1570 unsigned Size = CR.Range.second - CR.Range.first;
1571
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001572 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1573 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001574 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001575 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001576
1577 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1578 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001579 uint64_t TSize = 0;
1580 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1581 I!=E; ++I)
1582 TSize += I->size();
1583
1584 uint64_t LSize = FrontCase.size();
1585 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001586 DOUT << "Selecting best pivot: \n"
1587 << "First: " << First << ", Last: " << Last <<"\n"
1588 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001589 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001590 J!=E; ++I, ++J) {
1591 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1592 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001593 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001594 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1595 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001596 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001597 // Should always split in some non-trivial place
1598 DOUT <<"=>Step\n"
1599 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1600 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1601 << "Metric: " << Metric << "\n";
1602 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001603 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001604 FMetric = Metric;
1605 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001606 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001607
1608 LSize += J->size();
1609 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001610 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001611 if (areJTsAllowed(TLI)) {
1612 // If our case is dense we *really* should handle it earlier!
1613 assert((FMetric > 0) && "Should handle dense range earlier!");
1614 } else {
1615 Pivot = CR.Range.first + Size/2;
1616 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001617
1618 CaseRange LHSR(CR.Range.first, Pivot);
1619 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001620 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001621 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1622
1623 // We know that we branch to the LHS if the Value being switched on is
1624 // less than the Pivot value, C. We use this to optimize our binary
1625 // tree a bit, by recognizing that if SV is greater than or equal to the
1626 // LHS's Case Value, and that Case Value is exactly one less than the
1627 // Pivot's Value, then we can branch directly to the LHS's Target,
1628 // rather than creating a leaf node for it.
1629 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001630 LHSR.first->High == CR.GE &&
1631 cast<ConstantInt>(C)->getSExtValue() ==
1632 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1633 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001634 } else {
1635 TrueBB = new MachineBasicBlock(LLVMBB);
1636 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1637 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1638 }
1639
1640 // Similar to the optimization above, if the Value being switched on is
1641 // known to be less than the Constant CR.LT, and the current Case Value
1642 // is CR.LT - 1, then we can branch directly to the target block for
1643 // the current Case Value, rather than emitting a RHS leaf node for it.
1644 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001645 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1646 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1647 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001648 } else {
1649 FalseBB = new MachineBasicBlock(LLVMBB);
1650 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1651 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1652 }
1653
1654 // Create a CaseBlock record representing a conditional branch to
1655 // the LHS node if the value being switched on SV is less than C.
1656 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001657 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1658 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001659
1660 if (CR.CaseBB == CurMBB)
1661 visitSwitchCase(CB);
1662 else
1663 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001664
1665 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001666}
1667
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001668/// handleBitTestsSwitchCase - if current case range has few destination and
1669/// range span less, than machine word bitwidth, encode case range into series
1670/// of masks and emit bit tests with these masks.
1671bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1672 CaseRecVector& WorkList,
1673 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001674 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001675 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001676
1677 Case& FrontCase = *CR.Range.first;
1678 Case& BackCase = *(CR.Range.second-1);
1679
1680 // Get the MachineFunction which holds the current MBB. This is used when
1681 // inserting any additional MBBs necessary to represent the switch.
1682 MachineFunction *CurMF = CurMBB->getParent();
1683
1684 unsigned numCmps = 0;
1685 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1686 I!=E; ++I) {
1687 // Single case counts one, case range - two.
1688 if (I->Low == I->High)
1689 numCmps +=1;
1690 else
1691 numCmps +=2;
1692 }
1693
1694 // Count unique destinations
1695 SmallSet<MachineBasicBlock*, 4> Dests;
1696 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1697 Dests.insert(I->BB);
1698 if (Dests.size() > 3)
1699 // Don't bother the code below, if there are too much unique destinations
1700 return false;
1701 }
1702 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1703 << "Total number of comparisons: " << numCmps << "\n";
1704
1705 // Compute span of values.
1706 Constant* minValue = FrontCase.Low;
1707 Constant* maxValue = BackCase.High;
1708 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1709 cast<ConstantInt>(minValue)->getSExtValue();
1710 DOUT << "Compare range: " << range << "\n"
1711 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1712 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1713
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00001714 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001715 (!(Dests.size() == 1 && numCmps >= 3) &&
1716 !(Dests.size() == 2 && numCmps >= 5) &&
1717 !(Dests.size() >= 3 && numCmps >= 6)))
1718 return false;
1719
1720 DOUT << "Emitting bit tests\n";
1721 int64_t lowBound = 0;
1722
1723 // Optimize the case where all the case values fit in a
1724 // word without having to subtract minValue. In this case,
1725 // we can optimize away the subtraction.
1726 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001727 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001728 range = cast<ConstantInt>(maxValue)->getSExtValue();
1729 } else {
1730 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1731 }
1732
1733 CaseBitsVector CasesBits;
1734 unsigned i, count = 0;
1735
1736 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1737 MachineBasicBlock* Dest = I->BB;
1738 for (i = 0; i < count; ++i)
1739 if (Dest == CasesBits[i].BB)
1740 break;
1741
1742 if (i == count) {
1743 assert((count < 3) && "Too much destinations to test!");
1744 CasesBits.push_back(CaseBits(0, Dest, 0));
1745 count++;
1746 }
1747
1748 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1749 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1750
1751 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001752 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001753 CasesBits[i].Bits++;
1754 }
1755
1756 }
1757 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1758
1759 SelectionDAGISel::BitTestInfo BTC;
1760
1761 // Figure out which block is immediately after the current one.
1762 MachineFunction::iterator BBI = CR.CaseBB;
1763 ++BBI;
1764
1765 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1766
1767 DOUT << "Cases:\n";
1768 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1769 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1770 << ", BB: " << CasesBits[i].BB << "\n";
1771
1772 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1773 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1774 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1775 CaseBB,
1776 CasesBits[i].BB));
1777 }
1778
1779 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00001780 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001781 CR.CaseBB, Default, BTC);
1782
1783 if (CR.CaseBB == CurMBB)
1784 visitBitTestHeader(BTB);
1785
1786 BitTestCases.push_back(BTB);
1787
1788 return true;
1789}
1790
1791
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001792// Clusterify - Transform simple list of Cases into list of CaseRange's
1793unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1794 const SwitchInst& SI) {
1795 unsigned numCmps = 0;
1796
1797 // Start with "simple" cases
1798 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1799 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1800 Cases.push_back(Case(SI.getSuccessorValue(i),
1801 SI.getSuccessorValue(i),
1802 SMBB));
1803 }
1804 sort(Cases.begin(), Cases.end(), CaseCmp());
1805
1806 // Merge case into clusters
1807 if (Cases.size()>=2)
1808 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1809 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1810 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1811 MachineBasicBlock* nextBB = J->BB;
1812 MachineBasicBlock* currentBB = I->BB;
1813
1814 // If the two neighboring cases go to the same destination, merge them
1815 // into a single case.
1816 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1817 I->High = J->High;
1818 J = Cases.erase(J);
1819 } else {
1820 I = J++;
1821 }
1822 }
1823
1824 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1825 if (I->Low != I->High)
1826 // A range counts double, since it requires two compares.
1827 ++numCmps;
1828 }
1829
1830 return numCmps;
1831}
1832
1833void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001834 // Figure out which block is immediately after the current one.
1835 MachineBasicBlock *NextBlock = 0;
1836 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001837
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001838 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001839
Nate Begemanf15485a2006-03-27 01:32:24 +00001840 // If there is only the default destination, branch to it if it is not the
1841 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001842 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001843 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001844
Nate Begemanf15485a2006-03-27 01:32:24 +00001845 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001846 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001847 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001848 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001849
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001850 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001851 return;
1852 }
1853
1854 // If there are any non-default case statements, create a vector of Cases
1855 // representing each one, and sort the vector so that we can efficiently
1856 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001857 CaseVector Cases;
1858 unsigned numCmps = Clusterify(Cases, SI);
1859 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1860 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001861
Nate Begemanf15485a2006-03-27 01:32:24 +00001862 // Get the Value to be switched on and default basic blocks, which will be
1863 // inserted into CaseBlock records, representing basic blocks in the binary
1864 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001865 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001866
Nate Begemanf15485a2006-03-27 01:32:24 +00001867 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001868 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001869 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1870
1871 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001872 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001873 CaseRec CR = WorkList.back();
1874 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001875
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001876 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1877 continue;
1878
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001879 // If the range has few cases (two or less) emit a series of specific
1880 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001881 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1882 continue;
1883
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001884 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001885 // target supports indirect branches, then emit a jump table rather than
1886 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001887 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1888 continue;
1889
1890 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1891 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1892 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001893 }
1894}
1895
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001896
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001897void SelectionDAGLowering::visitSub(User &I) {
1898 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001899 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001900 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001901 visitVectorBinary(I, ISD::VSUB);
1902 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001903 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1904 if (CFP->isExactlyValue(-0.0)) {
1905 SDOperand Op2 = getValue(I.getOperand(1));
1906 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1907 return;
1908 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001909 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001910 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001911 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001912}
1913
Reid Spencer24d6da52007-01-21 00:29:26 +00001914void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001915 SDOperand Op1 = getValue(I.getOperand(0));
1916 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001917
1918 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001919}
1920
Reid Spencer24d6da52007-01-21 00:29:26 +00001921void
1922SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001923 assert(isa<VectorType>(I.getType()));
1924 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001925 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001926
Reid Spencer24d6da52007-01-21 00:29:26 +00001927 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1928 getValue(I.getOperand(0)),
1929 getValue(I.getOperand(1)),
1930 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1931 Typ));
1932}
1933
1934void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1935 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001936 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001937 visitVectorBinary(I, VectorOp);
1938 else
1939 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001940}
Chris Lattner2c49f272005-01-19 22:31:21 +00001941
Nate Begemane21ea612005-11-18 07:42:56 +00001942void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1943 SDOperand Op1 = getValue(I.getOperand(0));
1944 SDOperand Op2 = getValue(I.getOperand(1));
1945
Reid Spencer832254e2007-02-02 02:16:23 +00001946 if (TLI.getShiftAmountTy() < Op2.getValueType())
1947 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1948 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1949 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001950
Chris Lattner1c08c712005-01-07 07:47:53 +00001951 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1952}
1953
Reid Spencer45fb3f32006-11-20 01:22:35 +00001954void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001955 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1956 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1957 predicate = IC->getPredicate();
1958 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1959 predicate = ICmpInst::Predicate(IC->getPredicate());
1960 SDOperand Op1 = getValue(I.getOperand(0));
1961 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001962 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001963 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001964 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1965 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1966 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1967 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1968 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1969 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1970 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1971 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1972 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1973 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1974 default:
1975 assert(!"Invalid ICmp predicate value");
1976 Opcode = ISD::SETEQ;
1977 break;
1978 }
1979 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1980}
1981
1982void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001983 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1984 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1985 predicate = FC->getPredicate();
1986 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1987 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001988 SDOperand Op1 = getValue(I.getOperand(0));
1989 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001990 ISD::CondCode Condition, FOC, FPC;
1991 switch (predicate) {
1992 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1993 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1994 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1995 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1996 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1997 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1998 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1999 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2000 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2001 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2002 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2003 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2004 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2005 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2006 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2007 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2008 default:
2009 assert(!"Invalid FCmp predicate value");
2010 FOC = FPC = ISD::SETFALSE;
2011 break;
2012 }
2013 if (FiniteOnlyFPMath())
2014 Condition = FOC;
2015 else
2016 Condition = FPC;
2017 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002018}
2019
2020void SelectionDAGLowering::visitSelect(User &I) {
2021 SDOperand Cond = getValue(I.getOperand(0));
2022 SDOperand TrueVal = getValue(I.getOperand(1));
2023 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00002024 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00002025 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2026 TrueVal, FalseVal));
2027 } else {
2028 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2029 *(TrueVal.Val->op_end()-2),
2030 *(TrueVal.Val->op_end()-1)));
2031 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002032}
2033
Reid Spencer3da59db2006-11-27 01:05:10 +00002034
2035void SelectionDAGLowering::visitTrunc(User &I) {
2036 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2037 SDOperand N = getValue(I.getOperand(0));
2038 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2039 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2040}
2041
2042void SelectionDAGLowering::visitZExt(User &I) {
2043 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2044 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2045 SDOperand N = getValue(I.getOperand(0));
2046 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2047 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2048}
2049
2050void SelectionDAGLowering::visitSExt(User &I) {
2051 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2052 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2053 SDOperand N = getValue(I.getOperand(0));
2054 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2055 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2056}
2057
2058void SelectionDAGLowering::visitFPTrunc(User &I) {
2059 // FPTrunc is never a no-op cast, no need to check
2060 SDOperand N = getValue(I.getOperand(0));
2061 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2062 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2063}
2064
2065void SelectionDAGLowering::visitFPExt(User &I){
2066 // FPTrunc is never a no-op cast, no need to check
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2069 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2070}
2071
2072void SelectionDAGLowering::visitFPToUI(User &I) {
2073 // FPToUI is never a no-op cast, no need to check
2074 SDOperand N = getValue(I.getOperand(0));
2075 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2076 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2077}
2078
2079void SelectionDAGLowering::visitFPToSI(User &I) {
2080 // FPToSI is never a no-op cast, no need to check
2081 SDOperand N = getValue(I.getOperand(0));
2082 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2083 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2084}
2085
2086void SelectionDAGLowering::visitUIToFP(User &I) {
2087 // UIToFP is never a no-op cast, no need to check
2088 SDOperand N = getValue(I.getOperand(0));
2089 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2090 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2091}
2092
2093void SelectionDAGLowering::visitSIToFP(User &I){
2094 // UIToFP is never a no-op cast, no need to check
2095 SDOperand N = getValue(I.getOperand(0));
2096 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2097 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2098}
2099
2100void SelectionDAGLowering::visitPtrToInt(User &I) {
2101 // What to do depends on the size of the integer and the size of the pointer.
2102 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002103 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002104 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002105 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002106 SDOperand Result;
2107 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2108 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2109 else
2110 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2111 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2112 setValue(&I, Result);
2113}
Chris Lattner1c08c712005-01-07 07:47:53 +00002114
Reid Spencer3da59db2006-11-27 01:05:10 +00002115void SelectionDAGLowering::visitIntToPtr(User &I) {
2116 // What to do depends on the size of the integer and the size of the pointer.
2117 // We can either truncate, zero extend, or no-op, accordingly.
2118 SDOperand N = getValue(I.getOperand(0));
2119 MVT::ValueType SrcVT = N.getValueType();
2120 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2121 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2122 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2123 else
2124 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2125 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2126}
2127
2128void SelectionDAGLowering::visitBitCast(User &I) {
2129 SDOperand N = getValue(I.getOperand(0));
2130 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002131 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002132 // This is a cast to a vector from something else.
2133 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00002134 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00002135 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2136 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2137 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2138 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002139 return;
2140 }
2141 MVT::ValueType SrcVT = N.getValueType();
2142 if (SrcVT == MVT::Vector) {
2143 // This is a cast from a vctor to something else.
2144 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00002145 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00002146 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00002147 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002148
2149 // BitCast assures us that source and destination are the same size so this
2150 // is either a BIT_CONVERT or a no-op.
2151 if (DestVT != N.getValueType())
2152 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2153 else
2154 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002155}
2156
Chris Lattner2bbd8102006-03-29 00:11:43 +00002157void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002158 SDOperand InVec = getValue(I.getOperand(0));
2159 SDOperand InVal = getValue(I.getOperand(1));
2160 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2161 getValue(I.getOperand(2)));
2162
Chris Lattner2332b9f2006-03-19 01:17:20 +00002163 SDOperand Num = *(InVec.Val->op_end()-2);
2164 SDOperand Typ = *(InVec.Val->op_end()-1);
2165 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2166 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00002167}
2168
Chris Lattner2bbd8102006-03-29 00:11:43 +00002169void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002170 SDOperand InVec = getValue(I.getOperand(0));
2171 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2172 getValue(I.getOperand(1)));
2173 SDOperand Typ = *(InVec.Val->op_end()-1);
2174 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2175 TLI.getValueType(I.getType()), InVec, InIdx));
2176}
Chris Lattnerc7029802006-03-18 01:44:44 +00002177
Chris Lattner3e104b12006-04-08 04:15:24 +00002178void SelectionDAGLowering::visitShuffleVector(User &I) {
2179 SDOperand V1 = getValue(I.getOperand(0));
2180 SDOperand V2 = getValue(I.getOperand(1));
2181 SDOperand Mask = getValue(I.getOperand(2));
2182
2183 SDOperand Num = *(V1.Val->op_end()-2);
2184 SDOperand Typ = *(V2.Val->op_end()-1);
2185 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2186 V1, V2, Mask, Num, Typ));
2187}
2188
2189
Chris Lattner1c08c712005-01-07 07:47:53 +00002190void SelectionDAGLowering::visitGetElementPtr(User &I) {
2191 SDOperand N = getValue(I.getOperand(0));
2192 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002193
2194 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2195 OI != E; ++OI) {
2196 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002197 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002198 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002199 if (Field) {
2200 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002201 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002202 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00002203 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002204 }
2205 Ty = StTy->getElementType(Field);
2206 } else {
2207 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002208
Chris Lattner7c0104b2005-11-09 04:45:33 +00002209 // If this is a constant subscript, handle it quickly.
2210 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002211 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002212 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00002213 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00002214 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2215 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002216 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002217
2218 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00002219 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002220 SDOperand IdxN = getValue(Idx);
2221
2222 // If the index is smaller or larger than intptr_t, truncate or extend
2223 // it.
2224 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002225 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002226 } else if (IdxN.getValueType() > N.getValueType())
2227 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2228
2229 // If this is a multiply by a power of two, turn it into a shl
2230 // immediately. This is a very common case.
2231 if (isPowerOf2_64(ElementSize)) {
2232 unsigned Amt = Log2_64(ElementSize);
2233 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002234 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002235 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2236 continue;
2237 }
2238
2239 SDOperand Scale = getIntPtrConstant(ElementSize);
2240 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2241 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002242 }
2243 }
2244 setValue(&I, N);
2245}
2246
2247void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2248 // If this is a fixed sized alloca in the entry block of the function,
2249 // allocate it statically on the stack.
2250 if (FuncInfo.StaticAllocaMap.count(&I))
2251 return; // getValue will auto-populate this.
2252
2253 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00002254 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002255 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002256 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002257 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002258
2259 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002260 MVT::ValueType IntPtr = TLI.getPointerTy();
2261 if (IntPtr < AllocSize.getValueType())
2262 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2263 else if (IntPtr > AllocSize.getValueType())
2264 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002265
Chris Lattner68cd65e2005-01-22 23:04:37 +00002266 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00002267 getIntPtrConstant(TySize));
2268
2269 // Handle alignment. If the requested alignment is less than or equal to the
2270 // stack alignment, ignore it and round the size of the allocation up to the
2271 // stack alignment size. If the size is greater than the stack alignment, we
2272 // note this in the DYNAMIC_STACKALLOC node.
2273 unsigned StackAlign =
2274 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2275 if (Align <= StackAlign) {
2276 Align = 0;
2277 // Add SA-1 to the size.
2278 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2279 getIntPtrConstant(StackAlign-1));
2280 // Mask out the low bits for alignment purposes.
2281 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2282 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2283 }
2284
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002285 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002286 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2287 MVT::Other);
2288 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002289 setValue(&I, DSA);
2290 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002291
2292 // Inform the Frame Information that we have just allocated a variable-sized
2293 // object.
2294 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2295}
2296
Chris Lattner1c08c712005-01-07 07:47:53 +00002297void SelectionDAGLowering::visitLoad(LoadInst &I) {
2298 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002299
Chris Lattnerd3948112005-01-17 22:19:26 +00002300 SDOperand Root;
2301 if (I.isVolatile())
2302 Root = getRoot();
2303 else {
2304 // Do not serialize non-volatile loads against each other.
2305 Root = DAG.getRoot();
2306 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002307
Evan Cheng466685d2006-10-09 20:57:25 +00002308 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002309 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002310}
2311
2312SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002313 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002314 bool isVolatile,
2315 unsigned Alignment) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002316 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00002317 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00002318 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00002319 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2320 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002321 } else {
Christopher Lamb95c218a2007-04-22 23:15:30 +00002322 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2323 isVolatile, Alignment);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00002324 }
Chris Lattnerd3948112005-01-17 22:19:26 +00002325
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002326 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002327 DAG.setRoot(L.getValue(1));
2328 else
2329 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002330
2331 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002332}
2333
2334
2335void SelectionDAGLowering::visitStore(StoreInst &I) {
2336 Value *SrcV = I.getOperand(0);
2337 SDOperand Src = getValue(SrcV);
2338 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002339 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002340 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002341}
2342
Chris Lattner0eade312006-03-24 02:22:33 +00002343/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2344/// access memory and has no other side effects at all.
2345static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2346#define GET_NO_MEMORY_INTRINSICS
2347#include "llvm/Intrinsics.gen"
2348#undef GET_NO_MEMORY_INTRINSICS
2349 return false;
2350}
2351
Chris Lattnere58a7802006-04-02 03:41:14 +00002352// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2353// have any side-effects or if it only reads memory.
2354static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2355#define GET_SIDE_EFFECT_INFO
2356#include "llvm/Intrinsics.gen"
2357#undef GET_SIDE_EFFECT_INFO
2358 return false;
2359}
2360
Chris Lattner0eade312006-03-24 02:22:33 +00002361/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2362/// node.
2363void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2364 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00002365 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002366 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002367
2368 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002369 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002370 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2371 if (OnlyLoad) {
2372 // We don't need to serialize loads against other loads.
2373 Ops.push_back(DAG.getRoot());
2374 } else {
2375 Ops.push_back(getRoot());
2376 }
2377 }
Chris Lattner0eade312006-03-24 02:22:33 +00002378
2379 // Add the intrinsic ID as an integer operand.
2380 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2381
2382 // Add all operands of the call to the operand list.
2383 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2384 SDOperand Op = getValue(I.getOperand(i));
2385
Reid Spencerac9dcb92007-02-15 03:39:18 +00002386 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00002387 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002388 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002389 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2390
2391 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2392 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2393 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2394 }
2395
2396 assert(TLI.isTypeLegal(Op.getValueType()) &&
2397 "Intrinsic uses a non-legal type?");
2398 Ops.push_back(Op);
2399 }
2400
2401 std::vector<MVT::ValueType> VTs;
2402 if (I.getType() != Type::VoidTy) {
2403 MVT::ValueType VT = TLI.getValueType(I.getType());
2404 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002405 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002406 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2407
2408 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2409 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2410 }
2411
2412 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2413 VTs.push_back(VT);
2414 }
2415 if (HasChain)
2416 VTs.push_back(MVT::Other);
2417
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002418 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2419
Chris Lattner0eade312006-03-24 02:22:33 +00002420 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002421 SDOperand Result;
2422 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002423 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2424 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002425 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002426 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2427 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002428 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002429 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2430 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002431
Chris Lattnere58a7802006-04-02 03:41:14 +00002432 if (HasChain) {
2433 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2434 if (OnlyLoad)
2435 PendingLoads.push_back(Chain);
2436 else
2437 DAG.setRoot(Chain);
2438 }
Chris Lattner0eade312006-03-24 02:22:33 +00002439 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002440 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00002441 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2442 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2443 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2444 DAG.getValueType(EVT));
2445 }
2446 setValue(&I, Result);
2447 }
2448}
2449
Duncan Sands3b346362007-05-04 17:12:26 +00002450/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2451/// (possibly constant folded), return it. Otherwise return NULL.
2452static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2453 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2454 return GV;
2455 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2456 if (CE->getOpcode() == Instruction::BitCast)
2457 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2458 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2459 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2460 if (!CE->getOperand(i)->isNullValue())
2461 return NULL;
2462 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2463 }
2464 }
2465 return NULL;
2466}
2467
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002468/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2469/// we want to emit this as a call to a named external function, return the name
2470/// otherwise lower it and return null.
2471const char *
2472SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2473 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002474 default:
2475 // By default, turn this into a target intrinsic node.
2476 visitTargetIntrinsic(I, Intrinsic);
2477 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002478 case Intrinsic::vastart: visitVAStart(I); return 0;
2479 case Intrinsic::vaend: visitVAEnd(I); return 0;
2480 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002481 case Intrinsic::returnaddress:
2482 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2483 getValue(I.getOperand(1))));
2484 return 0;
2485 case Intrinsic::frameaddress:
2486 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2487 getValue(I.getOperand(1))));
2488 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002489 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002490 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002491 break;
2492 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002493 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002494 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002495 case Intrinsic::memcpy_i32:
2496 case Intrinsic::memcpy_i64:
2497 visitMemIntrinsic(I, ISD::MEMCPY);
2498 return 0;
2499 case Intrinsic::memset_i32:
2500 case Intrinsic::memset_i64:
2501 visitMemIntrinsic(I, ISD::MEMSET);
2502 return 0;
2503 case Intrinsic::memmove_i32:
2504 case Intrinsic::memmove_i64:
2505 visitMemIntrinsic(I, ISD::MEMMOVE);
2506 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002507
Chris Lattner86cb6432005-12-13 17:40:33 +00002508 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002509 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002510 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002511 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002512 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002513
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002514 Ops[0] = getRoot();
2515 Ops[1] = getValue(SPI.getLineValue());
2516 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002517
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002518 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002519 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002520 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2521
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002522 Ops[3] = DAG.getString(CompileUnit->getFileName());
2523 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002524
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002525 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002526 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002527
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002528 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002529 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002530 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002531 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002532 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002533 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2534 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002535 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002536 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002537 }
2538
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002539 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002540 }
2541 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002542 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002543 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002544 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2545 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002546 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002547 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002548 }
2549
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002550 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002551 }
2552 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002553 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002554 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002555 if (MMI && FSI.getSubprogram() &&
2556 MMI->Verify(FSI.getSubprogram())) {
2557 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002558 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002559 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002560 }
2561
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002562 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002563 }
2564 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002565 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002566 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002567 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002568 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002569 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002570 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002571 }
2572
2573 return 0;
2574 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002575
Jim Laskeyb180aa12007-02-21 22:53:45 +00002576 case Intrinsic::eh_exception: {
2577 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2578
Jim Laskey735b6f82007-02-22 15:38:06 +00002579 if (MMI) {
2580 // Add a label to mark the beginning of the landing pad. Deletion of the
2581 // landing pad can thus be detected via the MachineModuleInfo.
2582 unsigned LabelID = MMI->addLandingPad(CurMBB);
2583 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2584 DAG.getConstant(LabelID, MVT::i32)));
2585
2586 // Mark exception register as live in.
2587 unsigned Reg = TLI.getExceptionAddressRegister();
2588 if (Reg) CurMBB->addLiveIn(Reg);
2589
2590 // Insert the EXCEPTIONADDR instruction.
2591 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2592 SDOperand Ops[1];
2593 Ops[0] = DAG.getRoot();
2594 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2595 setValue(&I, Op);
2596 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002597 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002598 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002599 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002600 return 0;
2601 }
2602
Jim Laskey0b4711b2007-03-01 20:24:30 +00002603 case Intrinsic::eh_selector:
2604 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002605 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2606
Jim Laskey735b6f82007-02-22 15:38:06 +00002607 if (MMI) {
2608 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002609 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2610 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2611 isa<Function>(CE->getOperand(0)) &&
2612 "Personality should be a function");
2613 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey0b4711b2007-03-01 20:24:30 +00002614 if (Intrinsic == Intrinsic::eh_filter)
2615 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002616
Jim Laskey735b6f82007-02-22 15:38:06 +00002617 // Gather all the type infos for this landing pad and pass them along to
2618 // MachineModuleInfo.
2619 std::vector<GlobalVariable *> TyInfo;
2620 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Anton Korobeynikovb6824482007-05-06 20:14:21 +00002621 Constant *C = cast<Constant>(I.getOperand(i));
Duncan Sands3b346362007-05-04 17:12:26 +00002622 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands398898c2007-06-01 08:18:30 +00002623 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands3b346362007-05-04 17:12:26 +00002624 "TypeInfo must be a global variable or NULL");
2625 TyInfo.push_back(GV);
Jim Laskey735b6f82007-02-22 15:38:06 +00002626 }
2627 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2628
2629 // Mark exception selector register as live in.
2630 unsigned Reg = TLI.getExceptionSelectorRegister();
2631 if (Reg) CurMBB->addLiveIn(Reg);
2632
2633 // Insert the EHSELECTION instruction.
Anton Korobeynikov6ad82562007-05-02 22:15:48 +00002634 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002635 SDOperand Ops[2];
2636 Ops[0] = getValue(I.getOperand(1));
2637 Ops[1] = getRoot();
2638 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2639 setValue(&I, Op);
2640 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002641 } else {
Anton Korobeynikov6ad82562007-05-02 22:15:48 +00002642 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002643 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002644
2645 return 0;
2646 }
2647
2648 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002649 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002650
Jim Laskey735b6f82007-02-22 15:38:06 +00002651 if (MMI) {
2652 // Find the type id for the given typeinfo.
Duncan Sands3b346362007-05-04 17:12:26 +00002653 Constant *C = cast<Constant>(I.getOperand(1));
2654 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands398898c2007-06-01 08:18:30 +00002655 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands3b346362007-05-04 17:12:26 +00002656 "TypeInfo must be a global variable or NULL");
2657
Jim Laskey735b6f82007-02-22 15:38:06 +00002658 unsigned TypeID = MMI->getTypeIDFor(GV);
2659 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002660 } else {
2661 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002662 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002663
2664 return 0;
2665 }
2666
Reid Spencer0b118202006-01-16 21:12:35 +00002667 case Intrinsic::sqrt_f32:
2668 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002669 setValue(&I, DAG.getNode(ISD::FSQRT,
2670 getValue(I.getOperand(1)).getValueType(),
2671 getValue(I.getOperand(1))));
2672 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002673 case Intrinsic::powi_f32:
2674 case Intrinsic::powi_f64:
2675 setValue(&I, DAG.getNode(ISD::FPOWI,
2676 getValue(I.getOperand(1)).getValueType(),
2677 getValue(I.getOperand(1)),
2678 getValue(I.getOperand(2))));
2679 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002680 case Intrinsic::pcmarker: {
2681 SDOperand Tmp = getValue(I.getOperand(1));
2682 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2683 return 0;
2684 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002685 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002686 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002687 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2688 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2689 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002690 setValue(&I, Tmp);
2691 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002692 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002693 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00002694 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002695 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00002696 assert(0 && "part_select intrinsic not implemented");
2697 abort();
2698 }
2699 case Intrinsic::part_set: {
2700 // Currently not implemented: just abort
2701 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00002702 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002703 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002704 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002705 setValue(&I, DAG.getNode(ISD::BSWAP,
2706 getValue(I.getOperand(1)).getValueType(),
2707 getValue(I.getOperand(1))));
2708 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002709 case Intrinsic::cttz: {
2710 SDOperand Arg = getValue(I.getOperand(1));
2711 MVT::ValueType Ty = Arg.getValueType();
2712 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2713 if (Ty < MVT::i32)
2714 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2715 else if (Ty > MVT::i32)
2716 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2717 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002718 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002719 }
2720 case Intrinsic::ctlz: {
2721 SDOperand Arg = getValue(I.getOperand(1));
2722 MVT::ValueType Ty = Arg.getValueType();
2723 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2724 if (Ty < MVT::i32)
2725 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2726 else if (Ty > MVT::i32)
2727 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2728 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002729 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002730 }
2731 case Intrinsic::ctpop: {
2732 SDOperand Arg = getValue(I.getOperand(1));
2733 MVT::ValueType Ty = Arg.getValueType();
2734 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2735 if (Ty < MVT::i32)
2736 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2737 else if (Ty > MVT::i32)
2738 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2739 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002740 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002741 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002742 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002743 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002744 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2745 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002746 setValue(&I, Tmp);
2747 DAG.setRoot(Tmp.getValue(1));
2748 return 0;
2749 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002750 case Intrinsic::stackrestore: {
2751 SDOperand Tmp = getValue(I.getOperand(1));
2752 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002753 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002754 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002755 case Intrinsic::prefetch:
2756 // FIXME: Currently discarding prefetches.
2757 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002758 }
2759}
2760
2761
Jim Laskey1da20a72007-02-23 21:45:01 +00002762void SelectionDAGLowering::LowerCallTo(Instruction &I,
2763 const Type *CalledValueTy,
2764 unsigned CallingConv,
2765 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002766 SDOperand Callee, unsigned OpIdx,
2767 MachineBasicBlock *LandingPad) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002768 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002769 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer5694b6e2007-04-09 06:17:21 +00002770 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002771 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2772 unsigned BeginLabel = 0, EndLabel = 0;
2773
Jim Laskey735b6f82007-02-22 15:38:06 +00002774 TargetLowering::ArgListTy Args;
2775 TargetLowering::ArgListEntry Entry;
2776 Args.reserve(I.getNumOperands());
2777 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2778 Value *Arg = I.getOperand(i);
2779 SDOperand ArgNode = getValue(Arg);
2780 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00002781
2782 unsigned attrInd = i - OpIdx + 1;
2783 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2784 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2785 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2786 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey735b6f82007-02-22 15:38:06 +00002787 Args.push_back(Entry);
2788 }
2789
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002790 if (ExceptionHandling) {
2791 // Insert a label before the invoke call to mark the try range. This can be
2792 // used to detect deletion of the invoke via the MachineModuleInfo.
2793 BeginLabel = MMI->NextLabelID();
2794 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2795 DAG.getConstant(BeginLabel, MVT::i32)));
2796 }
2797
Jim Laskey735b6f82007-02-22 15:38:06 +00002798 std::pair<SDOperand,SDOperand> Result =
2799 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer18da0722007-04-11 02:44:20 +00002800 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey1da20a72007-02-23 21:45:01 +00002801 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002802 Callee, Args, DAG);
2803 if (I.getType() != Type::VoidTy)
2804 setValue(&I, Result.first);
2805 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002806
2807 if (ExceptionHandling) {
2808 // Insert a label at the end of the invoke call to mark the try range. This
2809 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2810 EndLabel = MMI->NextLabelID();
2811 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2812 DAG.getConstant(EndLabel, MVT::i32)));
2813
2814 // Inform MachineModuleInfo of range.
2815 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2816 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002817}
2818
2819
Chris Lattner1c08c712005-01-07 07:47:53 +00002820void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002821 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002822 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002823 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002824 if (unsigned IID = F->getIntrinsicID()) {
2825 RenameFn = visitIntrinsicCall(I, IID);
2826 if (!RenameFn)
2827 return;
2828 } else { // Not an LLVM intrinsic.
2829 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002830 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2831 if (I.getNumOperands() == 3 && // Basic sanity checks.
2832 I.getOperand(1)->getType()->isFloatingPoint() &&
2833 I.getType() == I.getOperand(1)->getType() &&
2834 I.getType() == I.getOperand(2)->getType()) {
2835 SDOperand LHS = getValue(I.getOperand(1));
2836 SDOperand RHS = getValue(I.getOperand(2));
2837 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2838 LHS, RHS));
2839 return;
2840 }
2841 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002842 if (I.getNumOperands() == 2 && // Basic sanity checks.
2843 I.getOperand(1)->getType()->isFloatingPoint() &&
2844 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002845 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002846 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2847 return;
2848 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002849 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002850 if (I.getNumOperands() == 2 && // Basic sanity checks.
2851 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002852 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002853 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002854 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2855 return;
2856 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002857 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002858 if (I.getNumOperands() == 2 && // Basic sanity checks.
2859 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002860 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002861 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002862 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2863 return;
2864 }
2865 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002866 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002867 } else if (isa<InlineAsm>(I.getOperand(0))) {
2868 visitInlineAsm(I);
2869 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002870 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002871
Chris Lattner64e14b12005-01-08 22:48:57 +00002872 SDOperand Callee;
2873 if (!RenameFn)
2874 Callee = getValue(I.getOperand(0));
2875 else
2876 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002877
Jim Laskey1da20a72007-02-23 21:45:01 +00002878 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002879 I.getCallingConv(),
2880 I.isTailCall(),
2881 Callee,
2882 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002883}
2884
Jim Laskey735b6f82007-02-22 15:38:06 +00002885
Chris Lattner864635a2006-02-22 22:37:12 +00002886SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002887 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002888 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2889 Chain = Val.getValue(1);
2890 Flag = Val.getValue(2);
2891
2892 // If the result was expanded, copy from the top part.
2893 if (Regs.size() > 1) {
2894 assert(Regs.size() == 2 &&
2895 "Cannot expand to more than 2 elts yet!");
2896 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002897 Chain = Hi.getValue(1);
2898 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002899 if (DAG.getTargetLoweringInfo().isLittleEndian())
2900 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2901 else
2902 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002903 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002904
Chris Lattnercf752aa2006-06-08 18:22:48 +00002905 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002906 // appropriate type.
2907 if (RegVT == ValueVT)
2908 return Val;
2909
Chris Lattner5df99b32007-03-25 05:00:54 +00002910 if (MVT::isVector(RegVT)) {
2911 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2912 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2913 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2914 MVT::i32),
2915 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2916 }
2917
Chris Lattnercf752aa2006-06-08 18:22:48 +00002918 if (MVT::isInteger(RegVT)) {
2919 if (ValueVT < RegVT)
2920 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2921 else
2922 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002923 }
Chris Lattner5df99b32007-03-25 05:00:54 +00002924
2925 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2926 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002927}
2928
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002929/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2930/// specified value into the registers specified by this object. This uses
2931/// Chain/Flag as the input and updates them for the output Chain/Flag.
2932void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002933 SDOperand &Chain, SDOperand &Flag,
2934 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002935 if (Regs.size() == 1) {
2936 // If there is a single register and the types differ, this must be
2937 // a promotion.
2938 if (RegVT != ValueVT) {
Chris Lattner5df99b32007-03-25 05:00:54 +00002939 if (MVT::isVector(RegVT)) {
2940 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2941 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002942 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002943 if (RegVT < ValueVT)
2944 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2945 else
2946 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002947 } else if (MVT::isFloatingPoint(RegVT) &&
2948 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002949 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner1a6acc22007-04-09 05:31:20 +00002950 } else if (MVT::getSizeInBits(RegVT) ==
2951 MVT::getSizeInBits(Val.getValueType())) {
2952 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2953 } else {
2954 assert(0 && "Unknown mismatch!");
2955 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002956 }
2957 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2958 Flag = Chain.getValue(1);
2959 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002960 std::vector<unsigned> R(Regs);
2961 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2962 std::reverse(R.begin(), R.end());
2963
2964 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002965 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002966 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002967 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002968 Flag = Chain.getValue(1);
2969 }
2970 }
2971}
Chris Lattner864635a2006-02-22 22:37:12 +00002972
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002973/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2974/// operand list. This adds the code marker and includes the number of
2975/// values added into it.
2976void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002977 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00002978 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2979 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002980 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2981 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2982}
Chris Lattner864635a2006-02-22 22:37:12 +00002983
2984/// isAllocatableRegister - If the specified register is safe to allocate,
2985/// i.e. it isn't a stack pointer or some other special register, return the
2986/// register class for the register. Otherwise, return null.
2987static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002988isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2989 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002990 MVT::ValueType FoundVT = MVT::Other;
2991 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002992 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2993 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002994 MVT::ValueType ThisVT = MVT::Other;
2995
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002996 const TargetRegisterClass *RC = *RCI;
2997 // If none of the the value types for this register class are valid, we
2998 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002999 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3000 I != E; ++I) {
3001 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003002 // If we have already found this register in a different register class,
3003 // choose the one with the largest VT specified. For example, on
3004 // PowerPC, we favor f64 register classes over f32.
3005 if (FoundVT == MVT::Other ||
3006 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3007 ThisVT = *I;
3008 break;
3009 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003010 }
3011 }
3012
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003013 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003014
Chris Lattner864635a2006-02-22 22:37:12 +00003015 // NOTE: This isn't ideal. In particular, this might allocate the
3016 // frame pointer in functions that need it (due to them not being taken
3017 // out of allocation, because a variable sized allocation hasn't been seen
3018 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003019 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3020 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003021 if (*I == Reg) {
3022 // We found a matching register class. Keep looking at others in case
3023 // we find one with larger registers that this physreg is also in.
3024 FoundRC = RC;
3025 FoundVT = ThisVT;
3026 break;
3027 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003028 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003029 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003030}
3031
Chris Lattner4e4b5762006-02-01 18:59:47 +00003032
Chris Lattner0c583402007-04-28 20:49:53 +00003033namespace {
3034/// AsmOperandInfo - This contains information for each constraint that we are
3035/// lowering.
3036struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3037 /// ConstraintCode - This contains the actual string for the code, like "m".
3038 std::string ConstraintCode;
Chris Lattner2a600be2007-04-28 21:01:43 +00003039
3040 /// ConstraintType - Information about the constraint code, e.g. Register,
3041 /// RegisterClass, Memory, Other, Unknown.
3042 TargetLowering::ConstraintType ConstraintType;
Chris Lattner0c583402007-04-28 20:49:53 +00003043
3044 /// CallOperand/CallOperandval - If this is the result output operand or a
3045 /// clobber, this is null, otherwise it is the incoming operand to the
3046 /// CallInst. This gets modified as the asm is processed.
3047 SDOperand CallOperand;
3048 Value *CallOperandVal;
3049
3050 /// ConstraintVT - The ValueType for the operand value.
3051 MVT::ValueType ConstraintVT;
3052
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003053 /// AssignedRegs - If this is a register or register class operand, this
3054 /// contains the set of register corresponding to the operand.
3055 RegsForValue AssignedRegs;
3056
Chris Lattner0c583402007-04-28 20:49:53 +00003057 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattner2a600be2007-04-28 21:01:43 +00003058 : InlineAsm::ConstraintInfo(info),
3059 ConstraintType(TargetLowering::C_Unknown),
Chris Lattner0c583402007-04-28 20:49:53 +00003060 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3061 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003062
3063 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003064
3065 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3066 /// busy in OutputRegs/InputRegs.
3067 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3068 std::set<unsigned> &OutputRegs,
3069 std::set<unsigned> &InputRegs) const {
3070 if (isOutReg)
3071 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3072 if (isInReg)
3073 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3074 }
Chris Lattner0c583402007-04-28 20:49:53 +00003075};
3076} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003077
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003078/// getConstraintGenerality - Return an integer indicating how general CT is.
3079static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3080 switch (CT) {
3081 default: assert(0 && "Unknown constraint type!");
3082 case TargetLowering::C_Other:
3083 case TargetLowering::C_Unknown:
3084 return 0;
3085 case TargetLowering::C_Register:
3086 return 1;
3087 case TargetLowering::C_RegisterClass:
3088 return 2;
3089 case TargetLowering::C_Memory:
3090 return 3;
3091 }
3092}
3093
3094void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3095 assert(!Codes.empty() && "Must have at least one constraint");
3096
3097 std::string *Current = &Codes[0];
3098 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3099 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3100 ConstraintCode = *Current;
3101 ConstraintType = CurType;
3102 return;
3103 }
3104
3105 unsigned CurGenerality = getConstraintGenerality(CurType);
3106
3107 // If we have multiple constraints, try to pick the most general one ahead
3108 // of time. This isn't a wonderful solution, but handles common cases.
3109 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3110 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3111 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3112 if (ThisGenerality > CurGenerality) {
3113 // This constraint letter is more general than the previous one,
3114 // use it.
3115 CurType = ThisType;
3116 Current = &Codes[j];
3117 CurGenerality = ThisGenerality;
3118 }
3119 }
3120
3121 ConstraintCode = *Current;
3122 ConstraintType = CurType;
3123}
3124
3125
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003126void SelectionDAGLowering::
3127GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003128 std::set<unsigned> &OutputRegs,
3129 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003130 // Compute whether this value requires an input register, an output register,
3131 // or both.
3132 bool isOutReg = false;
3133 bool isInReg = false;
3134 switch (OpInfo.Type) {
3135 case InlineAsm::isOutput:
3136 isOutReg = true;
3137
3138 // If this is an early-clobber output, or if there is an input
3139 // constraint that matches this, we need to reserve the input register
3140 // so no other inputs allocate to it.
3141 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3142 break;
3143 case InlineAsm::isInput:
3144 isInReg = true;
3145 isOutReg = false;
3146 break;
3147 case InlineAsm::isClobber:
3148 isOutReg = true;
3149 isInReg = true;
3150 break;
3151 }
3152
3153
3154 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003155 std::vector<unsigned> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003156
3157 // If this is a constraint for a single physreg, or a constraint for a
3158 // register class, find it.
3159 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3160 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3161 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003162
3163 unsigned NumRegs = 1;
3164 if (OpInfo.ConstraintVT != MVT::Other)
3165 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3166 MVT::ValueType RegVT;
3167 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3168
Chris Lattnerbf996f12007-04-30 17:29:31 +00003169
3170 // If this is a constraint for a specific physical register, like {r17},
3171 // assign it now.
3172 if (PhysReg.first) {
3173 if (OpInfo.ConstraintVT == MVT::Other)
3174 ValueVT = *PhysReg.second->vt_begin();
3175
3176 // Get the actual register value type. This is important, because the user
3177 // may have asked for (e.g.) the AX register in i32 type. We need to
3178 // remember that AX is actually i16 to get the right extension.
3179 RegVT = *PhysReg.second->vt_begin();
3180
3181 // This is a explicit reference to a physical register.
3182 Regs.push_back(PhysReg.first);
3183
3184 // If this is an expanded reference, add the rest of the regs to Regs.
3185 if (NumRegs != 1) {
3186 TargetRegisterClass::iterator I = PhysReg.second->begin();
3187 TargetRegisterClass::iterator E = PhysReg.second->end();
3188 for (; *I != PhysReg.first; ++I)
3189 assert(I != E && "Didn't find reg!");
3190
3191 // Already added the first reg.
3192 --NumRegs; ++I;
3193 for (; NumRegs; --NumRegs, ++I) {
3194 assert(I != E && "Ran out of registers to allocate!");
3195 Regs.push_back(*I);
3196 }
3197 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003198 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3199 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3200 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003201 }
3202
3203 // Otherwise, if this was a reference to an LLVM register class, create vregs
3204 // for this reference.
3205 std::vector<unsigned> RegClassRegs;
3206 if (PhysReg.second) {
3207 // If this is an early clobber or tied register, our regalloc doesn't know
3208 // how to maintain the constraint. If it isn't, go ahead and create vreg
3209 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003210 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3211 // If there is some other early clobber and this is an input register,
3212 // then we are forced to pre-allocate the input reg so it doesn't
3213 // conflict with the earlyclobber.
3214 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003215 RegVT = *PhysReg.second->vt_begin();
3216
3217 if (OpInfo.ConstraintVT == MVT::Other)
3218 ValueVT = RegVT;
3219
3220 // Create the appropriate number of virtual registers.
3221 SSARegMap *RegMap = MF.getSSARegMap();
3222 for (; NumRegs; --NumRegs)
3223 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3224
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003225 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3226 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3227 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003228 }
3229
3230 // Otherwise, we can't allocate it. Let the code below figure out how to
3231 // maintain these constraints.
3232 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3233
3234 } else {
3235 // This is a reference to a register class that doesn't directly correspond
3236 // to an LLVM register class. Allocate NumRegs consecutive, available,
3237 // registers from the class.
3238 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3239 OpInfo.ConstraintVT);
3240 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003241
Chris Lattnerbf996f12007-04-30 17:29:31 +00003242 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3243 unsigned NumAllocated = 0;
3244 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3245 unsigned Reg = RegClassRegs[i];
3246 // See if this register is available.
3247 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3248 (isInReg && InputRegs.count(Reg))) { // Already used.
3249 // Make sure we find consecutive registers.
3250 NumAllocated = 0;
3251 continue;
3252 }
3253
3254 // Check to see if this register is allocatable (i.e. don't give out the
3255 // stack pointer).
3256 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3257 if (!RC) {
3258 // Make sure we find consecutive registers.
3259 NumAllocated = 0;
3260 continue;
3261 }
3262
3263 // Okay, this register is good, we can use it.
3264 ++NumAllocated;
3265
3266 // If we allocated enough consecutive registers, succeed.
3267 if (NumAllocated == NumRegs) {
3268 unsigned RegStart = (i-NumAllocated)+1;
3269 unsigned RegEnd = i+1;
3270 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003271 for (unsigned i = RegStart; i != RegEnd; ++i)
3272 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003273
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003274 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3275 OpInfo.ConstraintVT);
3276 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3277 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003278 }
3279 }
3280
3281 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003282 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003283}
3284
3285
Chris Lattnerce7518c2006-01-26 22:24:51 +00003286/// visitInlineAsm - Handle a call to an InlineAsm object.
3287///
3288void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3289 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattnerce7518c2006-01-26 22:24:51 +00003290
Chris Lattner0c583402007-04-28 20:49:53 +00003291 /// ConstraintOperands - Information about all of the constraints.
3292 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003293
3294 SDOperand Chain = getRoot();
3295 SDOperand Flag;
3296
Chris Lattner4e4b5762006-02-01 18:59:47 +00003297 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003298
Chris Lattner0c583402007-04-28 20:49:53 +00003299 // Do a prepass over the constraints, canonicalizing them, and building up the
3300 // ConstraintOperands list.
3301 std::vector<InlineAsm::ConstraintInfo>
3302 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003303
3304 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3305 // constraint. If so, we can't let the register allocator allocate any input
3306 // registers, because it will not know to avoid the earlyclobbered output reg.
3307 bool SawEarlyClobber = false;
3308
3309 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattner0c583402007-04-28 20:49:53 +00003310 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3311 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3312 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3313
Chris Lattner0c583402007-04-28 20:49:53 +00003314 MVT::ValueType OpVT = MVT::Other;
3315
3316 // Compute the value type for each operand.
3317 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003318 case InlineAsm::isOutput:
Chris Lattner0c583402007-04-28 20:49:53 +00003319 if (!OpInfo.isIndirect) {
3320 // The return value of the call is this value. As such, there is no
3321 // corresponding argument.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003322 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3323 OpVT = TLI.getValueType(I.getType());
3324 } else {
Chris Lattner0c583402007-04-28 20:49:53 +00003325 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003326 }
3327 break;
3328 case InlineAsm::isInput:
Chris Lattner0c583402007-04-28 20:49:53 +00003329 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003330 break;
3331 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003332 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003333 break;
3334 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003335
Chris Lattner0c583402007-04-28 20:49:53 +00003336 // If this is an input or an indirect output, process the call argument.
3337 if (OpInfo.CallOperandVal) {
3338 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3339 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner6995cf62007-04-29 18:58:03 +00003340 // If this is an indirect operand, the operand is a pointer to the
3341 // accessed type.
3342 if (OpInfo.isIndirect)
3343 OpTy = cast<PointerType>(OpTy)->getElementType();
3344
3345 // If OpTy is not a first-class value, it may be a struct/union that we
3346 // can tile with integers.
3347 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3348 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3349 switch (BitSize) {
3350 default: break;
3351 case 1:
3352 case 8:
3353 case 16:
3354 case 32:
3355 case 64:
3356 OpTy = IntegerType::get(BitSize);
3357 break;
3358 }
Chris Lattner0c583402007-04-28 20:49:53 +00003359 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003360
3361 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003362 }
3363
3364 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003365
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003366 // Compute the constraint code and ConstraintType to use.
3367 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattner0c583402007-04-28 20:49:53 +00003368
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003369 // Keep track of whether we see an earlyclobber.
3370 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003371
3372 // If this is a memory input, and if the operand is not indirect, do what we
3373 // need to to provide an address for the memory input.
3374 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3375 !OpInfo.isIndirect) {
3376 assert(OpInfo.Type == InlineAsm::isInput &&
3377 "Can only indirectify direct input operands!");
3378
3379 // Memory operands really want the address of the value. If we don't have
3380 // an indirect input, put it in the constpool if we can, otherwise spill
3381 // it to a stack slot.
3382
3383 // If the operand is a float, integer, or vector constant, spill to a
3384 // constant pool entry to get its address.
3385 Value *OpVal = OpInfo.CallOperandVal;
3386 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3387 isa<ConstantVector>(OpVal)) {
3388 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3389 TLI.getPointerTy());
3390 } else {
3391 // Otherwise, create a stack slot and emit a store to it before the
3392 // asm.
3393 const Type *Ty = OpVal->getType();
3394 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3395 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3396 MachineFunction &MF = DAG.getMachineFunction();
3397 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3398 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3399 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3400 OpInfo.CallOperand = StackSlot;
3401 }
3402
3403 // There is no longer a Value* corresponding to this operand.
3404 OpInfo.CallOperandVal = 0;
3405 // It is now an indirect operand.
3406 OpInfo.isIndirect = true;
3407 }
3408
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003409 // If this constraint is for a specific register, allocate it before
3410 // anything else.
3411 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3412 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003413 }
Chris Lattner0c583402007-04-28 20:49:53 +00003414 ConstraintInfos.clear();
3415
3416
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003417 // Second pass - Loop over all of the operands, assigning virtual or physregs
3418 // to registerclass operands.
3419 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3420 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3421
3422 // C_Register operands have already been allocated, Other/Memory don't need
3423 // to be.
3424 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3425 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3426 }
3427
Chris Lattner0c583402007-04-28 20:49:53 +00003428 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3429 std::vector<SDOperand> AsmNodeOperands;
3430 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3431 AsmNodeOperands.push_back(
3432 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3433
Chris Lattner2cc2f662006-02-01 01:28:23 +00003434
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003435 // Loop over all of the inputs, copying the operand values into the
3436 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003437 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003438
Chris Lattner0c583402007-04-28 20:49:53 +00003439 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3440 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3441
3442 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3443 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003444
Chris Lattner0c583402007-04-28 20:49:53 +00003445 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003446 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003447 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3448 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003449 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003450 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003451
Chris Lattner22873462006-02-27 23:45:39 +00003452 // Add information to the INLINEASM node to know about this output.
3453 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003454 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3455 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003456 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003457 break;
3458 }
3459
Chris Lattner2a600be2007-04-28 21:01:43 +00003460 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003461
Chris Lattner864635a2006-02-22 22:37:12 +00003462 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003463 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003464 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003465 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003466 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003467 exit(1);
3468 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003469
Chris Lattner0c583402007-04-28 20:49:53 +00003470 if (!OpInfo.isIndirect) {
3471 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003472 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003473 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003474 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003475 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003476 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003477 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003478 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003479 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003480
3481 // Add information to the INLINEASM node to know that this register is
3482 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003483 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3484 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003485 break;
3486 }
3487 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003488 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003489
Chris Lattner0c583402007-04-28 20:49:53 +00003490 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003491 // If this is required to match an output register we have already set,
3492 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003493 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003494
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003495 // Scan until we find the definition we already emitted of this operand.
3496 // When we find it, create a RegsForValue operand.
3497 unsigned CurOp = 2; // The first operand.
3498 for (; OperandNo; --OperandNo) {
3499 // Advance to the next operand.
3500 unsigned NumOps =
3501 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003502 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3503 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003504 "Skipped past definitions?");
3505 CurOp += (NumOps>>3)+1;
3506 }
3507
3508 unsigned NumOps =
3509 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003510 if ((NumOps & 7) == 2 /*REGDEF*/) {
3511 // Add NumOps>>3 registers to MatchedRegs.
3512 RegsForValue MatchedRegs;
3513 MatchedRegs.ValueVT = InOperandVal.getValueType();
3514 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3515 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3516 unsigned Reg =
3517 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3518 MatchedRegs.Regs.push_back(Reg);
3519 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003520
Chris Lattner527fae12007-02-01 01:21:12 +00003521 // Use the produced MatchedRegs object to
3522 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3523 TLI.getPointerTy());
3524 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3525 break;
3526 } else {
3527 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3528 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003529 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003530 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003531
Chris Lattner2a600be2007-04-28 21:01:43 +00003532 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00003533 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003534 "Don't know how to handle indirect other inputs yet!");
3535
Chris Lattner53069fb2006-10-31 19:41:18 +00003536 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattner0c583402007-04-28 20:49:53 +00003537 OpInfo.ConstraintCode[0],
3538 DAG);
Chris Lattner53069fb2006-10-31 19:41:18 +00003539 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00003540 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003541 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003542 exit(1);
3543 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003544
3545 // Add information to the INLINEASM node to know about this input.
3546 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003547 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3548 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003549 AsmNodeOperands.push_back(InOperandVal);
3550 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00003551 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003552 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00003553 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3554 "Memory operands expect pointer values");
3555
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003556 // Add information to the INLINEASM node to know about this input.
3557 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003558 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3559 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003560 AsmNodeOperands.push_back(InOperandVal);
3561 break;
3562 }
3563
Chris Lattner2a600be2007-04-28 21:01:43 +00003564 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3565 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3566 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00003567 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003568 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003569
3570 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003571 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3572 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003573
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003574 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3575 TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003576
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003577 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3578 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003579 break;
3580 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003581 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003582 // Add the clobbered value to the operand list, so that the register
3583 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003584 if (!OpInfo.AssignedRegs.Regs.empty())
3585 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3586 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003587 break;
3588 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003589 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003590 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003591
3592 // Finish up input operands.
3593 AsmNodeOperands[0] = Chain;
3594 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3595
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003596 Chain = DAG.getNode(ISD::INLINEASM,
3597 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003598 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003599 Flag = Chain.getValue(1);
3600
Chris Lattner6656dd12006-01-31 02:03:41 +00003601 // If this asm returns a register value, copy the result from that register
3602 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003603 if (!RetValRegs.Regs.empty()) {
3604 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3605
3606 // If the result of the inline asm is a vector, it may have the wrong
3607 // width/num elts. Make sure to convert it to the right type with
3608 // vbit_convert.
3609 if (Val.getValueType() == MVT::Vector) {
3610 const VectorType *VTy = cast<VectorType>(I.getType());
3611 unsigned DesiredNumElts = VTy->getNumElements();
3612 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3613
3614 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3615 DAG.getConstant(DesiredNumElts, MVT::i32),
3616 DAG.getValueType(DesiredEltVT));
3617 }
3618
3619 setValue(&I, Val);
3620 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003621
Chris Lattner6656dd12006-01-31 02:03:41 +00003622 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3623
3624 // Process indirect outputs, first output all of the flagged copies out of
3625 // physregs.
3626 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003627 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003628 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00003629 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3630 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003631 }
3632
3633 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003634 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003635 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00003636 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003637 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003638 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003639 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003640 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3641 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003642 DAG.setRoot(Chain);
3643}
3644
3645
Chris Lattner1c08c712005-01-07 07:47:53 +00003646void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3647 SDOperand Src = getValue(I.getOperand(0));
3648
3649 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003650
3651 if (IntPtr < Src.getValueType())
3652 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3653 else if (IntPtr > Src.getValueType())
3654 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003655
3656 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003657 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003658 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3659 Src, getIntPtrConstant(ElementSize));
3660
Reid Spencer47857812006-12-31 05:55:36 +00003661 TargetLowering::ArgListTy Args;
3662 TargetLowering::ArgListEntry Entry;
3663 Entry.Node = Src;
3664 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003665 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003666
3667 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003668 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003669 DAG.getExternalSymbol("malloc", IntPtr),
3670 Args, DAG);
3671 setValue(&I, Result.first); // Pointers always fit in registers
3672 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003673}
3674
3675void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003676 TargetLowering::ArgListTy Args;
3677 TargetLowering::ArgListEntry Entry;
3678 Entry.Node = getValue(I.getOperand(0));
3679 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003680 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003681 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003682 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003683 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003684 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3685 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003686}
3687
Chris Lattner025c39b2005-08-26 20:54:47 +00003688// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3689// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3690// instructions are special in various ways, which require special support to
3691// insert. The specified MachineInstr is created but not inserted into any
3692// basic blocks, and the scheduler passes ownership of it to this method.
3693MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3694 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003695 cerr << "If a target marks an instruction with "
3696 << "'usesCustomDAGSchedInserter', it must implement "
3697 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003698 abort();
3699 return 0;
3700}
3701
Chris Lattner39ae3622005-01-09 00:00:49 +00003702void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003703 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3704 getValue(I.getOperand(1)),
3705 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003706}
3707
3708void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003709 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3710 getValue(I.getOperand(0)),
3711 DAG.getSrcValue(I.getOperand(0)));
3712 setValue(&I, V);
3713 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003714}
3715
3716void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003717 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3718 getValue(I.getOperand(1)),
3719 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003720}
3721
3722void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003723 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3724 getValue(I.getOperand(1)),
3725 getValue(I.getOperand(2)),
3726 DAG.getSrcValue(I.getOperand(1)),
3727 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003728}
3729
Evan Chengb15974a2006-12-12 07:27:38 +00003730/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3731/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3732static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3733 unsigned &i, SelectionDAG &DAG,
3734 TargetLowering &TLI) {
3735 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3736 return SDOperand(Arg, i++);
3737
3738 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3739 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3740 if (NumVals == 1) {
3741 return DAG.getNode(ISD::BIT_CONVERT, VT,
3742 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3743 } else if (NumVals == 2) {
3744 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3745 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3746 if (!TLI.isLittleEndian())
3747 std::swap(Lo, Hi);
3748 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3749 } else {
3750 // Value scalarized into many values. Unimp for now.
3751 assert(0 && "Cannot expand i64 -> i16 yet!");
3752 }
3753 return SDOperand();
3754}
3755
Chris Lattnerfdfded52006-04-12 16:20:43 +00003756/// TargetLowering::LowerArguments - This is the default LowerArguments
3757/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003758/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3759/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003760std::vector<SDOperand>
3761TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003762 const FunctionType *FTy = F.getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +00003763 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003764 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3765 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003766 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003767 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3768 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3769
3770 // Add one result value for each formal argument.
3771 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003772 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003773 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3774 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003775 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003776 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003777 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003778 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003779
Chris Lattnerddf53e42007-02-26 02:56:58 +00003780 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3781 // that is zero extended!
Reid Spencer18da0722007-04-11 02:44:20 +00003782 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003783 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer18da0722007-04-11 02:44:20 +00003784 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003785 Flags |= ISD::ParamFlags::SExt;
Reid Spencer18da0722007-04-11 02:44:20 +00003786 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003787 Flags |= ISD::ParamFlags::InReg;
Reid Spencer18da0722007-04-11 02:44:20 +00003788 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003789 Flags |= ISD::ParamFlags::StructReturn;
3790 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003791
Chris Lattnerfdfded52006-04-12 16:20:43 +00003792 switch (getTypeAction(VT)) {
3793 default: assert(0 && "Unknown type action!");
3794 case Legal:
3795 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003796 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003797 break;
3798 case Promote:
3799 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003800 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003801 break;
3802 case Expand:
3803 if (VT != MVT::Vector) {
3804 // If this is a large integer, it needs to be broken up into small
3805 // integers. Figure out what the destination type is and how many small
3806 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003807 MVT::ValueType NVT = getTypeToExpandTo(VT);
3808 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003809 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003810 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003811 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003812 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003813 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3814 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003815 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3816 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003817 } else {
3818 // Otherwise, this is a vector type. We only support legal vectors
3819 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003820 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3821 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003822
Chris Lattnerfdfded52006-04-12 16:20:43 +00003823 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003824 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003825 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3826 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3827 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003828 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003829 } else {
3830 assert(0 && "Don't support illegal by-val vector arguments yet!");
3831 }
3832 }
3833 break;
3834 }
3835 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003836
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003837 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003838
3839 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003840 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3841 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003842 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003843
3844 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003845
3846 // Set up the return result vector.
3847 Ops.clear();
3848 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003849 unsigned Idx = 1;
3850 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3851 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003852 MVT::ValueType VT = getValueType(I->getType());
3853
3854 switch (getTypeAction(VT)) {
3855 default: assert(0 && "Unknown type action!");
3856 case Legal:
3857 Ops.push_back(SDOperand(Result, i++));
3858 break;
3859 case Promote: {
3860 SDOperand Op(Result, i++);
3861 if (MVT::isInteger(VT)) {
Reid Spencer18da0722007-04-11 02:44:20 +00003862 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003863 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3864 DAG.getValueType(VT));
Reid Spencer18da0722007-04-11 02:44:20 +00003865 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003866 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3867 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003868 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3869 } else {
3870 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3871 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3872 }
3873 Ops.push_back(Op);
3874 break;
3875 }
3876 case Expand:
3877 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003878 // If this is a large integer or a floating point node that needs to be
3879 // expanded, it needs to be reassembled from small integers. Figure out
3880 // what the source elt type is and how many small integers it is.
3881 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003882 } else {
3883 // Otherwise, this is a vector type. We only support legal vectors
3884 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003885 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003886 unsigned NumElems = PTy->getNumElements();
3887 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003888
Chris Lattnerfdfded52006-04-12 16:20:43 +00003889 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003890 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003891 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003892 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003893 SDOperand N = SDOperand(Result, i++);
3894 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003895 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3896 DAG.getConstant(NumElems, MVT::i32),
3897 DAG.getValueType(getValueType(EltTy)));
3898 Ops.push_back(N);
3899 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003900 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003901 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003902 }
3903 }
3904 break;
3905 }
3906 }
3907 return Ops;
3908}
3909
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003910
Evan Chengb15974a2006-12-12 07:27:38 +00003911/// ExpandScalarCallArgs - Recursively expand call argument node by
3912/// bit_converting it or extract a pair of elements from the larger node.
3913static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003914 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003915 SmallVector<SDOperand, 32> &Ops,
3916 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003917 TargetLowering &TLI,
3918 bool isFirst = true) {
3919
Evan Chengb15974a2006-12-12 07:27:38 +00003920 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003921 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003922 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003923 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3924 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003925 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003926 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003927 return;
3928 }
3929
3930 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3931 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3932 if (NumVals == 1) {
3933 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003934 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003935 } else if (NumVals == 2) {
3936 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3937 DAG.getConstant(0, TLI.getPointerTy()));
3938 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3939 DAG.getConstant(1, TLI.getPointerTy()));
3940 if (!TLI.isLittleEndian())
3941 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003942 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3943 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003944 } else {
3945 // Value scalarized into many values. Unimp for now.
3946 assert(0 && "Cannot expand i64 -> i16 yet!");
3947 }
3948}
3949
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003950/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3951/// implementation, which just inserts an ISD::CALL node, which is later custom
3952/// lowered by the target to something concrete. FIXME: When all targets are
3953/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3954std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003955TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3956 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003957 unsigned CallingConv, bool isTailCall,
3958 SDOperand Callee,
3959 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003960 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003961 Ops.push_back(Chain); // Op#0 - Chain
3962 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3963 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3964 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3965 Ops.push_back(Callee);
3966
3967 // Handle all of the outgoing arguments.
3968 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003969 MVT::ValueType VT = getValueType(Args[i].Ty);
3970 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003971 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003972 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003973 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003974
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003975 if (Args[i].isSExt)
3976 Flags |= ISD::ParamFlags::SExt;
3977 if (Args[i].isZExt)
3978 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003979 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003980 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003981 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003982 Flags |= ISD::ParamFlags::StructReturn;
3983 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003984
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003985 switch (getTypeAction(VT)) {
3986 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003987 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003988 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003989 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003990 break;
3991 case Promote:
3992 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003993 unsigned ExtOp;
3994 if (Args[i].isSExt)
3995 ExtOp = ISD::SIGN_EXTEND;
3996 else if (Args[i].isZExt)
3997 ExtOp = ISD::ZERO_EXTEND;
3998 else
3999 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004000 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4001 } else {
4002 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
4003 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
4004 }
4005 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004006 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004007 break;
4008 case Expand:
4009 if (VT != MVT::Vector) {
4010 // If this is a large integer, it needs to be broken down into small
4011 // integers. Figure out what the source elt type is and how many small
4012 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004013 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004014 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00004015 // Otherwise, this is a vector type. We only support legal vectors
4016 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004017 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00004018 unsigned NumElems = PTy->getNumElements();
4019 const Type *EltTy = PTy->getElementType();
4020
4021 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004022 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00004023 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00004024 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00004025 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00004026 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4027 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004028 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00004029 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00004030 assert(0 && "Don't support illegal by-val vector call args yet!");
4031 abort();
4032 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004033 }
4034 break;
4035 }
4036 }
4037
4038 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00004039 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004040
4041 if (RetTy != Type::VoidTy) {
4042 MVT::ValueType VT = getValueType(RetTy);
4043 switch (getTypeAction(VT)) {
4044 default: assert(0 && "Unknown type action!");
4045 case Legal:
4046 RetTys.push_back(VT);
4047 break;
4048 case Promote:
4049 RetTys.push_back(getTypeToTransformTo(VT));
4050 break;
4051 case Expand:
4052 if (VT != MVT::Vector) {
4053 // If this is a large integer, it needs to be reassembled from small
4054 // integers. Figure out what the source elt type is and how many small
4055 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00004056 MVT::ValueType NVT = getTypeToExpandTo(VT);
4057 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004058 for (unsigned i = 0; i != NumVals; ++i)
4059 RetTys.push_back(NVT);
4060 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00004061 // Otherwise, this is a vector type. We only support legal vectors
4062 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004063 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00004064 unsigned NumElems = PTy->getNumElements();
4065 const Type *EltTy = PTy->getElementType();
4066
4067 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004068 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00004069 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4070 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4071 RetTys.push_back(TVT);
4072 } else {
4073 assert(0 && "Don't support illegal by-val vector call results yet!");
4074 abort();
4075 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004076 }
4077 }
4078 }
4079
4080 RetTys.push_back(MVT::Other); // Always has a chain.
4081
4082 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004083 SDOperand Res = DAG.getNode(ISD::CALL,
4084 DAG.getVTList(&RetTys[0], RetTys.size()),
4085 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004086
4087 // This returns a pair of operands. The first element is the
4088 // return value for the function (if RetTy is not VoidTy). The second
4089 // element is the outgoing token chain.
4090 SDOperand ResVal;
4091 if (RetTys.size() != 1) {
4092 MVT::ValueType VT = getValueType(RetTy);
4093 if (RetTys.size() == 2) {
4094 ResVal = Res;
4095
4096 // If this value was promoted, truncate it down.
4097 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00004098 if (VT == MVT::Vector) {
Chris Lattner5df99b32007-03-25 05:00:54 +00004099 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerda098e72006-05-16 23:39:44 +00004100 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004101 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4102 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00004103
4104 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00004105 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00004106 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00004107 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00004108 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4109 // "N x PTyElementVT" MVT::Vector type.
4110 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00004111 DAG.getConstant(NumElems, MVT::i32),
4112 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00004113 } else {
4114 abort();
4115 }
4116 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00004117 unsigned AssertOp = ISD::AssertSext;
4118 if (!RetTyIsSigned)
4119 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004120 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4121 DAG.getValueType(VT));
4122 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4123 } else {
4124 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00004125 if (getTypeAction(VT) == Expand)
4126 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4127 else
4128 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004129 }
4130 }
4131 } else if (RetTys.size() == 3) {
4132 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4133 Res.getValue(0), Res.getValue(1));
4134
4135 } else {
4136 assert(0 && "Case not handled yet!");
4137 }
4138 }
4139
4140 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4141}
4142
Chris Lattner50381b62005-05-14 05:50:48 +00004143SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004144 assert(0 && "LowerOperation not implemented for this target!");
4145 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004146 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004147}
4148
Nate Begeman0aed7842006-01-28 03:14:31 +00004149SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4150 SelectionDAG &DAG) {
4151 assert(0 && "CustomPromoteOperation not implemented for this target!");
4152 abort();
4153 return SDOperand();
4154}
4155
Evan Cheng74d0aa92006-02-15 21:59:04 +00004156/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004157/// operand.
4158static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004159 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004160 MVT::ValueType CurVT = VT;
4161 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4162 uint64_t Val = C->getValue() & 255;
4163 unsigned Shift = 8;
4164 while (CurVT != MVT::i8) {
4165 Val = (Val << Shift) | Val;
4166 Shift <<= 1;
4167 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004168 }
4169 return DAG.getConstant(Val, VT);
4170 } else {
4171 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4172 unsigned Shift = 8;
4173 while (CurVT != MVT::i8) {
4174 Value =
4175 DAG.getNode(ISD::OR, VT,
4176 DAG.getNode(ISD::SHL, VT, Value,
4177 DAG.getConstant(Shift, MVT::i8)), Value);
4178 Shift <<= 1;
4179 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004180 }
4181
4182 return Value;
4183 }
4184}
4185
Evan Cheng74d0aa92006-02-15 21:59:04 +00004186/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4187/// used when a memcpy is turned into a memset when the source is a constant
4188/// string ptr.
4189static SDOperand getMemsetStringVal(MVT::ValueType VT,
4190 SelectionDAG &DAG, TargetLowering &TLI,
4191 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004192 uint64_t Val = 0;
Dan Gohmanb55757e2007-05-18 17:52:13 +00004193 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004194 if (TLI.isLittleEndian())
4195 Offset = Offset + MSB - 1;
4196 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004197 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004198 Offset += TLI.isLittleEndian() ? -1 : 1;
4199 }
4200 return DAG.getConstant(Val, VT);
4201}
4202
Evan Cheng1db92f92006-02-14 08:22:34 +00004203/// getMemBasePlusOffset - Returns base and offset node for the
4204static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4205 SelectionDAG &DAG, TargetLowering &TLI) {
4206 MVT::ValueType VT = Base.getValueType();
4207 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4208}
4209
Evan Chengc4f8eee2006-02-14 20:12:38 +00004210/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004211/// to replace the memset / memcpy is below the threshold. It also returns the
4212/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004213static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4214 unsigned Limit, uint64_t Size,
4215 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004216 MVT::ValueType VT;
4217
4218 if (TLI.allowsUnalignedMemoryAccesses()) {
4219 VT = MVT::i64;
4220 } else {
4221 switch (Align & 7) {
4222 case 0:
4223 VT = MVT::i64;
4224 break;
4225 case 4:
4226 VT = MVT::i32;
4227 break;
4228 case 2:
4229 VT = MVT::i16;
4230 break;
4231 default:
4232 VT = MVT::i8;
4233 break;
4234 }
4235 }
4236
Evan Cheng80e89d72006-02-14 09:11:59 +00004237 MVT::ValueType LVT = MVT::i64;
4238 while (!TLI.isTypeLegal(LVT))
4239 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4240 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004241
Evan Cheng80e89d72006-02-14 09:11:59 +00004242 if (VT > LVT)
4243 VT = LVT;
4244
Evan Chengdea72452006-02-14 23:05:54 +00004245 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004246 while (Size != 0) {
Dan Gohmanb55757e2007-05-18 17:52:13 +00004247 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng1db92f92006-02-14 08:22:34 +00004248 while (VTSize > Size) {
4249 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004250 VTSize >>= 1;
4251 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004252 assert(MVT::isInteger(VT));
4253
4254 if (++NumMemOps > Limit)
4255 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004256 MemOps.push_back(VT);
4257 Size -= VTSize;
4258 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004259
4260 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004261}
4262
Chris Lattner7041ee32005-01-11 05:56:49 +00004263void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004264 SDOperand Op1 = getValue(I.getOperand(1));
4265 SDOperand Op2 = getValue(I.getOperand(2));
4266 SDOperand Op3 = getValue(I.getOperand(3));
4267 SDOperand Op4 = getValue(I.getOperand(4));
4268 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4269 if (Align == 0) Align = 1;
4270
4271 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4272 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004273
4274 // Expand memset / memcpy to a series of load / store ops
4275 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004276 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004277 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004278 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004279 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004280 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4281 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004282 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004283 unsigned Offset = 0;
4284 for (unsigned i = 0; i < NumMemOps; i++) {
4285 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004286 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004287 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004288 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004289 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004290 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004291 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004292 Offset += VTSize;
4293 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004294 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004295 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004296 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004297 case ISD::MEMCPY: {
4298 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4299 Size->getValue(), Align, TLI)) {
4300 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004301 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004302 GlobalAddressSDNode *G = NULL;
4303 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004304 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004305
4306 if (Op2.getOpcode() == ISD::GlobalAddress)
4307 G = cast<GlobalAddressSDNode>(Op2);
4308 else if (Op2.getOpcode() == ISD::ADD &&
4309 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4310 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4311 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004312 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004313 }
4314 if (G) {
4315 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004316 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004317 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004318 if (!Str.empty()) {
4319 CopyFromStr = true;
4320 SrcOff += SrcDelta;
4321 }
4322 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004323 }
4324
Evan Chengc080d6f2006-02-15 01:54:51 +00004325 for (unsigned i = 0; i < NumMemOps; i++) {
4326 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004327 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004328 SDOperand Value, Chain, Store;
4329
Evan Chengcffbb512006-02-16 23:11:42 +00004330 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004331 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4332 Chain = getRoot();
4333 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004334 DAG.getStore(Chain, Value,
4335 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004336 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004337 } else {
4338 Value = DAG.getLoad(VT, getRoot(),
4339 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00004340 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004341 Chain = Value.getValue(1);
4342 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004343 DAG.getStore(Chain, Value,
4344 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004345 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004346 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004347 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004348 SrcOff += VTSize;
4349 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004350 }
4351 }
4352 break;
4353 }
4354 }
4355
4356 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004357 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4358 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004359 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004360 }
4361 }
4362
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004363 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00004364}
4365
Chris Lattner7041ee32005-01-11 05:56:49 +00004366//===----------------------------------------------------------------------===//
4367// SelectionDAGISel code
4368//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004369
4370unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4371 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4372}
4373
Chris Lattner495a0b52005-08-17 06:37:43 +00004374void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004375 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004376 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004377}
Chris Lattner1c08c712005-01-07 07:47:53 +00004378
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004379
Chris Lattnerbad7f482006-10-28 19:22:10 +00004380
Chris Lattner1c08c712005-01-07 07:47:53 +00004381bool SelectionDAGISel::runOnFunction(Function &Fn) {
4382 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4383 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004384 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004385
4386 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4387
4388 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4389 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004390
Evan Chengad2070c2007-02-10 02:43:39 +00004391 // Add function live-ins to entry block live-in set.
4392 BasicBlock *EntryBB = &Fn.getEntryBlock();
4393 BB = FuncInfo.MBBMap[EntryBB];
4394 if (!MF.livein_empty())
4395 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4396 E = MF.livein_end(); I != E; ++I)
4397 BB->addLiveIn(I->first);
4398
Chris Lattner1c08c712005-01-07 07:47:53 +00004399 return true;
4400}
4401
Chris Lattner571e4342006-10-27 21:36:01 +00004402SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4403 unsigned Reg) {
4404 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004405 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004406 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004407 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004408
4409 // If this type is not legal, we must make sure to not create an invalid
4410 // register use.
4411 MVT::ValueType SrcVT = Op.getValueType();
4412 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004413 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004414 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004415 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004416 // Handle copies from generic vectors to registers.
4417 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004418 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004419 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004420
Chris Lattner70c2a612006-03-31 02:06:56 +00004421 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4422 // MVT::Vector type.
4423 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4424 DAG.getConstant(NE, MVT::i32),
4425 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004426
Chris Lattner70c2a612006-03-31 02:06:56 +00004427 // Loop over all of the elements of the resultant vector,
4428 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4429 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004430 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004431 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004432 for (unsigned i = 0; i != NE; ++i) {
4433 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004434 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004435 if (PTyElementVT == PTyLegalElementVT) {
4436 // Elements are legal.
4437 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4438 } else if (PTyLegalElementVT > PTyElementVT) {
4439 // Elements are promoted.
4440 if (MVT::isFloatingPoint(PTyLegalElementVT))
4441 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4442 else
4443 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4444 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4445 } else {
4446 // Elements are expanded.
4447 // The src value is expanded into multiple registers.
4448 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004449 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004450 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004451 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004452 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4453 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4454 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004455 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004456 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4457 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004458 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004459 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004460 if (MVT::isFloatingPoint(SrcVT))
4461 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4462 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004463 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004464 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004465 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004466 DestVT = TLI.getTypeToExpandTo(SrcVT);
4467 unsigned NumVals = TLI.getNumElements(SrcVT);
4468 if (NumVals == 1)
4469 return DAG.getCopyToReg(getRoot(), Reg,
4470 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4471 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004472 // The src value is expanded into multiple registers.
4473 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004474 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004475 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004476 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004477 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004478 return DAG.getCopyToReg(Op, Reg+1, Hi);
4479 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004480}
4481
Chris Lattner068a81e2005-01-17 17:15:02 +00004482void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004483LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004484 std::vector<SDOperand> &UnorderedChains) {
4485 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004486 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004487 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004488 SDOperand OldRoot = SDL.DAG.getRoot();
4489 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004490
Chris Lattnerbf209482005-10-30 19:42:35 +00004491 unsigned a = 0;
4492 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4493 AI != E; ++AI, ++a)
4494 if (!AI->use_empty()) {
4495 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004496
Chris Lattnerbf209482005-10-30 19:42:35 +00004497 // If this argument is live outside of the entry block, insert a copy from
4498 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004499 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4500 if (VMI != FuncInfo.ValueMap.end()) {
4501 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004502 UnorderedChains.push_back(Copy);
4503 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004504 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004505
Chris Lattnerbf209482005-10-30 19:42:35 +00004506 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004507 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004508 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004509}
4510
Chris Lattner1c08c712005-01-07 07:47:53 +00004511void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4512 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004513 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004514 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004515
4516 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004517
Chris Lattnerbf209482005-10-30 19:42:35 +00004518 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004519 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004520 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004521
4522 BB = FuncInfo.MBBMap[LLVMBB];
4523 SDL.setCurrentBasicBlock(BB);
4524
4525 // Lower all of the non-terminator instructions.
4526 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4527 I != E; ++I)
4528 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004529
4530 // Lower call part of invoke.
4531 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4532 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004533
Chris Lattner1c08c712005-01-07 07:47:53 +00004534 // Ensure that all instructions which are used outside of their defining
4535 // blocks are available as virtual registers.
4536 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004537 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004538 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004539 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004540 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004541 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004542 }
4543
4544 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4545 // ensure constants are generated when needed. Remember the virtual registers
4546 // that need to be added to the Machine PHI nodes as input. We cannot just
4547 // directly add them, because expansion might result in multiple MBB's for one
4548 // BB. As such, the start of the BB might correspond to a different MBB than
4549 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004550 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004551 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004552
4553 // Emit constants only once even if used by multiple PHI nodes.
4554 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004555
Chris Lattner8c494ab2006-10-27 23:50:33 +00004556 // Vector bool would be better, but vector<bool> is really slow.
4557 std::vector<unsigned char> SuccsHandled;
4558 if (TI->getNumSuccessors())
4559 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4560
Chris Lattner1c08c712005-01-07 07:47:53 +00004561 // Check successor nodes PHI nodes that expect a constant to be available from
4562 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004563 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4564 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004565 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004566 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004567
Chris Lattner8c494ab2006-10-27 23:50:33 +00004568 // If this terminator has multiple identical successors (common for
4569 // switches), only handle each succ once.
4570 unsigned SuccMBBNo = SuccMBB->getNumber();
4571 if (SuccsHandled[SuccMBBNo]) continue;
4572 SuccsHandled[SuccMBBNo] = true;
4573
4574 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004575 PHINode *PN;
4576
4577 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4578 // nodes and Machine PHI nodes, but the incoming operands have not been
4579 // emitted yet.
4580 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004581 (PN = dyn_cast<PHINode>(I)); ++I) {
4582 // Ignore dead phi's.
4583 if (PN->use_empty()) continue;
4584
4585 unsigned Reg;
4586 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004587
Chris Lattner8c494ab2006-10-27 23:50:33 +00004588 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4589 unsigned &RegOut = ConstantsOut[C];
4590 if (RegOut == 0) {
4591 RegOut = FuncInfo.CreateRegForValue(C);
4592 UnorderedChains.push_back(
4593 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004594 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004595 Reg = RegOut;
4596 } else {
4597 Reg = FuncInfo.ValueMap[PHIOp];
4598 if (Reg == 0) {
4599 assert(isa<AllocaInst>(PHIOp) &&
4600 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4601 "Didn't codegen value into a register!??");
4602 Reg = FuncInfo.CreateRegForValue(PHIOp);
4603 UnorderedChains.push_back(
4604 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004605 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004606 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004607
4608 // Remember that this register needs to added to the machine PHI node as
4609 // the input for this MBB.
4610 MVT::ValueType VT = TLI.getValueType(PN->getType());
4611 unsigned NumElements;
4612 if (VT != MVT::Vector)
4613 NumElements = TLI.getNumElements(VT);
4614 else {
4615 MVT::ValueType VT1,VT2;
4616 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004617 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004618 VT1, VT2);
4619 }
4620 for (unsigned i = 0, e = NumElements; i != e; ++i)
4621 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4622 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004623 }
4624 ConstantsOut.clear();
4625
Chris Lattnerddb870b2005-01-13 17:59:43 +00004626 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004627 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004628 SDOperand Root = SDL.getRoot();
4629 if (Root.getOpcode() != ISD::EntryToken) {
4630 unsigned i = 0, e = UnorderedChains.size();
4631 for (; i != e; ++i) {
4632 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4633 if (UnorderedChains[i].Val->getOperand(0) == Root)
4634 break; // Don't add the root if we already indirectly depend on it.
4635 }
4636
4637 if (i == e)
4638 UnorderedChains.push_back(Root);
4639 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004640 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4641 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004642 }
4643
Chris Lattner1c08c712005-01-07 07:47:53 +00004644 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004645 if (Invoke) {
4646 // Just the branch part of invoke.
4647 SDL.visitInvoke(*Invoke, true);
4648 } else {
4649 SDL.visit(*LLVMBB->getTerminator());
4650 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004651
Nate Begemanf15485a2006-03-27 01:32:24 +00004652 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004653 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004654 SwitchCases.clear();
4655 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004656 JTCases.clear();
4657 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004658 BitTestCases.clear();
4659 BitTestCases = SDL.BitTestCases;
4660
Chris Lattnera651cf62005-01-17 19:43:36 +00004661 // Make sure the root of the DAG is up-to-date.
4662 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004663}
4664
Nate Begemanf15485a2006-03-27 01:32:24 +00004665void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004666 // Get alias analysis for load/store combining.
4667 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4668
Chris Lattneraf21d552005-10-10 16:47:10 +00004669 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004670 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004671
Bill Wendling832171c2006-12-07 20:04:42 +00004672 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004673 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004674
Chris Lattner1c08c712005-01-07 07:47:53 +00004675 // Second step, hack on the DAG until it only uses operations and types that
4676 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004677 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004678
Bill Wendling832171c2006-12-07 20:04:42 +00004679 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004680 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004681
Chris Lattneraf21d552005-10-10 16:47:10 +00004682 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004683 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004684
Evan Chenga9c20912006-01-21 02:32:06 +00004685 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004686
Chris Lattnera33ef482005-03-30 01:10:47 +00004687 // Third, instruction select all of the operations to machine code, adding the
4688 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004689 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004690
Bill Wendling832171c2006-12-07 20:04:42 +00004691 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004692 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004693}
Chris Lattner1c08c712005-01-07 07:47:53 +00004694
Nate Begemanf15485a2006-03-27 01:32:24 +00004695void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4696 FunctionLoweringInfo &FuncInfo) {
4697 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4698 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004699 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004700 CurDAG = &DAG;
4701
4702 // First step, lower LLVM code to some DAG. This DAG may use operations and
4703 // types that are not supported by the target.
4704 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4705
4706 // Second step, emit the lowered DAG as machine code.
4707 CodeGenAndEmitDAG(DAG);
4708 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004709
4710 DOUT << "Total amount of phi nodes to update: "
4711 << PHINodesToUpdate.size() << "\n";
4712 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4713 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4714 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004715
Chris Lattnera33ef482005-03-30 01:10:47 +00004716 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004717 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004718 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004719 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4720 MachineInstr *PHI = PHINodesToUpdate[i].first;
4721 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4722 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004723 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004724 PHI->addMachineBasicBlockOperand(BB);
4725 }
4726 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004727 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004728
4729 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4730 // Lower header first, if it wasn't already lowered
4731 if (!BitTestCases[i].Emitted) {
4732 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4733 CurDAG = &HSDAG;
4734 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4735 // Set the current basic block to the mbb we wish to insert the code into
4736 BB = BitTestCases[i].Parent;
4737 HSDL.setCurrentBasicBlock(BB);
4738 // Emit the code
4739 HSDL.visitBitTestHeader(BitTestCases[i]);
4740 HSDAG.setRoot(HSDL.getRoot());
4741 CodeGenAndEmitDAG(HSDAG);
4742 }
4743
4744 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4745 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4746 CurDAG = &BSDAG;
4747 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4748 // Set the current basic block to the mbb we wish to insert the code into
4749 BB = BitTestCases[i].Cases[j].ThisBB;
4750 BSDL.setCurrentBasicBlock(BB);
4751 // Emit the code
4752 if (j+1 != ej)
4753 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4754 BitTestCases[i].Reg,
4755 BitTestCases[i].Cases[j]);
4756 else
4757 BSDL.visitBitTestCase(BitTestCases[i].Default,
4758 BitTestCases[i].Reg,
4759 BitTestCases[i].Cases[j]);
4760
4761
4762 BSDAG.setRoot(BSDL.getRoot());
4763 CodeGenAndEmitDAG(BSDAG);
4764 }
4765
4766 // Update PHI Nodes
4767 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4768 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4769 MachineBasicBlock *PHIBB = PHI->getParent();
4770 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4771 "This is not a machine PHI node that we are updating!");
4772 // This is "default" BB. We have two jumps to it. From "header" BB and
4773 // from last "case" BB.
4774 if (PHIBB == BitTestCases[i].Default) {
4775 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4776 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikov8085bcf2007-04-13 06:53:51 +00004777 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004778 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4779 }
4780 // One of "cases" BB.
4781 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4782 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4783 if (cBB->succ_end() !=
4784 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4785 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4786 PHI->addMachineBasicBlockOperand(cBB);
4787 }
4788 }
4789 }
4790 }
4791
Nate Begeman9453eea2006-04-23 06:26:20 +00004792 // If the JumpTable record is filled in, then we need to emit a jump table.
4793 // Updating the PHI nodes is tricky in this case, since we need to determine
4794 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004795 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4796 // Lower header first, if it wasn't already lowered
4797 if (!JTCases[i].first.Emitted) {
4798 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4799 CurDAG = &HSDAG;
4800 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4801 // Set the current basic block to the mbb we wish to insert the code into
4802 BB = JTCases[i].first.HeaderBB;
4803 HSDL.setCurrentBasicBlock(BB);
4804 // Emit the code
4805 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4806 HSDAG.setRoot(HSDL.getRoot());
4807 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004808 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004809
4810 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4811 CurDAG = &JSDAG;
4812 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004813 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004814 BB = JTCases[i].second.MBB;
4815 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004816 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004817 JSDL.visitJumpTable(JTCases[i].second);
4818 JSDAG.setRoot(JSDL.getRoot());
4819 CodeGenAndEmitDAG(JSDAG);
4820
Nate Begeman37efe672006-04-22 18:53:45 +00004821 // Update PHI Nodes
4822 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4823 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4824 MachineBasicBlock *PHIBB = PHI->getParent();
4825 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4826 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004827 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004828 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004829 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004830 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004831 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004832 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004833 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004834 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004835 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004836 }
4837 }
Nate Begeman37efe672006-04-22 18:53:45 +00004838 }
4839
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004840 // If the switch block involved a branch to one of the actual successors, we
4841 // need to update PHI nodes in that block.
4842 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4843 MachineInstr *PHI = PHINodesToUpdate[i].first;
4844 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4845 "This is not a machine PHI node that we are updating!");
4846 if (BB->isSuccessor(PHI->getParent())) {
4847 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4848 PHI->addMachineBasicBlockOperand(BB);
4849 }
4850 }
4851
Nate Begemanf15485a2006-03-27 01:32:24 +00004852 // If we generated any switch lowering information, build and codegen any
4853 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004854 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004855 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004856 CurDAG = &SDAG;
4857 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004858
Nate Begemanf15485a2006-03-27 01:32:24 +00004859 // Set the current basic block to the mbb we wish to insert the code into
4860 BB = SwitchCases[i].ThisBB;
4861 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004862
Nate Begemanf15485a2006-03-27 01:32:24 +00004863 // Emit the code
4864 SDL.visitSwitchCase(SwitchCases[i]);
4865 SDAG.setRoot(SDL.getRoot());
4866 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004867
4868 // Handle any PHI nodes in successors of this chunk, as if we were coming
4869 // from the original BB before switch expansion. Note that PHI nodes can
4870 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4871 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004872 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004873 for (MachineBasicBlock::iterator Phi = BB->begin();
4874 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4875 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4876 for (unsigned pn = 0; ; ++pn) {
4877 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4878 if (PHINodesToUpdate[pn].first == Phi) {
4879 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4880 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4881 break;
4882 }
4883 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004884 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004885
4886 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004887 if (BB == SwitchCases[i].FalseBB)
4888 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004889
4890 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004891 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004892 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004893 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004894 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004895 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004896}
Evan Chenga9c20912006-01-21 02:32:06 +00004897
Jim Laskey13ec7022006-08-01 14:21:23 +00004898
Evan Chenga9c20912006-01-21 02:32:06 +00004899//===----------------------------------------------------------------------===//
4900/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4901/// target node in the graph.
4902void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4903 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004904
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004905 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004906
4907 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004908 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004909 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004910 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004911
Jim Laskey9ff542f2006-08-01 18:29:48 +00004912 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004913 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004914 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004915}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004916
Chris Lattner03fc53c2006-03-06 00:22:00 +00004917
Jim Laskey9ff542f2006-08-01 18:29:48 +00004918HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4919 return new HazardRecognizer();
4920}
4921
Chris Lattner75548062006-10-11 03:58:02 +00004922//===----------------------------------------------------------------------===//
4923// Helper functions used by the generated instruction selector.
4924//===----------------------------------------------------------------------===//
4925// Calls to these methods are generated by tblgen.
4926
4927/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4928/// the dag combiner simplified the 255, we still want to match. RHS is the
4929/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4930/// specified in the .td file (e.g. 255).
4931bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4932 int64_t DesiredMaskS) {
4933 uint64_t ActualMask = RHS->getValue();
4934 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4935
4936 // If the actual mask exactly matches, success!
4937 if (ActualMask == DesiredMask)
4938 return true;
4939
4940 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4941 if (ActualMask & ~DesiredMask)
4942 return false;
4943
4944 // Otherwise, the DAG Combiner may have proven that the value coming in is
4945 // either already zero or is not demanded. Check for known zero input bits.
4946 uint64_t NeededMask = DesiredMask & ~ActualMask;
4947 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4948 return true;
4949
4950 // TODO: check to see if missing bits are just not demanded.
4951
4952 // Otherwise, this pattern doesn't match.
4953 return false;
4954}
4955
4956/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4957/// the dag combiner simplified the 255, we still want to match. RHS is the
4958/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4959/// specified in the .td file (e.g. 255).
4960bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4961 int64_t DesiredMaskS) {
4962 uint64_t ActualMask = RHS->getValue();
4963 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4964
4965 // If the actual mask exactly matches, success!
4966 if (ActualMask == DesiredMask)
4967 return true;
4968
4969 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4970 if (ActualMask & ~DesiredMask)
4971 return false;
4972
4973 // Otherwise, the DAG Combiner may have proven that the value coming in is
4974 // either already zero or is not demanded. Check for known zero input bits.
4975 uint64_t NeededMask = DesiredMask & ~ActualMask;
4976
4977 uint64_t KnownZero, KnownOne;
4978 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4979
4980 // If all the missing bits in the or are already known to be set, match!
4981 if ((NeededMask & KnownOne) == NeededMask)
4982 return true;
4983
4984 // TODO: check to see if missing bits are just not demanded.
4985
4986 // Otherwise, this pattern doesn't match.
4987 return false;
4988}
4989
Jim Laskey9ff542f2006-08-01 18:29:48 +00004990
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004991/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4992/// by tblgen. Others should not call it.
4993void SelectionDAGISel::
4994SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4995 std::vector<SDOperand> InOps;
4996 std::swap(InOps, Ops);
4997
4998 Ops.push_back(InOps[0]); // input chain.
4999 Ops.push_back(InOps[1]); // input asm string.
5000
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005001 unsigned i = 2, e = InOps.size();
5002 if (InOps[e-1].getValueType() == MVT::Flag)
5003 --e; // Don't process a flag operand if it is here.
5004
5005 while (i != e) {
5006 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5007 if ((Flags & 7) != 4 /*MEM*/) {
5008 // Just skip over this operand, copying the operands verbatim.
5009 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5010 i += (Flags >> 3) + 1;
5011 } else {
5012 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5013 // Otherwise, this is a memory operand. Ask the target to select it.
5014 std::vector<SDOperand> SelOps;
5015 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005016 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005017 exit(1);
5018 }
5019
5020 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005021 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005022 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005023 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005024 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5025 i += 2;
5026 }
5027 }
5028
5029 // Add the flag input back if present.
5030 if (e != InOps.size())
5031 Ops.push_back(InOps.back());
5032}
Devang Patel794fd752007-05-01 21:15:47 +00005033
Devang Patel19974732007-05-03 01:11:54 +00005034char SelectionDAGISel::ID = 0;