blob: f79ad0290a76f3768bb0e5d60ee681dfaa33066a [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000077static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
82 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084static RegisterScheduler
85defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087
Evan Cheng5c807602008-02-26 02:33:44 +000088namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000089
Chris Lattnerf899fce2008-04-27 23:48:12 +000090/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
91/// MVT::ValueTypes that represent all the individual underlying
92/// non-aggregate types that comprise it.
93static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
94 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
95 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 for (StructType::element_iterator EI = STy->element_begin(),
98 EB = STy->element_end();
99 EI != EB; ++EI)
100 ComputeValueVTs(TLI, *EI, ValueVTs);
101 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000102 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000103 // Given an array type, recursively traverse the elements.
104 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
105 const Type *EltTy = ATy->getElementType();
106 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
107 ComputeValueVTs(TLI, EltTy, ValueVTs);
108 return;
109 }
110 // Base case: we can get an MVT::ValueType for this LLVM IR type.
111 ValueVTs.push_back(TLI.getValueType(Ty));
112}
Dan Gohman23ce5022008-04-25 18:27:55 +0000113
Chris Lattnerf899fce2008-04-27 23:48:12 +0000114namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000115 /// RegsForValue - This struct represents the registers (physical or virtual)
116 /// that a particular set of values is assigned, and the type information about
117 /// the value. The most common situation is to represent one value at a time,
118 /// but struct or array values are handled element-wise as multiple values.
119 /// The splitting of aggregates is performed recursively, so that we never
120 /// have aggregate-typed registers. The values at this point do not necessarily
121 /// have legal types, so each value may require one or more registers of some
122 /// legal type.
123 ///
Chris Lattner95255282006-06-28 23:17:24 +0000124 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000125 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000126 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 const TargetLowering *TLI;
128
Dan Gohman0fe00902008-04-28 18:10:39 +0000129 /// ValueVTs - The value types of the values, which may not be legal, and
130 /// may need be promoted or synthesized from one or more registers.
131 ///
132 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000133
Dan Gohman0fe00902008-04-28 18:10:39 +0000134 /// RegVTs - The value types of the registers. This is the same size as
135 /// ValueVTs and it records, for each value, what the type of the assigned
136 /// register or registers are. (Individual values are never synthesized
137 /// from more than one type of register.)
138 ///
139 /// With virtual registers, the contents of RegVTs is redundant with TLI's
140 /// getRegisterType member function, however when with physical registers
141 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000142 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000143 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman0fe00902008-04-28 18:10:39 +0000145 /// Regs - This list holds the registers assigned to the values.
146 /// Each legal or promoted value requires one register, and each
147 /// expanded value requires multiple registers.
148 ///
149 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000150
Dan Gohman23ce5022008-04-25 18:27:55 +0000151 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000154 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000155 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000156 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000157 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000158 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000159 const SmallVector<MVT::ValueType, 4> &regvts,
160 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
163 unsigned Reg, const Type *Ty) : TLI(&tli) {
164 ComputeValueVTs(tli, Ty, ValueVTs);
165
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000166 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000167 MVT::ValueType ValueVT = ValueVTs[Value];
168 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
169 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
170 for (unsigned i = 0; i != NumRegs; ++i)
171 Regs.push_back(Reg + i);
172 RegVTs.push_back(RegisterVT);
173 Reg += NumRegs;
174 }
Chris Lattner864635a2006-02-22 22:37:12 +0000175 }
176
Chris Lattner41f62592008-04-29 04:29:54 +0000177 /// append - Add the specified values to this one.
178 void append(const RegsForValue &RHS) {
179 TLI = RHS.TLI;
180 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
181 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
182 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
183 }
184
185
Chris Lattner864635a2006-02-22 22:37:12 +0000186 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000187 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000189 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000190 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000192
193 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
194 /// specified value into the registers specified by this object. This uses
195 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000196 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000197 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199
200 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
201 /// operand list. This adds the code marker and includes the number of
202 /// values added into it.
203 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000204 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000205 };
206}
Evan Cheng4ef10862006-01-23 07:01:07 +0000207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208namespace llvm {
209 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000210 /// createDefaultScheduler - This creates an instruction scheduler appropriate
211 /// for the target.
212 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
213 SelectionDAG *DAG,
214 MachineBasicBlock *BB) {
215 TargetLowering &TLI = IS->getTargetLowering();
216
217 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
218 return createTDListDAGScheduler(IS, DAG, BB);
219 } else {
220 assert(TLI.getSchedulingPreference() ==
221 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
222 return createBURRListDAGScheduler(IS, DAG, BB);
223 }
224 }
225
226
227 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 /// FunctionLoweringInfo - This contains information that is global to a
229 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000230 class FunctionLoweringInfo {
231 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000232 TargetLowering &TLI;
233 Function &Fn;
234 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000235 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000236
237 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
238
239 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
240 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
241
242 /// ValueMap - Since we emit code for the function a basic block at a time,
243 /// we must remember which virtual registers hold the values for
244 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000245 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000246
247 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
248 /// the entry block. This allows the allocas to be efficiently referenced
249 /// anywhere in the function.
250 std::map<const AllocaInst*, int> StaticAllocaMap;
251
Duncan Sandsf4070822007-06-15 19:04:19 +0000252#ifndef NDEBUG
253 SmallSet<Instruction*, 8> CatchInfoLost;
254 SmallSet<Instruction*, 8> CatchInfoFound;
255#endif
256
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 }
Chris Lattner571e4342006-10-27 21:36:01 +0000260
261 /// isExportedInst - Return true if the specified value is an instruction
262 /// exported from its block.
263 bool isExportedInst(const Value *V) {
264 return ValueMap.count(V);
265 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000266
Chris Lattner3c384492006-03-16 19:51:18 +0000267 unsigned CreateRegForValue(const Value *V);
268
Chris Lattner1c08c712005-01-07 07:47:53 +0000269 unsigned InitializeRegForValue(const Value *V) {
270 unsigned &R = ValueMap[V];
271 assert(R == 0 && "Already initialized this value register!");
272 return R = CreateRegForValue(V);
273 }
274 };
275}
276
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000277/// isSelector - Return true if this instruction is a call to the
278/// eh.selector intrinsic.
279static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000281 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
282 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000283 return false;
284}
285
Chris Lattner1c08c712005-01-07 07:47:53 +0000286/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000287/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000288/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000289static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
290 if (isa<PHINode>(I)) return true;
291 BasicBlock *BB = I->getParent();
292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000293 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000294 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 return true;
297 return false;
298}
299
Chris Lattnerbf209482005-10-30 19:42:35 +0000300/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000301/// entry block, return true. This includes arguments used by switches, since
302/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000303static bool isOnlyUsedInEntryBlock(Argument *A) {
304 BasicBlock *Entry = A->getParent()->begin();
305 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000306 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000307 return false; // Use not in entry block.
308 return true;
309}
310
Chris Lattner1c08c712005-01-07 07:47:53 +0000311FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000313 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000314
Chris Lattnerbf209482005-10-30 19:42:35 +0000315 // Create a vreg for each argument register that is not dead and is used
316 // outside of the entry block for the function.
317 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
318 AI != E; ++AI)
319 if (!isOnlyUsedInEntryBlock(AI))
320 InitializeRegForValue(AI);
321
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 // Initialize the mapping of values to registers. This is only set up for
323 // instruction values that are used outside of the block that defines
324 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000325 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
327 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000329 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000330 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000331 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000332 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000333 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000334
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000336 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000337 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000338 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 }
340
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000341 for (; BB != EB; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000343 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
344 if (!isa<AllocaInst>(I) ||
345 !StaticAllocaMap.count(cast<AllocaInst>(I)))
346 InitializeRegForValue(I);
347
348 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
349 // also creates the initial PHI MachineInstrs, though none of the input
350 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000351 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000352 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
353 MBBMap[BB] = MBB;
354 MF.getBasicBlockList().push_back(MBB);
355
356 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
357 // appropriate.
358 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000359 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
360 if (PN->use_empty()) continue;
361
362 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000363 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000364 unsigned PHIReg = ValueMap[PN];
365 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000366 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000367 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000369 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 }
371}
372
Chris Lattner3c384492006-03-16 19:51:18 +0000373/// CreateRegForValue - Allocate the appropriate number of virtual registers of
374/// the correctly promoted or expanded types. Assign these registers
375/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000376///
377/// In the case that the given value has struct or array type, this function
378/// will assign registers for each member or element.
379///
Chris Lattner3c384492006-03-16 19:51:18 +0000380unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000381 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000383
Dan Gohman23ce5022008-04-25 18:27:55 +0000384 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000386 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000387 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000388
Chris Lattnerb606dba2008-04-28 06:44:42 +0000389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
393 }
394 }
395 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000396}
Chris Lattner1c08c712005-01-07 07:47:53 +0000397
398//===----------------------------------------------------------------------===//
399/// SelectionDAGLowering - This is the common target-independent lowering
400/// implementation that is parameterized by a TargetLowering object.
401/// Also, targets can overload any lowering method.
402///
403namespace llvm {
404class SelectionDAGLowering {
405 MachineBasicBlock *CurMBB;
406
Chris Lattner0da331f2007-02-04 01:31:47 +0000407 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Chris Lattnerd3948112005-01-17 22:19:26 +0000409 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
410 /// them up and then emit token factor nodes when possible. This allows us to
411 /// get simple disambiguation between loads without worrying about alias
412 /// analysis.
413 std::vector<SDOperand> PendingLoads;
414
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000415 /// PendingExports - CopyToReg nodes that copy values to virtual registers
416 /// for export to other blocks need to be emitted before any terminator
417 /// instruction, but they have no other ordering requirements. We bunch them
418 /// up and the emit a single tokenfactor for them just before terminator
419 /// instructions.
420 std::vector<SDOperand> PendingExports;
421
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000422 /// Case - A struct to record the Value for a switch case, and the
423 /// case's target basic block.
424 struct Case {
425 Constant* Low;
426 Constant* High;
427 MachineBasicBlock* BB;
428
429 Case() : Low(0), High(0), BB(0) { }
430 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
431 Low(low), High(high), BB(bb) { }
432 uint64_t size() const {
433 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
434 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
435 return (rHigh - rLow + 1ULL);
436 }
437 };
438
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000439 struct CaseBits {
440 uint64_t Mask;
441 MachineBasicBlock* BB;
442 unsigned Bits;
443
444 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
445 Mask(mask), BB(bb), Bits(bits) { }
446 };
447
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000448 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000449 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef CaseVector::iterator CaseItr;
451 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000452
453 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
454 /// of conditional branches.
455 struct CaseRec {
456 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
457 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
458
459 /// CaseBB - The MBB in which to emit the compare and branch
460 MachineBasicBlock *CaseBB;
461 /// LT, GE - If nonzero, we know the current case value must be less-than or
462 /// greater-than-or-equal-to these Constants.
463 Constant *LT;
464 Constant *GE;
465 /// Range - A pair of iterators representing the range of case values to be
466 /// processed at this point in the binary search tree.
467 CaseRange Range;
468 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000469
470 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000471
472 /// The comparison function for sorting the switch case values in the vector.
473 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000474 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000475 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000476 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
477 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
478 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
479 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000480 }
481 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000482
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000483 struct CaseBitsCmp {
484 bool operator () (const CaseBits& C1, const CaseBits& C2) {
485 return C1.Bits > C2.Bits;
486 }
487 };
488
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000489 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000490
Chris Lattner1c08c712005-01-07 07:47:53 +0000491public:
492 // TLI - This is information that describes the available target features we
493 // need for lowering. This indicates when operations are unavailable,
494 // implemented with a libcall, etc.
495 TargetLowering &TLI;
496 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000497 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000498 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000499
Nate Begemanf15485a2006-03-27 01:32:24 +0000500 /// SwitchCases - Vector of CaseBlock structures used to communicate
501 /// SwitchInst code generation information.
502 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000503 /// JTCases - Vector of JumpTable structures used to communicate
504 /// SwitchInst code generation information.
505 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000506 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000507
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 /// FuncInfo - Information about the function as a whole.
509 ///
510 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000511
512 /// GCI - Garbage collection metadata for the function.
513 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000514
515 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000516 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000517 FunctionLoweringInfo &funcinfo,
518 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000519 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000520 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000521 }
522
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000523 /// getRoot - Return the current virtual root of the Selection DAG,
524 /// flushing any PendingLoad items. This must be done before emitting
525 /// a store or any other node that may need to be ordered after any
526 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 ///
528 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000529 if (PendingLoads.empty())
530 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000531
Chris Lattnerd3948112005-01-17 22:19:26 +0000532 if (PendingLoads.size() == 1) {
533 SDOperand Root = PendingLoads[0];
534 DAG.setRoot(Root);
535 PendingLoads.clear();
536 return Root;
537 }
538
539 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000540 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
541 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000542 PendingLoads.clear();
543 DAG.setRoot(Root);
544 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000545 }
546
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000547 /// getControlRoot - Similar to getRoot, but instead of flushing all the
548 /// PendingLoad items, flush all the PendingExports items. It is necessary
549 /// to do this before emitting a terminator instruction.
550 ///
551 SDOperand getControlRoot() {
552 SDOperand Root = DAG.getRoot();
553
554 if (PendingExports.empty())
555 return Root;
556
557 // Turn all of the CopyToReg chains into one factored node.
558 if (Root.getOpcode() != ISD::EntryToken) {
559 unsigned i = 0, e = PendingExports.size();
560 for (; i != e; ++i) {
561 assert(PendingExports[i].Val->getNumOperands() > 1);
562 if (PendingExports[i].Val->getOperand(0) == Root)
563 break; // Don't add the root if we already indirectly depend on it.
564 }
565
566 if (i == e)
567 PendingExports.push_back(Root);
568 }
569
570 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
571 &PendingExports[0],
572 PendingExports.size());
573 PendingExports.clear();
574 DAG.setRoot(Root);
575 return Root;
576 }
577
578 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000579
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visit(Instruction &I) { visit(I.getOpcode(), I); }
581
582 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000583 // Note: this doesn't use InstVisitor, because it has to work with
584 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 switch (Opcode) {
586 default: assert(0 && "Unknown instruction type encountered!");
587 abort();
588 // Build the switch statement using the Instruction.def file.
589#define HANDLE_INST(NUM, OPCODE, CLASS) \
590 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
591#include "llvm/Instruction.def"
592 }
593 }
594
595 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
596
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000597 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000598 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000599 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
Chris Lattner199862b2006-03-16 19:57:50 +0000601 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner0da331f2007-02-04 01:31:47 +0000603 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000604 SDOperand &N = NodeMap[V];
605 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000606 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000608
Evan Cheng5c807602008-02-26 02:33:44 +0000609 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000610 std::set<unsigned> &OutputRegs,
611 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000612
Chris Lattner571e4342006-10-27 21:36:01 +0000613 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
614 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
615 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000616 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000617 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000618 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000619 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000620
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 // Terminator instructions.
622 void visitRet(ReturnInst &I);
623 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000624 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitUnreachable(UnreachableInst &I) { /* noop */ }
626
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000627 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000632 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000636 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000637 CaseRecVector& WorkList,
638 Value* SV,
639 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000640 bool handleBitTestsSwitchCase(CaseRec& CR,
641 CaseRecVector& WorkList,
642 Value* SV,
643 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000644 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000645 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
646 void visitBitTestCase(MachineBasicBlock* NextMBB,
647 unsigned Reg,
648 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000649 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000650 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
651 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000652
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000654 void visitInvoke(InvokeInst &I);
655 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000656
Dan Gohman7f321562007-06-25 16:23:39 +0000657 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000658 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000659 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000660 if (I.getType()->isFPOrFPVector())
661 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000662 else
Dan Gohman7f321562007-06-25 16:23:39 +0000663 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000664 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000665 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000666 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000667 if (I.getType()->isFPOrFPVector())
668 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000669 else
Dan Gohman7f321562007-06-25 16:23:39 +0000670 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000671 }
Dan Gohman7f321562007-06-25 16:23:39 +0000672 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
673 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
674 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
675 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
676 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
677 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
678 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
679 void visitOr (User &I) { visitBinary(I, ISD::OR); }
680 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000681 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000682 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
683 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000684 void visitICmp(User &I);
685 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000686 void visitVICmp(User &I);
687 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Chris Lattner2bbd8102006-03-29 00:11:43 +0000702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000704 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000705
Chris Lattner1c08c712005-01-07 07:47:53 +0000706 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000708
709 void visitMalloc(MallocInst &I);
710 void visitFree(FreeInst &I);
711 void visitAlloca(AllocaInst &I);
712 void visitLoad(LoadInst &I);
713 void visitStore(StoreInst &I);
714 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
715 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000716 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000717 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000718 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000719
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 void visitVAArg(VAArgInst &I);
722 void visitVAEnd(CallInst &I);
723 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724
Dan Gohmanef5d1942008-03-11 21:11:25 +0000725 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000726
Chris Lattner1c08c712005-01-07 07:47:53 +0000727 void visitUserOp1(Instruction &I) {
728 assert(0 && "UserOp1 should not exist at instruction selection time!");
729 abort();
730 }
731 void visitUserOp2(Instruction &I) {
732 assert(0 && "UserOp2 should not exist at instruction selection time!");
733 abort();
734 }
Mon P Wang63307c32008-05-05 19:05:59 +0000735
736private:
737 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
738
Chris Lattner1c08c712005-01-07 07:47:53 +0000739};
740} // end namespace llvm
741
Dan Gohman6183f782007-07-05 20:12:34 +0000742
Duncan Sandsb988bac2008-02-11 20:58:28 +0000743/// getCopyFromParts - Create a value that contains the specified legal parts
744/// combined into the value they represent. If the parts combine to a type
745/// larger then ValueVT then AssertOp can be used to specify whether the extra
746/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000747/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000748static SDOperand getCopyFromParts(SelectionDAG &DAG,
749 const SDOperand *Parts,
750 unsigned NumParts,
751 MVT::ValueType PartVT,
752 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000753 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000754 assert(NumParts > 0 && "No parts to assemble!");
755 TargetLowering &TLI = DAG.getTargetLoweringInfo();
756 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000757
Duncan Sands014e04a2008-02-12 20:46:31 +0000758 if (NumParts > 1) {
759 // Assemble the value from multiple parts.
760 if (!MVT::isVector(ValueVT)) {
761 unsigned PartBits = MVT::getSizeInBits(PartVT);
762 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000763
Duncan Sands014e04a2008-02-12 20:46:31 +0000764 // Assemble the power of 2 part.
765 unsigned RoundParts = NumParts & (NumParts - 1) ?
766 1 << Log2_32(NumParts) : NumParts;
767 unsigned RoundBits = PartBits * RoundParts;
768 MVT::ValueType RoundVT = RoundBits == ValueBits ?
769 ValueVT : MVT::getIntegerType(RoundBits);
770 SDOperand Lo, Hi;
771
772 if (RoundParts > 2) {
773 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
774 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
776 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000777 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000778 Lo = Parts[0];
779 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000780 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000781 if (TLI.isBigEndian())
782 std::swap(Lo, Hi);
783 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
784
785 if (RoundParts < NumParts) {
786 // Assemble the trailing non-power-of-2 part.
787 unsigned OddParts = NumParts - RoundParts;
788 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
789 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
790
791 // Combine the round and odd parts.
792 Lo = Val;
793 if (TLI.isBigEndian())
794 std::swap(Lo, Hi);
795 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
796 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
797 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
798 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
799 TLI.getShiftAmountTy()));
800 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
801 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
802 }
803 } else {
804 // Handle a multi-element vector.
805 MVT::ValueType IntermediateVT, RegisterVT;
806 unsigned NumIntermediates;
807 unsigned NumRegs =
808 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
809 RegisterVT);
810
811 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
812 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
813 assert(RegisterVT == Parts[0].getValueType() &&
814 "Part type doesn't match part!");
815
816 // Assemble the parts into intermediate operands.
817 SmallVector<SDOperand, 8> Ops(NumIntermediates);
818 if (NumIntermediates == NumParts) {
819 // If the register was not expanded, truncate or copy the value,
820 // as appropriate.
821 for (unsigned i = 0; i != NumParts; ++i)
822 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
823 PartVT, IntermediateVT);
824 } else if (NumParts > 0) {
825 // If the intermediate type was expanded, build the intermediate operands
826 // from the parts.
827 assert(NumParts % NumIntermediates == 0 &&
828 "Must expand into a divisible number of parts!");
829 unsigned Factor = NumParts / NumIntermediates;
830 for (unsigned i = 0; i != NumIntermediates; ++i)
831 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
832 PartVT, IntermediateVT);
833 }
834
835 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
836 // operands.
837 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
838 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
839 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000840 }
Dan Gohman6183f782007-07-05 20:12:34 +0000841 }
842
Duncan Sands014e04a2008-02-12 20:46:31 +0000843 // There is now one part, held in Val. Correct it to match ValueVT.
844 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000845
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 if (PartVT == ValueVT)
847 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000848
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 if (MVT::isVector(PartVT)) {
850 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
851 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000852 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000853
854 if (MVT::isVector(ValueVT)) {
855 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
856 MVT::getVectorNumElements(ValueVT) == 1 &&
857 "Only trivial scalar-to-vector conversions should get here!");
858 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
859 }
860
861 if (MVT::isInteger(PartVT) &&
862 MVT::isInteger(ValueVT)) {
863 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
864 // For a truncate, see if we have any information to
865 // indicate whether the truncated bits will always be
866 // zero or sign-extension.
867 if (AssertOp != ISD::DELETED_NODE)
868 Val = DAG.getNode(AssertOp, PartVT, Val,
869 DAG.getValueType(ValueVT));
870 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
871 } else {
872 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
873 }
874 }
875
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000876 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
877 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000878 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000879 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000880 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000881 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
882 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000883
884 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
885 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
886
887 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000888 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000889}
890
Duncan Sandsb988bac2008-02-11 20:58:28 +0000891/// getCopyToParts - Create a series of nodes that contain the specified value
892/// split into legal parts. If the parts contain more bits than Val, then, for
893/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000894static void getCopyToParts(SelectionDAG &DAG,
895 SDOperand Val,
896 SDOperand *Parts,
897 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000898 MVT::ValueType PartVT,
899 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000900 TargetLowering &TLI = DAG.getTargetLoweringInfo();
901 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000902 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000903 unsigned PartBits = MVT::getSizeInBits(PartVT);
904 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000905
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 if (!NumParts)
907 return;
908
909 if (!MVT::isVector(ValueVT)) {
910 if (PartVT == ValueVT) {
911 assert(NumParts == 1 && "No-op copy with multiple parts!");
912 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000913 return;
914 }
915
Duncan Sands014e04a2008-02-12 20:46:31 +0000916 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
917 // If the parts cover more bits than the value has, promote the value.
918 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
919 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000920 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000921 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
922 ValueVT = MVT::getIntegerType(NumParts * PartBits);
923 Val = DAG.getNode(ExtendKind, ValueVT, Val);
924 } else {
925 assert(0 && "Unknown mismatch!");
926 }
927 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
928 // Different types of the same size.
929 assert(NumParts == 1 && PartVT != ValueVT);
930 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
931 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
932 // If the parts cover less bits than value has, truncate the value.
933 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
934 ValueVT = MVT::getIntegerType(NumParts * PartBits);
935 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000936 } else {
937 assert(0 && "Unknown mismatch!");
938 }
939 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000940
941 // The value may have changed - recompute ValueVT.
942 ValueVT = Val.getValueType();
943 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
944 "Failed to tile the value with PartVT!");
945
946 if (NumParts == 1) {
947 assert(PartVT == ValueVT && "Type conversion failed!");
948 Parts[0] = Val;
949 return;
950 }
951
952 // Expand the value into multiple parts.
953 if (NumParts & (NumParts - 1)) {
954 // The number of parts is not a power of 2. Split off and copy the tail.
955 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
956 "Do not know what to expand to!");
957 unsigned RoundParts = 1 << Log2_32(NumParts);
958 unsigned RoundBits = RoundParts * PartBits;
959 unsigned OddParts = NumParts - RoundParts;
960 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
961 DAG.getConstant(RoundBits,
962 TLI.getShiftAmountTy()));
963 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
964 if (TLI.isBigEndian())
965 // The odd parts were reversed by getCopyToParts - unreverse them.
966 std::reverse(Parts + RoundParts, Parts + NumParts);
967 NumParts = RoundParts;
968 ValueVT = MVT::getIntegerType(NumParts * PartBits);
969 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
970 }
971
972 // The number of parts is a power of 2. Repeatedly bisect the value using
973 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000974 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
975 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
976 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000977 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
978 for (unsigned i = 0; i < NumParts; i += StepSize) {
979 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000980 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
981 SDOperand &Part0 = Parts[i];
982 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000983
Duncan Sands25eb0432008-03-12 20:30:08 +0000984 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
985 DAG.getConstant(1, PtrVT));
986 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
987 DAG.getConstant(0, PtrVT));
988
989 if (ThisBits == PartBits && ThisVT != PartVT) {
990 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
991 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
992 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000993 }
994 }
995
996 if (TLI.isBigEndian())
997 std::reverse(Parts, Parts + NumParts);
998
999 return;
1000 }
1001
1002 // Vector ValueVT.
1003 if (NumParts == 1) {
1004 if (PartVT != ValueVT) {
1005 if (MVT::isVector(PartVT)) {
1006 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1007 } else {
1008 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1009 MVT::getVectorNumElements(ValueVT) == 1 &&
1010 "Only trivial vector-to-scalar conversions should get here!");
1011 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1012 DAG.getConstant(0, PtrVT));
1013 }
1014 }
1015
Dan Gohman6183f782007-07-05 20:12:34 +00001016 Parts[0] = Val;
1017 return;
1018 }
1019
1020 // Handle a multi-element vector.
1021 MVT::ValueType IntermediateVT, RegisterVT;
1022 unsigned NumIntermediates;
1023 unsigned NumRegs =
1024 DAG.getTargetLoweringInfo()
1025 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1026 RegisterVT);
1027 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1028
1029 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1030 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1031
1032 // Split the vector into intermediate operands.
1033 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1034 for (unsigned i = 0; i != NumIntermediates; ++i)
1035 if (MVT::isVector(IntermediateVT))
1036 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1037 IntermediateVT, Val,
1038 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001039 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001040 else
1041 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1042 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001043 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001044
1045 // Split the intermediate operands into legal parts.
1046 if (NumParts == NumIntermediates) {
1047 // If the register was not expanded, promote or copy the value,
1048 // as appropriate.
1049 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001050 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001051 } else if (NumParts > 0) {
1052 // If the intermediate type was expanded, split each the value into
1053 // legal parts.
1054 assert(NumParts % NumIntermediates == 0 &&
1055 "Must expand into a divisible number of parts!");
1056 unsigned Factor = NumParts / NumIntermediates;
1057 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001058 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001059 }
1060}
1061
1062
Chris Lattner199862b2006-03-16 19:57:50 +00001063SDOperand SelectionDAGLowering::getValue(const Value *V) {
1064 SDOperand &N = NodeMap[V];
1065 if (N.Val) return N;
1066
Chris Lattner199862b2006-03-16 19:57:50 +00001067 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001068 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001069
1070 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1071 return N = DAG.getConstant(CI->getValue(), VT);
1072
1073 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001074 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001075
1076 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001077 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001078
1079 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1080 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1081
Chris Lattner6833b062008-04-28 07:16:35 +00001082 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1083 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001084
1085 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1086 visit(CE->getOpcode(), *CE);
1087 SDOperand N1 = NodeMap[V];
1088 assert(N1.Val && "visit didn't populate the ValueMap!");
1089 return N1;
1090 }
1091
Chris Lattner6833b062008-04-28 07:16:35 +00001092 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001093 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001094
Chris Lattner6833b062008-04-28 07:16:35 +00001095 // Now that we know the number and type of the elements, get that number of
1096 // elements into the Ops array based on what kind of constant it is.
1097 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001098 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1099 for (unsigned i = 0; i != NumElements; ++i)
1100 Ops.push_back(getValue(CP->getOperand(i)));
1101 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001102 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1103 "Unknown vector constant!");
1104 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1105
Chris Lattnerb606dba2008-04-28 06:44:42 +00001106 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001107 if (isa<UndefValue>(C))
1108 Op = DAG.getNode(ISD::UNDEF, EltVT);
1109 else if (MVT::isFloatingPoint(EltVT))
1110 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001111 else
Chris Lattner6833b062008-04-28 07:16:35 +00001112 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001113 Ops.assign(NumElements, Op);
1114 }
1115
1116 // Create a BUILD_VECTOR node.
1117 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001118 }
1119
Chris Lattnerb606dba2008-04-28 06:44:42 +00001120 // If this is a static alloca, generate it as the frameindex instead of
1121 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001122 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1123 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001124 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001125 if (SI != FuncInfo.StaticAllocaMap.end())
1126 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1127 }
1128
Chris Lattner251db182007-02-25 18:40:32 +00001129 unsigned InReg = FuncInfo.ValueMap[V];
1130 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001131
Chris Lattner6833b062008-04-28 07:16:35 +00001132 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001133 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001134 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001135}
1136
1137
Chris Lattner1c08c712005-01-07 07:47:53 +00001138void SelectionDAGLowering::visitRet(ReturnInst &I) {
1139 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001140 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001141 return;
1142 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001143
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001144 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001145 NewValues.push_back(getControlRoot());
1146 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001147 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001148 MVT::ValueType VT = RetOp.getValueType();
1149
Evan Cheng8e7d0562006-05-26 23:09:09 +00001150 // FIXME: C calling convention requires the return type to be promoted to
1151 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001152 if (MVT::isInteger(VT)) {
1153 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1154 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1155 VT = MinVT;
1156 }
1157
1158 unsigned NumParts = TLI.getNumRegisters(VT);
1159 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1160 SmallVector<SDOperand, 4> Parts(NumParts);
1161 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1162
1163 const Function *F = I.getParent()->getParent();
1164 if (F->paramHasAttr(0, ParamAttr::SExt))
1165 ExtendKind = ISD::SIGN_EXTEND;
1166 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1167 ExtendKind = ISD::ZERO_EXTEND;
1168
1169 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1170
1171 for (unsigned i = 0; i < NumParts; ++i) {
1172 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001173 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001174 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001175 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001176 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1177 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001178}
1179
Chris Lattner571e4342006-10-27 21:36:01 +00001180/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1181/// the current basic block, add it to ValueMap now so that we'll get a
1182/// CopyTo/FromReg.
1183void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1184 // No need to export constants.
1185 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1186
1187 // Already exported?
1188 if (FuncInfo.isExportedInst(V)) return;
1189
1190 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001191 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001192}
1193
Chris Lattner8c494ab2006-10-27 23:50:33 +00001194bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1195 const BasicBlock *FromBB) {
1196 // The operands of the setcc have to be in this block. We don't know
1197 // how to export them from some other block.
1198 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1199 // Can export from current BB.
1200 if (VI->getParent() == FromBB)
1201 return true;
1202
1203 // Is already exported, noop.
1204 return FuncInfo.isExportedInst(V);
1205 }
1206
1207 // If this is an argument, we can export it if the BB is the entry block or
1208 // if it is already exported.
1209 if (isa<Argument>(V)) {
1210 if (FromBB == &FromBB->getParent()->getEntryBlock())
1211 return true;
1212
1213 // Otherwise, can only export this if it is already exported.
1214 return FuncInfo.isExportedInst(V);
1215 }
1216
1217 // Otherwise, constants can always be exported.
1218 return true;
1219}
1220
Chris Lattner6a586c82006-10-29 21:01:20 +00001221static bool InBlock(const Value *V, const BasicBlock *BB) {
1222 if (const Instruction *I = dyn_cast<Instruction>(V))
1223 return I->getParent() == BB;
1224 return true;
1225}
1226
Chris Lattner571e4342006-10-27 21:36:01 +00001227/// FindMergedConditions - If Cond is an expression like
1228void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1229 MachineBasicBlock *TBB,
1230 MachineBasicBlock *FBB,
1231 MachineBasicBlock *CurBB,
1232 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001233 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001234 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001235
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1237 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001238 BOp->getParent() != CurBB->getBasicBlock() ||
1239 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1240 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001241 const BasicBlock *BB = CurBB->getBasicBlock();
1242
Reid Spencere4d87aa2006-12-23 06:05:41 +00001243 // If the leaf of the tree is a comparison, merge the condition into
1244 // the caseblock.
1245 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1246 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001247 // how to export them from some other block. If this is the first block
1248 // of the sequence, no exporting is needed.
1249 (CurBB == CurMBB ||
1250 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1251 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001252 BOp = cast<Instruction>(Cond);
1253 ISD::CondCode Condition;
1254 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1255 switch (IC->getPredicate()) {
1256 default: assert(0 && "Unknown icmp predicate opcode!");
1257 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1258 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1259 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1260 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1261 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1262 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1263 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1264 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1265 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1266 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1267 }
1268 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1269 ISD::CondCode FPC, FOC;
1270 switch (FC->getPredicate()) {
1271 default: assert(0 && "Unknown fcmp predicate opcode!");
1272 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1273 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1274 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1275 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1276 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1277 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1278 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001279 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1280 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001281 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1282 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1283 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1284 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1285 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1286 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1287 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1288 }
1289 if (FiniteOnlyFPMath())
1290 Condition = FOC;
1291 else
1292 Condition = FPC;
1293 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001294 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001295 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001296 }
1297
Chris Lattner571e4342006-10-27 21:36:01 +00001298 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001299 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001300 SwitchCases.push_back(CB);
1301 return;
1302 }
1303
1304 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001305 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001306 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001307 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001308 return;
1309 }
1310
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001311
1312 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001313 MachineFunction::iterator BBI = CurBB;
1314 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1315 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1316
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001317 if (Opc == Instruction::Or) {
1318 // Codegen X | Y as:
1319 // jmp_if_X TBB
1320 // jmp TmpBB
1321 // TmpBB:
1322 // jmp_if_Y TBB
1323 // jmp FBB
1324 //
Chris Lattner571e4342006-10-27 21:36:01 +00001325
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001326 // Emit the LHS condition.
1327 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1328
1329 // Emit the RHS condition into TmpBB.
1330 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1331 } else {
1332 assert(Opc == Instruction::And && "Unknown merge op!");
1333 // Codegen X & Y as:
1334 // jmp_if_X TmpBB
1335 // jmp FBB
1336 // TmpBB:
1337 // jmp_if_Y TBB
1338 // jmp FBB
1339 //
1340 // This requires creation of TmpBB after CurBB.
1341
1342 // Emit the LHS condition.
1343 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1344
1345 // Emit the RHS condition into TmpBB.
1346 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1347 }
Chris Lattner571e4342006-10-27 21:36:01 +00001348}
1349
Chris Lattnerdf19f272006-10-31 22:37:42 +00001350/// If the set of cases should be emitted as a series of branches, return true.
1351/// If we should emit this as a bunch of and/or'd together conditions, return
1352/// false.
1353static bool
1354ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1355 if (Cases.size() != 2) return true;
1356
Chris Lattner0ccb5002006-10-31 23:06:00 +00001357 // If this is two comparisons of the same values or'd or and'd together, they
1358 // will get folded into a single comparison, so don't emit two blocks.
1359 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1360 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1361 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1362 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1363 return false;
1364 }
1365
Chris Lattnerdf19f272006-10-31 22:37:42 +00001366 return true;
1367}
1368
Chris Lattner1c08c712005-01-07 07:47:53 +00001369void SelectionDAGLowering::visitBr(BranchInst &I) {
1370 // Update machine-CFG edges.
1371 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001372
1373 // Figure out which block is immediately after the current one.
1374 MachineBasicBlock *NextBlock = 0;
1375 MachineFunction::iterator BBI = CurMBB;
1376 if (++BBI != CurMBB->getParent()->end())
1377 NextBlock = BBI;
1378
1379 if (I.isUnconditional()) {
1380 // If this is not a fall-through branch, emit the branch.
1381 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001382 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001383 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001384
Chris Lattner57ab6592006-10-24 17:57:59 +00001385 // Update machine-CFG edges.
1386 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 return;
1388 }
1389
1390 // If this condition is one of the special cases we handle, do special stuff
1391 // now.
1392 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001393 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001394
1395 // If this is a series of conditions that are or'd or and'd together, emit
1396 // this as a sequence of branches instead of setcc's with and/or operations.
1397 // For example, instead of something like:
1398 // cmp A, B
1399 // C = seteq
1400 // cmp D, E
1401 // F = setle
1402 // or C, F
1403 // jnz foo
1404 // Emit:
1405 // cmp A, B
1406 // je foo
1407 // cmp D, E
1408 // jle foo
1409 //
1410 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1411 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001412 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001413 BOp->getOpcode() == Instruction::Or)) {
1414 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001415 // If the compares in later blocks need to use values not currently
1416 // exported from this block, export them now. This block should always
1417 // be the first entry.
1418 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1419
Chris Lattnerdf19f272006-10-31 22:37:42 +00001420 // Allow some cases to be rejected.
1421 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001422 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1423 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1424 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1425 }
1426
1427 // Emit the branch for this block.
1428 visitSwitchCase(SwitchCases[0]);
1429 SwitchCases.erase(SwitchCases.begin());
1430 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001431 }
1432
Chris Lattner0ccb5002006-10-31 23:06:00 +00001433 // Okay, we decided not to do this, remove any inserted MBB's and clear
1434 // SwitchCases.
1435 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1436 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1437
Chris Lattnerdf19f272006-10-31 22:37:42 +00001438 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001439 }
1440 }
Chris Lattner24525952006-10-24 18:07:37 +00001441
1442 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001443 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001444 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001445 // Use visitSwitchCase to actually insert the fast branch sequence for this
1446 // cond branch.
1447 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001448}
1449
Nate Begemanf15485a2006-03-27 01:32:24 +00001450/// visitSwitchCase - Emits the necessary code to represent a single node in
1451/// the binary search tree resulting from lowering a switch instruction.
1452void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001453 SDOperand Cond;
1454 SDOperand CondLHS = getValue(CB.CmpLHS);
1455
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001456 // Build the setcc now.
1457 if (CB.CmpMHS == NULL) {
1458 // Fold "(X == true)" to X and "(X == false)" to !X to
1459 // handle common cases produced by branch lowering.
1460 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1461 Cond = CondLHS;
1462 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1463 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1464 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1465 } else
1466 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1467 } else {
1468 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001469
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001470 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1471 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1472
1473 SDOperand CmpOp = getValue(CB.CmpMHS);
1474 MVT::ValueType VT = CmpOp.getValueType();
1475
1476 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1477 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1478 } else {
1479 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1480 Cond = DAG.getSetCC(MVT::i1, SUB,
1481 DAG.getConstant(High-Low, VT), ISD::SETULE);
1482 }
1483
1484 }
1485
Nate Begemanf15485a2006-03-27 01:32:24 +00001486 // Set NextBlock to be the MBB immediately after the current one, if any.
1487 // This is used to avoid emitting unnecessary branches to the next block.
1488 MachineBasicBlock *NextBlock = 0;
1489 MachineFunction::iterator BBI = CurMBB;
1490 if (++BBI != CurMBB->getParent()->end())
1491 NextBlock = BBI;
1492
1493 // If the lhs block is the next block, invert the condition so that we can
1494 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001495 if (CB.TrueBB == NextBlock) {
1496 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001497 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1498 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1499 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001500 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001501 DAG.getBasicBlock(CB.TrueBB));
1502 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001503 DAG.setRoot(BrCond);
1504 else
1505 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001506 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001507 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001508 CurMBB->addSuccessor(CB.TrueBB);
1509 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001510}
1511
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001512/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001513void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001514 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001515 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001516 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001517 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001518 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1519 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1520 Table, Index));
1521 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001522}
1523
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001524/// visitJumpTableHeader - This function emits necessary code to produce index
1525/// in the JumpTable from switch case.
1526void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1527 SelectionDAGISel::JumpTableHeader &JTH) {
1528 // Subtract the lowest switch case value from the value being switched on
1529 // and conditional branch to default mbb if the result is greater than the
1530 // difference between smallest and largest cases.
1531 SDOperand SwitchOp = getValue(JTH.SValue);
1532 MVT::ValueType VT = SwitchOp.getValueType();
1533 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1534 DAG.getConstant(JTH.First, VT));
1535
1536 // The SDNode we just created, which holds the value being switched on
1537 // minus the the smallest case value, needs to be copied to a virtual
1538 // register so it can be used as an index into the jump table in a
1539 // subsequent basic block. This value may be smaller or larger than the
1540 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001541 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001542 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1543 else
1544 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1545
1546 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001547 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001548 JT.Reg = JumpTableReg;
1549
1550 // Emit the range check for the jump table, and branch to the default
1551 // block for the switch statement if the value being switched on exceeds
1552 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001553 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001554 DAG.getConstant(JTH.Last-JTH.First,VT),
1555 ISD::SETUGT);
1556
1557 // Set NextBlock to be the MBB immediately after the current one, if any.
1558 // This is used to avoid emitting unnecessary branches to the next block.
1559 MachineBasicBlock *NextBlock = 0;
1560 MachineFunction::iterator BBI = CurMBB;
1561 if (++BBI != CurMBB->getParent()->end())
1562 NextBlock = BBI;
1563
1564 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1565 DAG.getBasicBlock(JT.Default));
1566
1567 if (JT.MBB == NextBlock)
1568 DAG.setRoot(BrCond);
1569 else
1570 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001571 DAG.getBasicBlock(JT.MBB)));
1572
1573 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001574}
1575
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001576/// visitBitTestHeader - This function emits necessary code to produce value
1577/// suitable for "bit tests"
1578void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1579 // Subtract the minimum value
1580 SDOperand SwitchOp = getValue(B.SValue);
1581 MVT::ValueType VT = SwitchOp.getValueType();
1582 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1583 DAG.getConstant(B.First, VT));
1584
1585 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001586 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001587 DAG.getConstant(B.Range, VT),
1588 ISD::SETUGT);
1589
1590 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001591 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001592 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1593 else
1594 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1595
1596 // Make desired shift
1597 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1598 DAG.getConstant(1, TLI.getPointerTy()),
1599 ShiftOp);
1600
1601 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001602 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001603 B.Reg = SwitchReg;
1604
1605 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1606 DAG.getBasicBlock(B.Default));
1607
1608 // Set NextBlock to be the MBB immediately after the current one, if any.
1609 // This is used to avoid emitting unnecessary branches to the next block.
1610 MachineBasicBlock *NextBlock = 0;
1611 MachineFunction::iterator BBI = CurMBB;
1612 if (++BBI != CurMBB->getParent()->end())
1613 NextBlock = BBI;
1614
1615 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1616 if (MBB == NextBlock)
1617 DAG.setRoot(BrRange);
1618 else
1619 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1620 DAG.getBasicBlock(MBB)));
1621
1622 CurMBB->addSuccessor(B.Default);
1623 CurMBB->addSuccessor(MBB);
1624
1625 return;
1626}
1627
1628/// visitBitTestCase - this function produces one "bit test"
1629void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1630 unsigned Reg,
1631 SelectionDAGISel::BitTestCase &B) {
1632 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001633 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001634
1635 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1636 SwitchVal,
1637 DAG.getConstant(B.Mask,
1638 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001639 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001640 DAG.getConstant(0, TLI.getPointerTy()),
1641 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001642 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001643 AndCmp, DAG.getBasicBlock(B.TargetBB));
1644
1645 // Set NextBlock to be the MBB immediately after the current one, if any.
1646 // This is used to avoid emitting unnecessary branches to the next block.
1647 MachineBasicBlock *NextBlock = 0;
1648 MachineFunction::iterator BBI = CurMBB;
1649 if (++BBI != CurMBB->getParent()->end())
1650 NextBlock = BBI;
1651
1652 if (NextMBB == NextBlock)
1653 DAG.setRoot(BrAnd);
1654 else
1655 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1656 DAG.getBasicBlock(NextMBB)));
1657
1658 CurMBB->addSuccessor(B.TargetBB);
1659 CurMBB->addSuccessor(NextMBB);
1660
1661 return;
1662}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001663
Jim Laskeyb180aa12007-02-21 22:53:45 +00001664void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1665 // Retrieve successors.
1666 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001667 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001668
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001669 if (isa<InlineAsm>(I.getCalledValue()))
1670 visitInlineAsm(&I);
1671 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001672 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001673
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001674 // If the value of the invoke is used outside of its defining block, make it
1675 // available as a virtual register.
1676 if (!I.use_empty()) {
1677 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1678 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001679 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001680 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001681
1682 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001683 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001684 DAG.getBasicBlock(Return)));
1685
1686 // Update successor info
1687 CurMBB->addSuccessor(Return);
1688 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001689}
1690
1691void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1692}
1693
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001694/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001695/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001696bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001697 CaseRecVector& WorkList,
1698 Value* SV,
1699 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001700 Case& BackCase = *(CR.Range.second-1);
1701
1702 // Size is the number of Cases represented by this range.
1703 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001704 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001705 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001706
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001707 // Get the MachineFunction which holds the current MBB. This is used when
1708 // inserting any additional MBBs necessary to represent the switch.
1709 MachineFunction *CurMF = CurMBB->getParent();
1710
1711 // Figure out which block is immediately after the current one.
1712 MachineBasicBlock *NextBlock = 0;
1713 MachineFunction::iterator BBI = CR.CaseBB;
1714
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001715 if (++BBI != CurMBB->getParent()->end())
1716 NextBlock = BBI;
1717
1718 // TODO: If any two of the cases has the same destination, and if one value
1719 // is the same as the other, but has one bit unset that the other has set,
1720 // use bit manipulation to do two compares at once. For example:
1721 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1722
1723 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001724 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001725 // The last case block won't fall through into 'NextBlock' if we emit the
1726 // branches in this order. See if rearranging a case value would help.
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001728 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001729 std::swap(*I, BackCase);
1730 break;
1731 }
1732 }
1733 }
1734
1735 // Create a CaseBlock record representing a conditional branch to
1736 // the Case's target mbb if the value being switched on SV is equal
1737 // to C.
1738 MachineBasicBlock *CurBlock = CR.CaseBB;
1739 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1740 MachineBasicBlock *FallThrough;
1741 if (I != E-1) {
1742 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1743 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1744 } else {
1745 // If the last case doesn't match, go to the default block.
1746 FallThrough = Default;
1747 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001748
1749 Value *RHS, *LHS, *MHS;
1750 ISD::CondCode CC;
1751 if (I->High == I->Low) {
1752 // This is just small small case range :) containing exactly 1 case
1753 CC = ISD::SETEQ;
1754 LHS = SV; RHS = I->High; MHS = NULL;
1755 } else {
1756 CC = ISD::SETLE;
1757 LHS = I->Low; MHS = SV; RHS = I->High;
1758 }
1759 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1760 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001761
1762 // If emitting the first comparison, just call visitSwitchCase to emit the
1763 // code into the current block. Otherwise, push the CaseBlock onto the
1764 // vector to be later processed by SDISel, and insert the node's MBB
1765 // before the next MBB.
1766 if (CurBlock == CurMBB)
1767 visitSwitchCase(CB);
1768 else
1769 SwitchCases.push_back(CB);
1770
1771 CurBlock = FallThrough;
1772 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001773
1774 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001775}
1776
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001777static inline bool areJTsAllowed(const TargetLowering &TLI) {
1778 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1779 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1780}
1781
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001782/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001783bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001784 CaseRecVector& WorkList,
1785 Value* SV,
1786 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001787 Case& FrontCase = *CR.Range.first;
1788 Case& BackCase = *(CR.Range.second-1);
1789
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001790 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1791 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1792
1793 uint64_t TSize = 0;
1794 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1795 I!=E; ++I)
1796 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001797
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001798 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001799 return false;
1800
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001801 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1802 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001803 return false;
1804
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001805 DOUT << "Lowering jump table\n"
1806 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001807 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001808
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001809 // Get the MachineFunction which holds the current MBB. This is used when
1810 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001811 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001812
1813 // Figure out which block is immediately after the current one.
1814 MachineBasicBlock *NextBlock = 0;
1815 MachineFunction::iterator BBI = CR.CaseBB;
1816
1817 if (++BBI != CurMBB->getParent()->end())
1818 NextBlock = BBI;
1819
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001820 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1821
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001822 // Create a new basic block to hold the code for loading the address
1823 // of the jump table, and jumping to it. Update successor information;
1824 // we will either branch to the default case for the switch, or the jump
1825 // table.
1826 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1827 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1828 CR.CaseBB->addSuccessor(Default);
1829 CR.CaseBB->addSuccessor(JumpTableBB);
1830
1831 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001832 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001833 // a case statement, push the case's BB onto the vector, otherwise, push
1834 // the default BB.
1835 std::vector<MachineBasicBlock*> DestBBs;
1836 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1838 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1839 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1840
1841 if ((Low <= TEI) && (TEI <= High)) {
1842 DestBBs.push_back(I->BB);
1843 if (TEI==High)
1844 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001845 } else {
1846 DestBBs.push_back(Default);
1847 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001848 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001849
1850 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001851 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001852 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1853 E = DestBBs.end(); I != E; ++I) {
1854 if (!SuccsHandled[(*I)->getNumber()]) {
1855 SuccsHandled[(*I)->getNumber()] = true;
1856 JumpTableBB->addSuccessor(*I);
1857 }
1858 }
1859
1860 // Create a jump table index for this jump table, or return an existing
1861 // one.
1862 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1863
1864 // Set the jump table information so that we can codegen it as a second
1865 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001866 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001867 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1868 (CR.CaseBB == CurMBB));
1869 if (CR.CaseBB == CurMBB)
1870 visitJumpTableHeader(JT, JTH);
1871
1872 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001873
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001874 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001875}
1876
1877/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1878/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001879bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880 CaseRecVector& WorkList,
1881 Value* SV,
1882 MachineBasicBlock* Default) {
1883 // Get the MachineFunction which holds the current MBB. This is used when
1884 // inserting any additional MBBs necessary to represent the switch.
1885 MachineFunction *CurMF = CurMBB->getParent();
1886
1887 // Figure out which block is immediately after the current one.
1888 MachineBasicBlock *NextBlock = 0;
1889 MachineFunction::iterator BBI = CR.CaseBB;
1890
1891 if (++BBI != CurMBB->getParent()->end())
1892 NextBlock = BBI;
1893
1894 Case& FrontCase = *CR.Range.first;
1895 Case& BackCase = *(CR.Range.second-1);
1896 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1897
1898 // Size is the number of Cases represented by this range.
1899 unsigned Size = CR.Range.second - CR.Range.first;
1900
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001901 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1902 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001903 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001904 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001905
1906 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1907 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001908 uint64_t TSize = 0;
1909 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1910 I!=E; ++I)
1911 TSize += I->size();
1912
1913 uint64_t LSize = FrontCase.size();
1914 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001915 DOUT << "Selecting best pivot: \n"
1916 << "First: " << First << ", Last: " << Last <<"\n"
1917 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001918 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001919 J!=E; ++I, ++J) {
1920 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1921 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001922 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001923 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1924 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001925 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001926 // Should always split in some non-trivial place
1927 DOUT <<"=>Step\n"
1928 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1929 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1930 << "Metric: " << Metric << "\n";
1931 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001932 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001933 FMetric = Metric;
1934 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001935 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001936
1937 LSize += J->size();
1938 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001939 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001940 if (areJTsAllowed(TLI)) {
1941 // If our case is dense we *really* should handle it earlier!
1942 assert((FMetric > 0) && "Should handle dense range earlier!");
1943 } else {
1944 Pivot = CR.Range.first + Size/2;
1945 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001946
1947 CaseRange LHSR(CR.Range.first, Pivot);
1948 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001949 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001950 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1951
1952 // We know that we branch to the LHS if the Value being switched on is
1953 // less than the Pivot value, C. We use this to optimize our binary
1954 // tree a bit, by recognizing that if SV is greater than or equal to the
1955 // LHS's Case Value, and that Case Value is exactly one less than the
1956 // Pivot's Value, then we can branch directly to the LHS's Target,
1957 // rather than creating a leaf node for it.
1958 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001959 LHSR.first->High == CR.GE &&
1960 cast<ConstantInt>(C)->getSExtValue() ==
1961 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1962 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001963 } else {
1964 TrueBB = new MachineBasicBlock(LLVMBB);
1965 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1966 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1967 }
1968
1969 // Similar to the optimization above, if the Value being switched on is
1970 // known to be less than the Constant CR.LT, and the current Case Value
1971 // is CR.LT - 1, then we can branch directly to the target block for
1972 // the current Case Value, rather than emitting a RHS leaf node for it.
1973 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001974 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1975 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1976 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001977 } else {
1978 FalseBB = new MachineBasicBlock(LLVMBB);
1979 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1980 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1981 }
1982
1983 // Create a CaseBlock record representing a conditional branch to
1984 // the LHS node if the value being switched on SV is less than C.
1985 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001986 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1987 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001988
1989 if (CR.CaseBB == CurMBB)
1990 visitSwitchCase(CB);
1991 else
1992 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001993
1994 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001995}
1996
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001997/// handleBitTestsSwitchCase - if current case range has few destination and
1998/// range span less, than machine word bitwidth, encode case range into series
1999/// of masks and emit bit tests with these masks.
2000bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2001 CaseRecVector& WorkList,
2002 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002003 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00002004 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002005
2006 Case& FrontCase = *CR.Range.first;
2007 Case& BackCase = *(CR.Range.second-1);
2008
2009 // Get the MachineFunction which holds the current MBB. This is used when
2010 // inserting any additional MBBs necessary to represent the switch.
2011 MachineFunction *CurMF = CurMBB->getParent();
2012
2013 unsigned numCmps = 0;
2014 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2015 I!=E; ++I) {
2016 // Single case counts one, case range - two.
2017 if (I->Low == I->High)
2018 numCmps +=1;
2019 else
2020 numCmps +=2;
2021 }
2022
2023 // Count unique destinations
2024 SmallSet<MachineBasicBlock*, 4> Dests;
2025 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2026 Dests.insert(I->BB);
2027 if (Dests.size() > 3)
2028 // Don't bother the code below, if there are too much unique destinations
2029 return false;
2030 }
2031 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2032 << "Total number of comparisons: " << numCmps << "\n";
2033
2034 // Compute span of values.
2035 Constant* minValue = FrontCase.Low;
2036 Constant* maxValue = BackCase.High;
2037 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2038 cast<ConstantInt>(minValue)->getSExtValue();
2039 DOUT << "Compare range: " << range << "\n"
2040 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2041 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2042
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002043 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002044 (!(Dests.size() == 1 && numCmps >= 3) &&
2045 !(Dests.size() == 2 && numCmps >= 5) &&
2046 !(Dests.size() >= 3 && numCmps >= 6)))
2047 return false;
2048
2049 DOUT << "Emitting bit tests\n";
2050 int64_t lowBound = 0;
2051
2052 // Optimize the case where all the case values fit in a
2053 // word without having to subtract minValue. In this case,
2054 // we can optimize away the subtraction.
2055 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002056 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002057 range = cast<ConstantInt>(maxValue)->getSExtValue();
2058 } else {
2059 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2060 }
2061
2062 CaseBitsVector CasesBits;
2063 unsigned i, count = 0;
2064
2065 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2066 MachineBasicBlock* Dest = I->BB;
2067 for (i = 0; i < count; ++i)
2068 if (Dest == CasesBits[i].BB)
2069 break;
2070
2071 if (i == count) {
2072 assert((count < 3) && "Too much destinations to test!");
2073 CasesBits.push_back(CaseBits(0, Dest, 0));
2074 count++;
2075 }
2076
2077 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2078 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2079
2080 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002081 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002082 CasesBits[i].Bits++;
2083 }
2084
2085 }
2086 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2087
2088 SelectionDAGISel::BitTestInfo BTC;
2089
2090 // Figure out which block is immediately after the current one.
2091 MachineFunction::iterator BBI = CR.CaseBB;
2092 ++BBI;
2093
2094 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2095
2096 DOUT << "Cases:\n";
2097 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2098 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2099 << ", BB: " << CasesBits[i].BB << "\n";
2100
2101 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2102 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2103 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2104 CaseBB,
2105 CasesBits[i].BB));
2106 }
2107
2108 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002109 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002110 CR.CaseBB, Default, BTC);
2111
2112 if (CR.CaseBB == CurMBB)
2113 visitBitTestHeader(BTB);
2114
2115 BitTestCases.push_back(BTB);
2116
2117 return true;
2118}
2119
2120
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002121/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002122unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2123 const SwitchInst& SI) {
2124 unsigned numCmps = 0;
2125
2126 // Start with "simple" cases
2127 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2128 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2129 Cases.push_back(Case(SI.getSuccessorValue(i),
2130 SI.getSuccessorValue(i),
2131 SMBB));
2132 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002133 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002134
2135 // Merge case into clusters
2136 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002137 // Must recompute end() each iteration because it may be
2138 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002139 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002140 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2141 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2142 MachineBasicBlock* nextBB = J->BB;
2143 MachineBasicBlock* currentBB = I->BB;
2144
2145 // If the two neighboring cases go to the same destination, merge them
2146 // into a single case.
2147 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2148 I->High = J->High;
2149 J = Cases.erase(J);
2150 } else {
2151 I = J++;
2152 }
2153 }
2154
2155 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2156 if (I->Low != I->High)
2157 // A range counts double, since it requires two compares.
2158 ++numCmps;
2159 }
2160
2161 return numCmps;
2162}
2163
2164void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002165 // Figure out which block is immediately after the current one.
2166 MachineBasicBlock *NextBlock = 0;
2167 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002168
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002169 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002170
Nate Begemanf15485a2006-03-27 01:32:24 +00002171 // If there is only the default destination, branch to it if it is not the
2172 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002173 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002174 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002175
Nate Begemanf15485a2006-03-27 01:32:24 +00002176 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002177 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002178 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002179 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002180
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002181 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002182 return;
2183 }
2184
2185 // If there are any non-default case statements, create a vector of Cases
2186 // representing each one, and sort the vector so that we can efficiently
2187 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002188 CaseVector Cases;
2189 unsigned numCmps = Clusterify(Cases, SI);
2190 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2191 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002192
Nate Begemanf15485a2006-03-27 01:32:24 +00002193 // Get the Value to be switched on and default basic blocks, which will be
2194 // inserted into CaseBlock records, representing basic blocks in the binary
2195 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002196 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002197
Nate Begemanf15485a2006-03-27 01:32:24 +00002198 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002199 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002200 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2201
2202 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002203 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002204 CaseRec CR = WorkList.back();
2205 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002206
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002207 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2208 continue;
2209
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002210 // If the range has few cases (two or less) emit a series of specific
2211 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002212 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2213 continue;
2214
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002215 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002216 // target supports indirect branches, then emit a jump table rather than
2217 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002218 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2219 continue;
2220
2221 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2222 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2223 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002224 }
2225}
2226
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002227
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002228void SelectionDAGLowering::visitSub(User &I) {
2229 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002230 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002231 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002232 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2233 const VectorType *DestTy = cast<VectorType>(I.getType());
2234 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002235 if (ElTy->isFloatingPoint()) {
2236 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002237 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002238 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2239 if (CV == CNZ) {
2240 SDOperand Op2 = getValue(I.getOperand(1));
2241 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2242 return;
2243 }
Dan Gohman7f321562007-06-25 16:23:39 +00002244 }
2245 }
2246 }
2247 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002248 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002249 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002250 SDOperand Op2 = getValue(I.getOperand(1));
2251 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2252 return;
2253 }
Dan Gohman7f321562007-06-25 16:23:39 +00002254 }
2255
2256 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002257}
2258
Dan Gohman7f321562007-06-25 16:23:39 +00002259void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002260 SDOperand Op1 = getValue(I.getOperand(0));
2261 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002262
2263 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002264}
2265
Nate Begemane21ea612005-11-18 07:42:56 +00002266void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2267 SDOperand Op1 = getValue(I.getOperand(0));
2268 SDOperand Op2 = getValue(I.getOperand(1));
2269
Dan Gohman7f321562007-06-25 16:23:39 +00002270 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2271 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002272 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2273 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2274 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002275
Chris Lattner1c08c712005-01-07 07:47:53 +00002276 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2277}
2278
Reid Spencer45fb3f32006-11-20 01:22:35 +00002279void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002280 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2281 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2282 predicate = IC->getPredicate();
2283 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2284 predicate = ICmpInst::Predicate(IC->getPredicate());
2285 SDOperand Op1 = getValue(I.getOperand(0));
2286 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002287 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002288 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002289 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2290 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2291 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2292 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2293 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2294 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2295 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2296 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2297 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2298 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2299 default:
2300 assert(!"Invalid ICmp predicate value");
2301 Opcode = ISD::SETEQ;
2302 break;
2303 }
2304 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2305}
2306
2307void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002308 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2309 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2310 predicate = FC->getPredicate();
2311 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2312 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002313 SDOperand Op1 = getValue(I.getOperand(0));
2314 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002315 ISD::CondCode Condition, FOC, FPC;
2316 switch (predicate) {
2317 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2318 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2319 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2320 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2321 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2322 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2323 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002324 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2325 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002326 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2327 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2328 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2329 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2330 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2331 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2332 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2333 default:
2334 assert(!"Invalid FCmp predicate value");
2335 FOC = FPC = ISD::SETFALSE;
2336 break;
2337 }
2338 if (FiniteOnlyFPMath())
2339 Condition = FOC;
2340 else
2341 Condition = FPC;
2342 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002343}
2344
Nate Begemanb43e9c12008-05-12 19:40:03 +00002345void SelectionDAGLowering::visitVICmp(User &I) {
2346 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2347 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2348 predicate = IC->getPredicate();
2349 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2350 predicate = ICmpInst::Predicate(IC->getPredicate());
2351 SDOperand Op1 = getValue(I.getOperand(0));
2352 SDOperand Op2 = getValue(I.getOperand(1));
2353 ISD::CondCode Opcode;
2354 switch (predicate) {
2355 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2356 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2357 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2358 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2359 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2360 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2361 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2362 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2363 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2364 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2365 default:
2366 assert(!"Invalid ICmp predicate value");
2367 Opcode = ISD::SETEQ;
2368 break;
2369 }
2370 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2371}
2372
2373void SelectionDAGLowering::visitVFCmp(User &I) {
2374 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2375 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2376 predicate = FC->getPredicate();
2377 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2378 predicate = FCmpInst::Predicate(FC->getPredicate());
2379 SDOperand Op1 = getValue(I.getOperand(0));
2380 SDOperand Op2 = getValue(I.getOperand(1));
2381 ISD::CondCode Condition, FOC, FPC;
2382 switch (predicate) {
2383 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2384 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2385 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2386 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2387 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2388 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2389 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2390 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2391 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2392 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2393 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2394 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2395 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2396 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2397 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2398 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2399 default:
2400 assert(!"Invalid VFCmp predicate value");
2401 FOC = FPC = ISD::SETFALSE;
2402 break;
2403 }
2404 if (FiniteOnlyFPMath())
2405 Condition = FOC;
2406 else
2407 Condition = FPC;
2408
2409 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2410
2411 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2412}
2413
Chris Lattner1c08c712005-01-07 07:47:53 +00002414void SelectionDAGLowering::visitSelect(User &I) {
2415 SDOperand Cond = getValue(I.getOperand(0));
2416 SDOperand TrueVal = getValue(I.getOperand(1));
2417 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002418 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2419 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002420}
2421
Reid Spencer3da59db2006-11-27 01:05:10 +00002422
2423void SelectionDAGLowering::visitTrunc(User &I) {
2424 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2425 SDOperand N = getValue(I.getOperand(0));
2426 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2427 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2428}
2429
2430void SelectionDAGLowering::visitZExt(User &I) {
2431 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2432 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2433 SDOperand N = getValue(I.getOperand(0));
2434 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2435 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2436}
2437
2438void SelectionDAGLowering::visitSExt(User &I) {
2439 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2440 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2441 SDOperand N = getValue(I.getOperand(0));
2442 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2443 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2444}
2445
2446void SelectionDAGLowering::visitFPTrunc(User &I) {
2447 // FPTrunc is never a no-op cast, no need to check
2448 SDOperand N = getValue(I.getOperand(0));
2449 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002450 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002451}
2452
2453void SelectionDAGLowering::visitFPExt(User &I){
2454 // FPTrunc is never a no-op cast, no need to check
2455 SDOperand N = getValue(I.getOperand(0));
2456 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2457 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2458}
2459
2460void SelectionDAGLowering::visitFPToUI(User &I) {
2461 // FPToUI is never a no-op cast, no need to check
2462 SDOperand N = getValue(I.getOperand(0));
2463 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2464 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2465}
2466
2467void SelectionDAGLowering::visitFPToSI(User &I) {
2468 // FPToSI is never a no-op cast, no need to check
2469 SDOperand N = getValue(I.getOperand(0));
2470 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2471 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2472}
2473
2474void SelectionDAGLowering::visitUIToFP(User &I) {
2475 // UIToFP is never a no-op cast, no need to check
2476 SDOperand N = getValue(I.getOperand(0));
2477 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2478 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2479}
2480
2481void SelectionDAGLowering::visitSIToFP(User &I){
2482 // UIToFP is never a no-op cast, no need to check
2483 SDOperand N = getValue(I.getOperand(0));
2484 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2485 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2486}
2487
2488void SelectionDAGLowering::visitPtrToInt(User &I) {
2489 // What to do depends on the size of the integer and the size of the pointer.
2490 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002491 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002492 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002493 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002494 SDOperand Result;
2495 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2496 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2497 else
2498 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2499 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2500 setValue(&I, Result);
2501}
Chris Lattner1c08c712005-01-07 07:47:53 +00002502
Reid Spencer3da59db2006-11-27 01:05:10 +00002503void SelectionDAGLowering::visitIntToPtr(User &I) {
2504 // What to do depends on the size of the integer and the size of the pointer.
2505 // We can either truncate, zero extend, or no-op, accordingly.
2506 SDOperand N = getValue(I.getOperand(0));
2507 MVT::ValueType SrcVT = N.getValueType();
2508 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2509 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2510 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2511 else
2512 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2513 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2514}
2515
2516void SelectionDAGLowering::visitBitCast(User &I) {
2517 SDOperand N = getValue(I.getOperand(0));
2518 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002519
2520 // BitCast assures us that source and destination are the same size so this
2521 // is either a BIT_CONVERT or a no-op.
2522 if (DestVT != N.getValueType())
2523 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2524 else
2525 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002526}
2527
Chris Lattner2bbd8102006-03-29 00:11:43 +00002528void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002529 SDOperand InVec = getValue(I.getOperand(0));
2530 SDOperand InVal = getValue(I.getOperand(1));
2531 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2532 getValue(I.getOperand(2)));
2533
Dan Gohman7f321562007-06-25 16:23:39 +00002534 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2535 TLI.getValueType(I.getType()),
2536 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002537}
2538
Chris Lattner2bbd8102006-03-29 00:11:43 +00002539void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002540 SDOperand InVec = getValue(I.getOperand(0));
2541 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2542 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002543 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002544 TLI.getValueType(I.getType()), InVec, InIdx));
2545}
Chris Lattnerc7029802006-03-18 01:44:44 +00002546
Chris Lattner3e104b12006-04-08 04:15:24 +00002547void SelectionDAGLowering::visitShuffleVector(User &I) {
2548 SDOperand V1 = getValue(I.getOperand(0));
2549 SDOperand V2 = getValue(I.getOperand(1));
2550 SDOperand Mask = getValue(I.getOperand(2));
2551
Dan Gohman7f321562007-06-25 16:23:39 +00002552 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2553 TLI.getValueType(I.getType()),
2554 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002555}
2556
2557
Chris Lattner1c08c712005-01-07 07:47:53 +00002558void SelectionDAGLowering::visitGetElementPtr(User &I) {
2559 SDOperand N = getValue(I.getOperand(0));
2560 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002561
2562 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2563 OI != E; ++OI) {
2564 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002565 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002566 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002567 if (Field) {
2568 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002569 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002570 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002571 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002572 }
2573 Ty = StTy->getElementType(Field);
2574 } else {
2575 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002576
Chris Lattner7c0104b2005-11-09 04:45:33 +00002577 // If this is a constant subscript, handle it quickly.
2578 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002579 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002580 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002581 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002582 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2583 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002584 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002585 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002586
2587 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002588 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002589 SDOperand IdxN = getValue(Idx);
2590
2591 // If the index is smaller or larger than intptr_t, truncate or extend
2592 // it.
2593 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002594 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002595 } else if (IdxN.getValueType() > N.getValueType())
2596 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2597
2598 // If this is a multiply by a power of two, turn it into a shl
2599 // immediately. This is a very common case.
2600 if (isPowerOf2_64(ElementSize)) {
2601 unsigned Amt = Log2_64(ElementSize);
2602 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002603 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002604 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2605 continue;
2606 }
2607
Chris Lattner0bd48932008-01-17 07:00:52 +00002608 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002609 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2610 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002611 }
2612 }
2613 setValue(&I, N);
2614}
2615
2616void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2617 // If this is a fixed sized alloca in the entry block of the function,
2618 // allocate it statically on the stack.
2619 if (FuncInfo.StaticAllocaMap.count(&I))
2620 return; // getValue will auto-populate this.
2621
2622 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002623 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002624 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002625 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002626 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002627
2628 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002629 MVT::ValueType IntPtr = TLI.getPointerTy();
2630 if (IntPtr < AllocSize.getValueType())
2631 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2632 else if (IntPtr > AllocSize.getValueType())
2633 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002634
Chris Lattner68cd65e2005-01-22 23:04:37 +00002635 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002636 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002637
Evan Cheng45157792007-08-16 23:46:29 +00002638 // Handle alignment. If the requested alignment is less than or equal to
2639 // the stack alignment, ignore it. If the size is greater than or equal to
2640 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002641 unsigned StackAlign =
2642 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002643 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002644 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002645
2646 // Round the size of the allocation up to the stack alignment size
2647 // by add SA-1 to the size.
2648 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002649 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002650 // Mask out the low bits for alignment purposes.
2651 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002652 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002653
Chris Lattner0bd48932008-01-17 07:00:52 +00002654 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002655 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2656 MVT::Other);
2657 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002658 setValue(&I, DSA);
2659 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002660
2661 // Inform the Frame Information that we have just allocated a variable-sized
2662 // object.
2663 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2664}
2665
Chris Lattner1c08c712005-01-07 07:47:53 +00002666void SelectionDAGLowering::visitLoad(LoadInst &I) {
2667 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002668
Chris Lattnerd3948112005-01-17 22:19:26 +00002669 SDOperand Root;
2670 if (I.isVolatile())
2671 Root = getRoot();
2672 else {
2673 // Do not serialize non-volatile loads against each other.
2674 Root = DAG.getRoot();
2675 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002676
Evan Cheng466685d2006-10-09 20:57:25 +00002677 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002678 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002679}
2680
2681SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002682 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002683 bool isVolatile,
2684 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002685 SDOperand L =
2686 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2687 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002688
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002689 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002690 DAG.setRoot(L.getValue(1));
2691 else
2692 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002693
2694 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002695}
2696
2697
2698void SelectionDAGLowering::visitStore(StoreInst &I) {
2699 Value *SrcV = I.getOperand(0);
2700 SDOperand Src = getValue(SrcV);
2701 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002702 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002703 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002704}
2705
Chris Lattner0eade312006-03-24 02:22:33 +00002706/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2707/// node.
2708void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2709 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002710 bool HasChain = !I.doesNotAccessMemory();
2711 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2712
Chris Lattner0eade312006-03-24 02:22:33 +00002713 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002714 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002715 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2716 if (OnlyLoad) {
2717 // We don't need to serialize loads against other loads.
2718 Ops.push_back(DAG.getRoot());
2719 } else {
2720 Ops.push_back(getRoot());
2721 }
2722 }
Chris Lattner0eade312006-03-24 02:22:33 +00002723
2724 // Add the intrinsic ID as an integer operand.
2725 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2726
2727 // Add all operands of the call to the operand list.
2728 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2729 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002730 assert(TLI.isTypeLegal(Op.getValueType()) &&
2731 "Intrinsic uses a non-legal type?");
2732 Ops.push_back(Op);
2733 }
2734
2735 std::vector<MVT::ValueType> VTs;
2736 if (I.getType() != Type::VoidTy) {
2737 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002738 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002739 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002740 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2741
2742 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2743 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2744 }
2745
2746 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2747 VTs.push_back(VT);
2748 }
2749 if (HasChain)
2750 VTs.push_back(MVT::Other);
2751
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002752 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2753
Chris Lattner0eade312006-03-24 02:22:33 +00002754 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002755 SDOperand Result;
2756 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002757 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2758 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002759 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002760 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2761 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002762 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002763 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2764 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002765
Chris Lattnere58a7802006-04-02 03:41:14 +00002766 if (HasChain) {
2767 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2768 if (OnlyLoad)
2769 PendingLoads.push_back(Chain);
2770 else
2771 DAG.setRoot(Chain);
2772 }
Chris Lattner0eade312006-03-24 02:22:33 +00002773 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002774 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002775 MVT::ValueType VT = TLI.getValueType(PTy);
2776 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002777 }
2778 setValue(&I, Result);
2779 }
2780}
2781
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002782/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002783static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00002784 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002785 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002786 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002787 "TypeInfo must be a global variable or NULL");
2788 return GV;
2789}
2790
Duncan Sandsf4070822007-06-15 19:04:19 +00002791/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002792/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002793static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2794 MachineBasicBlock *MBB) {
2795 // Inform the MachineModuleInfo of the personality for this landing pad.
2796 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2797 assert(CE->getOpcode() == Instruction::BitCast &&
2798 isa<Function>(CE->getOperand(0)) &&
2799 "Personality should be a function");
2800 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2801
2802 // Gather all the type infos for this landing pad and pass them along to
2803 // MachineModuleInfo.
2804 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002805 unsigned N = I.getNumOperands();
2806
2807 for (unsigned i = N - 1; i > 2; --i) {
2808 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2809 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002810 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002811 assert (FirstCatch <= N && "Invalid filter length");
2812
2813 if (FirstCatch < N) {
2814 TyInfo.reserve(N - FirstCatch);
2815 for (unsigned j = FirstCatch; j < N; ++j)
2816 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2817 MMI->addCatchTypeInfo(MBB, TyInfo);
2818 TyInfo.clear();
2819 }
2820
Duncan Sands6590b042007-08-27 15:47:50 +00002821 if (!FilterLength) {
2822 // Cleanup.
2823 MMI->addCleanup(MBB);
2824 } else {
2825 // Filter.
2826 TyInfo.reserve(FilterLength - 1);
2827 for (unsigned j = i + 1; j < FirstCatch; ++j)
2828 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2829 MMI->addFilterTypeInfo(MBB, TyInfo);
2830 TyInfo.clear();
2831 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002832
2833 N = i;
2834 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002835 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002836
2837 if (N > 3) {
2838 TyInfo.reserve(N - 3);
2839 for (unsigned j = 3; j < N; ++j)
2840 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002841 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002842 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002843}
2844
Mon P Wang63307c32008-05-05 19:05:59 +00002845
2846/// Inlined utility function to implement binary input atomic intrinsics for
2847// visitIntrinsicCall: I is a call instruction
2848// Op is the associated NodeType for I
2849const char *
2850SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2851 SDOperand Root = getRoot();
2852 SDOperand O2 = getValue(I.getOperand(2));
2853 SDOperand L = DAG.getAtomic(Op, Root,
2854 getValue(I.getOperand(1)),
2855 O2, O2.getValueType());
2856 setValue(&I, L);
2857 DAG.setRoot(L.getValue(1));
2858 return 0;
2859}
2860
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002861/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2862/// we want to emit this as a call to a named external function, return the name
2863/// otherwise lower it and return null.
2864const char *
2865SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2866 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002867 default:
2868 // By default, turn this into a target intrinsic node.
2869 visitTargetIntrinsic(I, Intrinsic);
2870 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002871 case Intrinsic::vastart: visitVAStart(I); return 0;
2872 case Intrinsic::vaend: visitVAEnd(I); return 0;
2873 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002874 case Intrinsic::returnaddress:
2875 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2876 getValue(I.getOperand(1))));
2877 return 0;
2878 case Intrinsic::frameaddress:
2879 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2880 getValue(I.getOperand(1))));
2881 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002882 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002883 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002884 break;
2885 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002886 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002887 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002888 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002889 case Intrinsic::memcpy_i64: {
2890 SDOperand Op1 = getValue(I.getOperand(1));
2891 SDOperand Op2 = getValue(I.getOperand(2));
2892 SDOperand Op3 = getValue(I.getOperand(3));
2893 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2894 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2895 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002896 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002897 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002898 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002899 case Intrinsic::memset_i64: {
2900 SDOperand Op1 = getValue(I.getOperand(1));
2901 SDOperand Op2 = getValue(I.getOperand(2));
2902 SDOperand Op3 = getValue(I.getOperand(3));
2903 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2904 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2905 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002906 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002907 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002908 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002909 case Intrinsic::memmove_i64: {
2910 SDOperand Op1 = getValue(I.getOperand(1));
2911 SDOperand Op2 = getValue(I.getOperand(2));
2912 SDOperand Op3 = getValue(I.getOperand(3));
2913 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2914
2915 // If the source and destination are known to not be aliases, we can
2916 // lower memmove as memcpy.
2917 uint64_t Size = -1ULL;
2918 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2919 Size = C->getValue();
2920 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2921 AliasAnalysis::NoAlias) {
2922 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2923 I.getOperand(1), 0, I.getOperand(2), 0));
2924 return 0;
2925 }
2926
2927 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2928 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002929 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002930 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002931 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002932 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002933 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002934 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002935 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002936
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002937 Ops[0] = getRoot();
2938 Ops[1] = getValue(SPI.getLineValue());
2939 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002940
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002941 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002942 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002943 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2944
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002945 Ops[3] = DAG.getString(CompileUnit->getFileName());
2946 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002947
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002948 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002949 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002950
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002951 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002952 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002953 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002954 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002955 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002956 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2957 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002958 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002959 DAG.getConstant(LabelID, MVT::i32),
2960 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002961 }
2962
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002963 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002964 }
2965 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002966 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002967 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002968 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2969 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002970 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2971 DAG.getConstant(LabelID, MVT::i32),
2972 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002973 }
2974
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002975 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002976 }
2977 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002978 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002979 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002980 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002981 Value *SP = FSI.getSubprogram();
2982 if (SP && MMI->Verify(SP)) {
2983 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2984 // what (most?) gdb expects.
2985 DebugInfoDesc *DD = MMI->getDescFor(SP);
2986 assert(DD && "Not a debug information descriptor");
2987 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2988 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2989 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2990 CompileUnit->getFileName());
2991 // Record the source line but does create a label. It will be emitted
2992 // at asm emission time.
2993 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002994 }
2995
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002996 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002997 }
2998 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002999 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003000 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003001 Value *Variable = DI.getVariable();
3002 if (MMI && Variable && MMI->Verify(Variable))
3003 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3004 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003005 return 0;
3006 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003007
Jim Laskeyb180aa12007-02-21 22:53:45 +00003008 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003009 if (!CurMBB->isLandingPad()) {
3010 // FIXME: Mark exception register as live in. Hack for PR1508.
3011 unsigned Reg = TLI.getExceptionAddressRegister();
3012 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003013 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003014 // Insert the EXCEPTIONADDR instruction.
3015 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3016 SDOperand Ops[1];
3017 Ops[0] = DAG.getRoot();
3018 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3019 setValue(&I, Op);
3020 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003021 return 0;
3022 }
3023
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003024 case Intrinsic::eh_selector_i32:
3025 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003026 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003027 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3028 MVT::i32 : MVT::i64);
3029
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003030 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003031 if (CurMBB->isLandingPad())
3032 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003033 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003034#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003035 FuncInfo.CatchInfoLost.insert(&I);
3036#endif
Duncan Sands90291952007-07-06 09:18:59 +00003037 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3038 unsigned Reg = TLI.getExceptionSelectorRegister();
3039 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003040 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003041
3042 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003043 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003044 SDOperand Ops[2];
3045 Ops[0] = getValue(I.getOperand(1));
3046 Ops[1] = getRoot();
3047 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3048 setValue(&I, Op);
3049 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003050 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003051 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003052 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003053
3054 return 0;
3055 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003056
3057 case Intrinsic::eh_typeid_for_i32:
3058 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003059 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003060 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3061 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003062
Jim Laskey735b6f82007-02-22 15:38:06 +00003063 if (MMI) {
3064 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003065 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003066
Jim Laskey735b6f82007-02-22 15:38:06 +00003067 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003068 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003069 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003070 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003071 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003072 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003073
3074 return 0;
3075 }
3076
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003077 case Intrinsic::eh_return: {
3078 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3079
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003080 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003081 MMI->setCallsEHReturn(true);
3082 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3083 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003084 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003085 getValue(I.getOperand(1)),
3086 getValue(I.getOperand(2))));
3087 } else {
3088 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3089 }
3090
3091 return 0;
3092 }
3093
3094 case Intrinsic::eh_unwind_init: {
3095 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3096 MMI->setCallsUnwindInit(true);
3097 }
3098
3099 return 0;
3100 }
3101
3102 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003103 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3104 SDOperand CfaArg;
3105 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3106 CfaArg = DAG.getNode(ISD::TRUNCATE,
3107 TLI.getPointerTy(), getValue(I.getOperand(1)));
3108 else
3109 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3110 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003111
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003112 SDOperand Offset = DAG.getNode(ISD::ADD,
3113 TLI.getPointerTy(),
3114 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3115 TLI.getPointerTy()),
3116 CfaArg);
3117 setValue(&I, DAG.getNode(ISD::ADD,
3118 TLI.getPointerTy(),
3119 DAG.getNode(ISD::FRAMEADDR,
3120 TLI.getPointerTy(),
3121 DAG.getConstant(0,
3122 TLI.getPointerTy())),
3123 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003124 return 0;
3125 }
3126
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003127 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003128 setValue(&I, DAG.getNode(ISD::FSQRT,
3129 getValue(I.getOperand(1)).getValueType(),
3130 getValue(I.getOperand(1))));
3131 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003132 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003133 setValue(&I, DAG.getNode(ISD::FPOWI,
3134 getValue(I.getOperand(1)).getValueType(),
3135 getValue(I.getOperand(1)),
3136 getValue(I.getOperand(2))));
3137 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003138 case Intrinsic::sin:
3139 setValue(&I, DAG.getNode(ISD::FSIN,
3140 getValue(I.getOperand(1)).getValueType(),
3141 getValue(I.getOperand(1))));
3142 return 0;
3143 case Intrinsic::cos:
3144 setValue(&I, DAG.getNode(ISD::FCOS,
3145 getValue(I.getOperand(1)).getValueType(),
3146 getValue(I.getOperand(1))));
3147 return 0;
3148 case Intrinsic::pow:
3149 setValue(&I, DAG.getNode(ISD::FPOW,
3150 getValue(I.getOperand(1)).getValueType(),
3151 getValue(I.getOperand(1)),
3152 getValue(I.getOperand(2))));
3153 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003154 case Intrinsic::pcmarker: {
3155 SDOperand Tmp = getValue(I.getOperand(1));
3156 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3157 return 0;
3158 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003159 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003160 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003161 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3162 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3163 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003164 setValue(&I, Tmp);
3165 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003166 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003167 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003168 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003169 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003170 assert(0 && "part_select intrinsic not implemented");
3171 abort();
3172 }
3173 case Intrinsic::part_set: {
3174 // Currently not implemented: just abort
3175 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003176 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003177 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003178 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003179 setValue(&I, DAG.getNode(ISD::BSWAP,
3180 getValue(I.getOperand(1)).getValueType(),
3181 getValue(I.getOperand(1))));
3182 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003183 case Intrinsic::cttz: {
3184 SDOperand Arg = getValue(I.getOperand(1));
3185 MVT::ValueType Ty = Arg.getValueType();
3186 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003187 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003188 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003189 }
3190 case Intrinsic::ctlz: {
3191 SDOperand Arg = getValue(I.getOperand(1));
3192 MVT::ValueType Ty = Arg.getValueType();
3193 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003194 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003195 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003196 }
3197 case Intrinsic::ctpop: {
3198 SDOperand Arg = getValue(I.getOperand(1));
3199 MVT::ValueType Ty = Arg.getValueType();
3200 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003201 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003202 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003203 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003204 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003205 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003206 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3207 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003208 setValue(&I, Tmp);
3209 DAG.setRoot(Tmp.getValue(1));
3210 return 0;
3211 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003212 case Intrinsic::stackrestore: {
3213 SDOperand Tmp = getValue(I.getOperand(1));
3214 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003215 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003216 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003217 case Intrinsic::var_annotation:
3218 // Discard annotate attributes
3219 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003220
Duncan Sands36397f52007-07-27 12:58:54 +00003221 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003222 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003223
3224 SDOperand Ops[6];
3225 Ops[0] = getRoot();
3226 Ops[1] = getValue(I.getOperand(1));
3227 Ops[2] = getValue(I.getOperand(2));
3228 Ops[3] = getValue(I.getOperand(3));
3229 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3230 Ops[5] = DAG.getSrcValue(F);
3231
Duncan Sandsf7331b32007-09-11 14:10:23 +00003232 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3233 DAG.getNodeValueTypes(TLI.getPointerTy(),
3234 MVT::Other), 2,
3235 Ops, 6);
3236
3237 setValue(&I, Tmp);
3238 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003239 return 0;
3240 }
Gordon Henriksence224772008-01-07 01:30:38 +00003241
3242 case Intrinsic::gcroot:
3243 if (GCI) {
3244 Value *Alloca = I.getOperand(1);
3245 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3246
3247 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3248 GCI->addStackRoot(FI->getIndex(), TypeMap);
3249 }
3250 return 0;
3251
3252 case Intrinsic::gcread:
3253 case Intrinsic::gcwrite:
3254 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3255 return 0;
3256
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003257 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003258 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003259 return 0;
3260 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003261
3262 case Intrinsic::trap: {
3263 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3264 return 0;
3265 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003266 case Intrinsic::prefetch: {
3267 SDOperand Ops[4];
3268 Ops[0] = getRoot();
3269 Ops[1] = getValue(I.getOperand(1));
3270 Ops[2] = getValue(I.getOperand(2));
3271 Ops[3] = getValue(I.getOperand(3));
3272 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3273 return 0;
3274 }
3275
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003276 case Intrinsic::memory_barrier: {
3277 SDOperand Ops[6];
3278 Ops[0] = getRoot();
3279 for (int x = 1; x < 6; ++x)
3280 Ops[x] = getValue(I.getOperand(x));
3281
3282 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3283 return 0;
3284 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003285 case Intrinsic::atomic_lcs: {
3286 SDOperand Root = getRoot();
3287 SDOperand O3 = getValue(I.getOperand(3));
3288 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3289 getValue(I.getOperand(1)),
3290 getValue(I.getOperand(2)),
3291 O3, O3.getValueType());
3292 setValue(&I, L);
3293 DAG.setRoot(L.getValue(1));
3294 return 0;
3295 }
Mon P Wang63307c32008-05-05 19:05:59 +00003296 case Intrinsic::atomic_las:
3297 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3298 case Intrinsic::atomic_lss:
3299 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3300 case Intrinsic::atomic_load_and:
3301 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3302 case Intrinsic::atomic_load_or:
3303 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3304 case Intrinsic::atomic_load_xor:
3305 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3306 case Intrinsic::atomic_load_min:
3307 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3308 case Intrinsic::atomic_load_max:
3309 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3310 case Intrinsic::atomic_load_umin:
3311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3312 case Intrinsic::atomic_load_umax:
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3314 case Intrinsic::atomic_swap:
3315 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003316 }
3317}
3318
3319
Duncan Sands6f74b482007-12-19 09:48:52 +00003320void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003321 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003322 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003323 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003324 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003325 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3326 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003327
Jim Laskey735b6f82007-02-22 15:38:06 +00003328 TargetLowering::ArgListTy Args;
3329 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003330 Args.reserve(CS.arg_size());
3331 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3332 i != e; ++i) {
3333 SDOperand ArgNode = getValue(*i);
3334 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003335
Duncan Sands6f74b482007-12-19 09:48:52 +00003336 unsigned attrInd = i - CS.arg_begin() + 1;
3337 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3338 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3339 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3340 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3341 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3342 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003343 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003344 Args.push_back(Entry);
3345 }
3346
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003347 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003348 // Insert a label before the invoke call to mark the try range. This can be
3349 // used to detect deletion of the invoke via the MachineModuleInfo.
3350 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003351 // Both PendingLoads and PendingExports must be flushed here;
3352 // this call might not return.
3353 (void)getRoot();
3354 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003355 DAG.getConstant(BeginLabel, MVT::i32),
3356 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003357 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003358
Jim Laskey735b6f82007-02-22 15:38:06 +00003359 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003360 TLI.LowerCallTo(getRoot(), CS.getType(),
3361 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003362 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003363 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003364 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003365 if (CS.getType() != Type::VoidTy)
3366 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003367 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003368
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003369 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003370 // Insert a label at the end of the invoke call to mark the try range. This
3371 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3372 EndLabel = MMI->NextLabelID();
3373 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003374 DAG.getConstant(EndLabel, MVT::i32),
3375 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003376
Duncan Sands6f74b482007-12-19 09:48:52 +00003377 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003378 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3379 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003380}
3381
3382
Chris Lattner1c08c712005-01-07 07:47:53 +00003383void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003384 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003385 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003386 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003387 if (unsigned IID = F->getIntrinsicID()) {
3388 RenameFn = visitIntrinsicCall(I, IID);
3389 if (!RenameFn)
3390 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003391 }
3392 }
3393
3394 // Check for well-known libc/libm calls. If the function is internal, it
3395 // can't be a library call.
3396 unsigned NameLen = F->getNameLen();
3397 if (!F->hasInternalLinkage() && NameLen) {
3398 const char *NameStr = F->getNameStart();
3399 if (NameStr[0] == 'c' &&
3400 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3401 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3402 if (I.getNumOperands() == 3 && // Basic sanity checks.
3403 I.getOperand(1)->getType()->isFloatingPoint() &&
3404 I.getType() == I.getOperand(1)->getType() &&
3405 I.getType() == I.getOperand(2)->getType()) {
3406 SDOperand LHS = getValue(I.getOperand(1));
3407 SDOperand RHS = getValue(I.getOperand(2));
3408 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3409 LHS, RHS));
3410 return;
3411 }
3412 } else if (NameStr[0] == 'f' &&
3413 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003414 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3415 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003416 if (I.getNumOperands() == 2 && // Basic sanity checks.
3417 I.getOperand(1)->getType()->isFloatingPoint() &&
3418 I.getType() == I.getOperand(1)->getType()) {
3419 SDOperand Tmp = getValue(I.getOperand(1));
3420 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3421 return;
3422 }
3423 } else if (NameStr[0] == 's' &&
3424 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003425 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3426 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003427 if (I.getNumOperands() == 2 && // Basic sanity checks.
3428 I.getOperand(1)->getType()->isFloatingPoint() &&
3429 I.getType() == I.getOperand(1)->getType()) {
3430 SDOperand Tmp = getValue(I.getOperand(1));
3431 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3432 return;
3433 }
3434 } else if (NameStr[0] == 'c' &&
3435 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003436 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3437 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003438 if (I.getNumOperands() == 2 && // Basic sanity checks.
3439 I.getOperand(1)->getType()->isFloatingPoint() &&
3440 I.getType() == I.getOperand(1)->getType()) {
3441 SDOperand Tmp = getValue(I.getOperand(1));
3442 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3443 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003444 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003445 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003446 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003447 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003448 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003449 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003450 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003451
Chris Lattner64e14b12005-01-08 22:48:57 +00003452 SDOperand Callee;
3453 if (!RenameFn)
3454 Callee = getValue(I.getOperand(0));
3455 else
3456 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003457
Duncan Sands6f74b482007-12-19 09:48:52 +00003458 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003459}
3460
Jim Laskey735b6f82007-02-22 15:38:06 +00003461
Dan Gohmanef5d1942008-03-11 21:11:25 +00003462void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003463 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003464 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3465 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003466 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003467 }
Chris Lattner6833b062008-04-28 07:16:35 +00003468
3469 // To add support for individual return values with aggregate types,
3470 // we'd need a way to take a getresult index and determine which
3471 // values of the Call SDNode are associated with it.
3472 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3473 "Individual return values must not be aggregates!");
3474
3475 SDOperand Call = getValue(I.getOperand(0));
3476 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003477}
3478
3479
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003480/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3481/// this value and returns the result as a ValueVT value. This uses
3482/// Chain/Flag as the input and updates them for the output Chain/Flag.
3483/// If the Flag pointer is NULL, no flag is used.
3484SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003485 SDOperand &Chain,
3486 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003487 // Assemble the legal parts into the final values.
3488 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003489 SmallVector<SDOperand, 8> Parts;
3490 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003491 // Copy the legal parts from the registers.
3492 MVT::ValueType ValueVT = ValueVTs[Value];
3493 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3494 MVT::ValueType RegisterVT = RegVTs[Value];
3495
Chris Lattner6833b062008-04-28 07:16:35 +00003496 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003497 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003498 SDOperand P;
3499 if (Flag == 0)
3500 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3501 else {
3502 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003503 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003504 }
3505 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003506 Parts[Part+i] = P;
3507 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003508
Dan Gohman23ce5022008-04-25 18:27:55 +00003509 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3510 ValueVT);
3511 Part += NumRegs;
3512 }
Chris Lattner6833b062008-04-28 07:16:35 +00003513
3514 if (ValueVTs.size() == 1)
3515 return Values[0];
3516
Dan Gohman23ce5022008-04-25 18:27:55 +00003517 return DAG.getNode(ISD::MERGE_VALUES,
3518 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3519 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003520}
3521
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003522/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3523/// specified value into the registers specified by this object. This uses
3524/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003525/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003526void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003527 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003528 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003529 unsigned NumRegs = Regs.size();
3530 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003531 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003532 MVT::ValueType ValueVT = ValueVTs[Value];
3533 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3534 MVT::ValueType RegisterVT = RegVTs[Value];
3535
3536 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3537 &Parts[Part], NumParts, RegisterVT);
3538 Part += NumParts;
3539 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003540
3541 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003542 SmallVector<SDOperand, 8> Chains(NumRegs);
3543 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003544 SDOperand Part;
3545 if (Flag == 0)
3546 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3547 else {
3548 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003549 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003550 }
3551 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003552 }
Chris Lattner6833b062008-04-28 07:16:35 +00003553
Evan Cheng33bf38a2008-04-28 22:07:13 +00003554 if (NumRegs == 1 || Flag)
3555 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3556 // flagged to it. That is the CopyToReg nodes and the user are considered
3557 // a single scheduling unit. If we create a TokenFactor and return it as
3558 // chain, then the TokenFactor is both a predecessor (operand) of the
3559 // user as well as a successor (the TF operands are flagged to the user).
3560 // c1, f1 = CopyToReg
3561 // c2, f2 = CopyToReg
3562 // c3 = TokenFactor c1, c2
3563 // ...
3564 // = op c3, ..., f2
3565 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003566 else
3567 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003568}
Chris Lattner864635a2006-02-22 22:37:12 +00003569
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003570/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3571/// operand list. This adds the code marker and includes the number of
3572/// values added into it.
3573void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003574 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003575 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3576 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003577 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3578 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003579 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003580 for (unsigned i = 0; i != NumRegs; ++i)
3581 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003582 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003583}
Chris Lattner864635a2006-02-22 22:37:12 +00003584
3585/// isAllocatableRegister - If the specified register is safe to allocate,
3586/// i.e. it isn't a stack pointer or some other special register, return the
3587/// register class for the register. Otherwise, return null.
3588static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003589isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003590 const TargetLowering &TLI,
3591 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003592 MVT::ValueType FoundVT = MVT::Other;
3593 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003594 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3595 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003596 MVT::ValueType ThisVT = MVT::Other;
3597
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003598 const TargetRegisterClass *RC = *RCI;
3599 // If none of the the value types for this register class are valid, we
3600 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003601 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3602 I != E; ++I) {
3603 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003604 // If we have already found this register in a different register class,
3605 // choose the one with the largest VT specified. For example, on
3606 // PowerPC, we favor f64 register classes over f32.
3607 if (FoundVT == MVT::Other ||
3608 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3609 ThisVT = *I;
3610 break;
3611 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003612 }
3613 }
3614
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003615 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003616
Chris Lattner864635a2006-02-22 22:37:12 +00003617 // NOTE: This isn't ideal. In particular, this might allocate the
3618 // frame pointer in functions that need it (due to them not being taken
3619 // out of allocation, because a variable sized allocation hasn't been seen
3620 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003621 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3622 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003623 if (*I == Reg) {
3624 // We found a matching register class. Keep looking at others in case
3625 // we find one with larger registers that this physreg is also in.
3626 FoundRC = RC;
3627 FoundVT = ThisVT;
3628 break;
3629 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003630 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003631 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003632}
3633
Chris Lattner4e4b5762006-02-01 18:59:47 +00003634
Chris Lattner0c583402007-04-28 20:49:53 +00003635namespace {
3636/// AsmOperandInfo - This contains information for each constraint that we are
3637/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003638struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3639 /// CallOperand - If this is the result output operand or a clobber
3640 /// this is null, otherwise it is the incoming operand to the CallInst.
3641 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003642 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003643
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003644 /// AssignedRegs - If this is a register or register class operand, this
3645 /// contains the set of register corresponding to the operand.
3646 RegsForValue AssignedRegs;
3647
Dan Gohman23ce5022008-04-25 18:27:55 +00003648 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003649 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003650 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003651
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003652 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3653 /// busy in OutputRegs/InputRegs.
3654 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3655 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003656 std::set<unsigned> &InputRegs,
3657 const TargetRegisterInfo &TRI) const {
3658 if (isOutReg) {
3659 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3660 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3661 }
3662 if (isInReg) {
3663 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3664 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3665 }
3666 }
3667
3668private:
3669 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3670 /// specified set.
3671 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3672 const TargetRegisterInfo &TRI) {
3673 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3674 Regs.insert(Reg);
3675 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3676 for (; *Aliases; ++Aliases)
3677 Regs.insert(*Aliases);
3678 }
Chris Lattner0c583402007-04-28 20:49:53 +00003679};
3680} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003681
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003682
Chris Lattner0fe71e92008-02-21 19:43:13 +00003683/// GetRegistersForValue - Assign registers (virtual or physical) for the
3684/// specified operand. We prefer to assign virtual registers, to allow the
3685/// register allocator handle the assignment process. However, if the asm uses
3686/// features that we can't model on machineinstrs, we have SDISel do the
3687/// allocation. This produces generally horrible, but correct, code.
3688///
3689/// OpInfo describes the operand.
3690/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3691/// or any explicitly clobbered registers.
3692/// Input and OutputRegs are the set of already allocated physical registers.
3693///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003694void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003695GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003696 std::set<unsigned> &OutputRegs,
3697 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003698 // Compute whether this value requires an input register, an output register,
3699 // or both.
3700 bool isOutReg = false;
3701 bool isInReg = false;
3702 switch (OpInfo.Type) {
3703 case InlineAsm::isOutput:
3704 isOutReg = true;
3705
3706 // If this is an early-clobber output, or if there is an input
3707 // constraint that matches this, we need to reserve the input register
3708 // so no other inputs allocate to it.
3709 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3710 break;
3711 case InlineAsm::isInput:
3712 isInReg = true;
3713 isOutReg = false;
3714 break;
3715 case InlineAsm::isClobber:
3716 isOutReg = true;
3717 isInReg = true;
3718 break;
3719 }
3720
3721
3722 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003723 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003724
3725 // If this is a constraint for a single physreg, or a constraint for a
3726 // register class, find it.
3727 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3728 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3729 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003730
3731 unsigned NumRegs = 1;
3732 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003733 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003734 MVT::ValueType RegVT;
3735 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3736
Chris Lattnerbf996f12007-04-30 17:29:31 +00003737
3738 // If this is a constraint for a specific physical register, like {r17},
3739 // assign it now.
3740 if (PhysReg.first) {
3741 if (OpInfo.ConstraintVT == MVT::Other)
3742 ValueVT = *PhysReg.second->vt_begin();
3743
3744 // Get the actual register value type. This is important, because the user
3745 // may have asked for (e.g.) the AX register in i32 type. We need to
3746 // remember that AX is actually i16 to get the right extension.
3747 RegVT = *PhysReg.second->vt_begin();
3748
3749 // This is a explicit reference to a physical register.
3750 Regs.push_back(PhysReg.first);
3751
3752 // If this is an expanded reference, add the rest of the regs to Regs.
3753 if (NumRegs != 1) {
3754 TargetRegisterClass::iterator I = PhysReg.second->begin();
3755 TargetRegisterClass::iterator E = PhysReg.second->end();
3756 for (; *I != PhysReg.first; ++I)
3757 assert(I != E && "Didn't find reg!");
3758
3759 // Already added the first reg.
3760 --NumRegs; ++I;
3761 for (; NumRegs; --NumRegs, ++I) {
3762 assert(I != E && "Ran out of registers to allocate!");
3763 Regs.push_back(*I);
3764 }
3765 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003766 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003767 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3768 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003769 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003770 }
3771
3772 // Otherwise, if this was a reference to an LLVM register class, create vregs
3773 // for this reference.
3774 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003775 const TargetRegisterClass *RC = PhysReg.second;
3776 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003777 // If this is an early clobber or tied register, our regalloc doesn't know
3778 // how to maintain the constraint. If it isn't, go ahead and create vreg
3779 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003780 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3781 // If there is some other early clobber and this is an input register,
3782 // then we are forced to pre-allocate the input reg so it doesn't
3783 // conflict with the earlyclobber.
3784 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003785 RegVT = *PhysReg.second->vt_begin();
3786
3787 if (OpInfo.ConstraintVT == MVT::Other)
3788 ValueVT = RegVT;
3789
3790 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003791 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003792 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003793 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003794
Dan Gohman23ce5022008-04-25 18:27:55 +00003795 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003796 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003797 }
3798
3799 // Otherwise, we can't allocate it. Let the code below figure out how to
3800 // maintain these constraints.
3801 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3802
3803 } else {
3804 // This is a reference to a register class that doesn't directly correspond
3805 // to an LLVM register class. Allocate NumRegs consecutive, available,
3806 // registers from the class.
3807 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3808 OpInfo.ConstraintVT);
3809 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003810
Dan Gohman6f0d0242008-02-10 18:45:23 +00003811 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003812 unsigned NumAllocated = 0;
3813 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3814 unsigned Reg = RegClassRegs[i];
3815 // See if this register is available.
3816 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3817 (isInReg && InputRegs.count(Reg))) { // Already used.
3818 // Make sure we find consecutive registers.
3819 NumAllocated = 0;
3820 continue;
3821 }
3822
3823 // Check to see if this register is allocatable (i.e. don't give out the
3824 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003825 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003826 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003827 if (!RC) { // Couldn't allocate this register.
3828 // Reset NumAllocated to make sure we return consecutive registers.
3829 NumAllocated = 0;
3830 continue;
3831 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003832 }
3833
3834 // Okay, this register is good, we can use it.
3835 ++NumAllocated;
3836
3837 // If we allocated enough consecutive registers, succeed.
3838 if (NumAllocated == NumRegs) {
3839 unsigned RegStart = (i-NumAllocated)+1;
3840 unsigned RegEnd = i+1;
3841 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003842 for (unsigned i = RegStart; i != RegEnd; ++i)
3843 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003844
Dan Gohman23ce5022008-04-25 18:27:55 +00003845 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003846 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003847 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003848 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003849 }
3850 }
3851
3852 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003853}
3854
3855
Chris Lattnerce7518c2006-01-26 22:24:51 +00003856/// visitInlineAsm - Handle a call to an InlineAsm object.
3857///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003858void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3859 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003860
Chris Lattner0c583402007-04-28 20:49:53 +00003861 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003862 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003863
3864 SDOperand Chain = getRoot();
3865 SDOperand Flag;
3866
Chris Lattner4e4b5762006-02-01 18:59:47 +00003867 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003868
Chris Lattner0c583402007-04-28 20:49:53 +00003869 // Do a prepass over the constraints, canonicalizing them, and building up the
3870 // ConstraintOperands list.
3871 std::vector<InlineAsm::ConstraintInfo>
3872 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003873
3874 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3875 // constraint. If so, we can't let the register allocator allocate any input
3876 // registers, because it will not know to avoid the earlyclobbered output reg.
3877 bool SawEarlyClobber = false;
3878
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003879 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003880 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003881 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003882 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3883 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003884
Chris Lattner0c583402007-04-28 20:49:53 +00003885 MVT::ValueType OpVT = MVT::Other;
3886
3887 // Compute the value type for each operand.
3888 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003889 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003890 // Indirect outputs just consume an argument.
3891 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003892 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003893 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003894 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003895 // The return value of the call is this value. As such, there is no
3896 // corresponding argument.
3897 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3898 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3899 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3900 } else {
3901 assert(ResNo == 0 && "Asm only has one result!");
3902 OpVT = TLI.getValueType(CS.getType());
3903 }
3904 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003905 break;
3906 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003907 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003908 break;
3909 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003910 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003911 break;
3912 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003913
Chris Lattner0c583402007-04-28 20:49:53 +00003914 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003915 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003916 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003917 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3918 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003919 else {
3920 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3921 const Type *OpTy = OpInfo.CallOperandVal->getType();
3922 // If this is an indirect operand, the operand is a pointer to the
3923 // accessed type.
3924 if (OpInfo.isIndirect)
3925 OpTy = cast<PointerType>(OpTy)->getElementType();
3926
3927 // If OpTy is not a first-class value, it may be a struct/union that we
3928 // can tile with integers.
3929 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3930 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3931 switch (BitSize) {
3932 default: break;
3933 case 1:
3934 case 8:
3935 case 16:
3936 case 32:
3937 case 64:
3938 OpTy = IntegerType::get(BitSize);
3939 break;
3940 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003941 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003942
3943 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003944 }
3945 }
3946
3947 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003948
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003949 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003950 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003951
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003952 // Keep track of whether we see an earlyclobber.
3953 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003954
Chris Lattner0fe71e92008-02-21 19:43:13 +00003955 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003956 if (!SawEarlyClobber &&
3957 OpInfo.Type == InlineAsm::isClobber &&
3958 OpInfo.ConstraintType == TargetLowering::C_Register) {
3959 // Note that we want to ignore things that we don't trick here, like
3960 // dirflag, fpsr, flags, etc.
3961 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3962 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3963 OpInfo.ConstraintVT);
3964 if (PhysReg.first || PhysReg.second) {
3965 // This is a register we know of.
3966 SawEarlyClobber = true;
3967 }
3968 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003969
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003970 // If this is a memory input, and if the operand is not indirect, do what we
3971 // need to to provide an address for the memory input.
3972 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3973 !OpInfo.isIndirect) {
3974 assert(OpInfo.Type == InlineAsm::isInput &&
3975 "Can only indirectify direct input operands!");
3976
3977 // Memory operands really want the address of the value. If we don't have
3978 // an indirect input, put it in the constpool if we can, otherwise spill
3979 // it to a stack slot.
3980
3981 // If the operand is a float, integer, or vector constant, spill to a
3982 // constant pool entry to get its address.
3983 Value *OpVal = OpInfo.CallOperandVal;
3984 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3985 isa<ConstantVector>(OpVal)) {
3986 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3987 TLI.getPointerTy());
3988 } else {
3989 // Otherwise, create a stack slot and emit a store to it before the
3990 // asm.
3991 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003992 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003993 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3994 MachineFunction &MF = DAG.getMachineFunction();
3995 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3996 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3997 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3998 OpInfo.CallOperand = StackSlot;
3999 }
4000
4001 // There is no longer a Value* corresponding to this operand.
4002 OpInfo.CallOperandVal = 0;
4003 // It is now an indirect operand.
4004 OpInfo.isIndirect = true;
4005 }
4006
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004007 // If this constraint is for a specific register, allocate it before
4008 // anything else.
4009 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4010 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004011 }
Chris Lattner0c583402007-04-28 20:49:53 +00004012 ConstraintInfos.clear();
4013
4014
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004015 // Second pass - Loop over all of the operands, assigning virtual or physregs
4016 // to registerclass operands.
4017 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004018 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004019
4020 // C_Register operands have already been allocated, Other/Memory don't need
4021 // to be.
4022 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4023 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4024 }
4025
Chris Lattner0c583402007-04-28 20:49:53 +00004026 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4027 std::vector<SDOperand> AsmNodeOperands;
4028 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4029 AsmNodeOperands.push_back(
4030 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4031
Chris Lattner2cc2f662006-02-01 01:28:23 +00004032
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004033 // Loop over all of the inputs, copying the operand values into the
4034 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004035 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004036
Chris Lattner0c583402007-04-28 20:49:53 +00004037 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4038 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4039
4040 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004041 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004042
Chris Lattner0c583402007-04-28 20:49:53 +00004043 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004044 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004045 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4046 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004047 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004048 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004049
Chris Lattner22873462006-02-27 23:45:39 +00004050 // Add information to the INLINEASM node to know about this output.
4051 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004052 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4053 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004054 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004055 break;
4056 }
4057
Chris Lattner2a600be2007-04-28 21:01:43 +00004058 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004059
Chris Lattner864635a2006-02-22 22:37:12 +00004060 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004061 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004062 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004063 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004064 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004065 exit(1);
4066 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004067
Chris Lattner41f62592008-04-29 04:29:54 +00004068 // If this is an indirect operand, store through the pointer after the
4069 // asm.
4070 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004071 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004072 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004073 } else {
4074 // This is the result value of the call.
4075 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4076 // Concatenate this output onto the outputs list.
4077 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004078 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004079
4080 // Add information to the INLINEASM node to know that this register is
4081 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004082 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4083 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004084 break;
4085 }
4086 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004087 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004088
Chris Lattner0c583402007-04-28 20:49:53 +00004089 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004090 // If this is required to match an output register we have already set,
4091 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004092 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004093
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004094 // Scan until we find the definition we already emitted of this operand.
4095 // When we find it, create a RegsForValue operand.
4096 unsigned CurOp = 2; // The first operand.
4097 for (; OperandNo; --OperandNo) {
4098 // Advance to the next operand.
4099 unsigned NumOps =
4100 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004101 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4102 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004103 "Skipped past definitions?");
4104 CurOp += (NumOps>>3)+1;
4105 }
4106
4107 unsigned NumOps =
4108 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004109 if ((NumOps & 7) == 2 /*REGDEF*/) {
4110 // Add NumOps>>3 registers to MatchedRegs.
4111 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004112 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004113 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4114 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004115 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4116 unsigned Reg =
4117 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4118 MatchedRegs.Regs.push_back(Reg);
4119 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004120
Chris Lattner527fae12007-02-01 01:21:12 +00004121 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004122 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004123 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4124 break;
4125 } else {
4126 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004127 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4128 // Add information to the INLINEASM node to know about this input.
4129 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4130 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4131 TLI.getPointerTy()));
4132 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4133 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004134 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004135 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004136
Chris Lattner2a600be2007-04-28 21:01:43 +00004137 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004138 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004139 "Don't know how to handle indirect other inputs yet!");
4140
Chris Lattner48884cd2007-08-25 00:47:38 +00004141 std::vector<SDOperand> Ops;
4142 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4143 Ops, DAG);
4144 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004145 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004146 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004147 exit(1);
4148 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004149
4150 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004151 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004152 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4153 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004154 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004155 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004156 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004157 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004158 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4159 "Memory operands expect pointer values");
4160
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004161 // Add information to the INLINEASM node to know about this input.
4162 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004163 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4164 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004165 AsmNodeOperands.push_back(InOperandVal);
4166 break;
4167 }
4168
Chris Lattner2a600be2007-04-28 21:01:43 +00004169 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4170 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4171 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004172 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004173 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004174
4175 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004176 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4177 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004178
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004179 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004180
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004181 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4182 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004183 break;
4184 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004185 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004186 // Add the clobbered value to the operand list, so that the register
4187 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004188 if (!OpInfo.AssignedRegs.Regs.empty())
4189 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4190 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004191 break;
4192 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004193 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004194 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004195
4196 // Finish up input operands.
4197 AsmNodeOperands[0] = Chain;
4198 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4199
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004200 Chain = DAG.getNode(ISD::INLINEASM,
4201 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004202 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004203 Flag = Chain.getValue(1);
4204
Chris Lattner6656dd12006-01-31 02:03:41 +00004205 // If this asm returns a register value, copy the result from that register
4206 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004207 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004208 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004209
4210 // If any of the results of the inline asm is a vector, it may have the
4211 // wrong width/num elts. This can happen for register classes that can
4212 // contain multiple different value types. The preg or vreg allocated may
4213 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004214 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004215 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4216 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4217 if (MVT::isVector(Val.Val->getValueType(i)))
4218 Val = DAG.getNode(ISD::BIT_CONVERT,
4219 TLI.getValueType(ResSTy->getElementType(i)), Val);
4220 }
4221 } else {
4222 if (MVT::isVector(Val.getValueType()))
4223 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4224 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004225 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004226
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004227 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004228 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004229
Chris Lattner6656dd12006-01-31 02:03:41 +00004230 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4231
4232 // Process indirect outputs, first output all of the flagged copies out of
4233 // physregs.
4234 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004235 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004236 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004237 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004238 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004239 }
4240
4241 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004242 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004243 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004244 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004245 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004246 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004247 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004248 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4249 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004250 DAG.setRoot(Chain);
4251}
4252
4253
Chris Lattner1c08c712005-01-07 07:47:53 +00004254void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4255 SDOperand Src = getValue(I.getOperand(0));
4256
4257 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004258
4259 if (IntPtr < Src.getValueType())
4260 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4261 else if (IntPtr > Src.getValueType())
4262 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004263
4264 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004265 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004266 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004267 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004268
Reid Spencer47857812006-12-31 05:55:36 +00004269 TargetLowering::ArgListTy Args;
4270 TargetLowering::ArgListEntry Entry;
4271 Entry.Node = Src;
4272 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004273 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004274
4275 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004276 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4277 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004278 setValue(&I, Result.first); // Pointers always fit in registers
4279 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004280}
4281
4282void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004283 TargetLowering::ArgListTy Args;
4284 TargetLowering::ArgListEntry Entry;
4285 Entry.Node = getValue(I.getOperand(0));
4286 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004287 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004288 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004289 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004290 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4291 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004292 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4293 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004294}
4295
Evan Chengff9b3732008-01-30 18:18:23 +00004296// EmitInstrWithCustomInserter - This method should be implemented by targets
4297// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004298// instructions are special in various ways, which require special support to
4299// insert. The specified MachineInstr is created but not inserted into any
4300// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004301MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004302 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004303 cerr << "If a target marks an instruction with "
4304 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004305 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004306 abort();
4307 return 0;
4308}
4309
Chris Lattner39ae3622005-01-09 00:00:49 +00004310void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004311 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4312 getValue(I.getOperand(1)),
4313 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004314}
4315
4316void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004317 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4318 getValue(I.getOperand(0)),
4319 DAG.getSrcValue(I.getOperand(0)));
4320 setValue(&I, V);
4321 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004322}
4323
4324void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004325 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4326 getValue(I.getOperand(1)),
4327 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004328}
4329
4330void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004331 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4332 getValue(I.getOperand(1)),
4333 getValue(I.getOperand(2)),
4334 DAG.getSrcValue(I.getOperand(1)),
4335 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004336}
4337
Chris Lattnerfdfded52006-04-12 16:20:43 +00004338/// TargetLowering::LowerArguments - This is the default LowerArguments
4339/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004340/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4341/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004342std::vector<SDOperand>
4343TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4344 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4345 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004346 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004347 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4348 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4349
4350 // Add one result value for each formal argument.
4351 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004352 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004353 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4354 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004355 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004356 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004357 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004358 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004359
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004360 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004361 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004362 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004363 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004364 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004365 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004366 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004367 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004368 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004369 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004370 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004371 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004372 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004373 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004374 // For ByVal, alignment should be passed from FE. BE will guess if
4375 // this info is not there but there are cases it cannot get right.
4376 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004377 FrameAlign = F.getParamAlignment(j);
4378 Flags.setByValAlign(FrameAlign);
4379 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004380 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004381 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004382 Flags.setNest();
4383 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004384
4385 MVT::ValueType RegisterVT = getRegisterType(VT);
4386 unsigned NumRegs = getNumRegisters(VT);
4387 for (unsigned i = 0; i != NumRegs; ++i) {
4388 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004389 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004390 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004391 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004392 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004393 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004394 MyFlags.setOrigAlign(1);
4395 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004396 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004397 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004398
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004399 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004400
4401 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004402 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004403 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004404 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004405
4406 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4407 // allows exposing the loads that may be part of the argument access to the
4408 // first DAGCombiner pass.
4409 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4410
4411 // The number of results should match up, except that the lowered one may have
4412 // an extra flag result.
4413 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4414 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4415 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4416 && "Lowering produced unexpected number of results!");
4417 Result = TmpRes.Val;
4418
Dan Gohman27a70be2007-07-02 16:18:06 +00004419 unsigned NumArgRegs = Result->getNumValues() - 1;
4420 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004421
4422 // Set up the return result vector.
4423 Ops.clear();
4424 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004425 unsigned Idx = 1;
4426 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4427 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004428 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004429 MVT::ValueType PartVT = getRegisterType(VT);
4430
4431 unsigned NumParts = getNumRegisters(VT);
4432 SmallVector<SDOperand, 4> Parts(NumParts);
4433 for (unsigned j = 0; j != NumParts; ++j)
4434 Parts[j] = SDOperand(Result, i++);
4435
4436 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4437 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4438 AssertOp = ISD::AssertSext;
4439 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4440 AssertOp = ISD::AssertZext;
4441
4442 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004443 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004444 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004445 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004446 return Ops;
4447}
4448
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004449
4450/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4451/// implementation, which just inserts an ISD::CALL node, which is later custom
4452/// lowered by the target to something concrete. FIXME: When all targets are
4453/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4454std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004455TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4456 bool RetSExt, bool RetZExt, bool isVarArg,
4457 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004458 SDOperand Callee,
4459 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004460 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004461 Ops.push_back(Chain); // Op#0 - Chain
4462 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4463 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4464 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4465 Ops.push_back(Callee);
4466
4467 // Handle all of the outgoing arguments.
4468 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004469 MVT::ValueType VT = getValueType(Args[i].Ty);
4470 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004471 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004472 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004473 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004474
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004475 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004476 Flags.setZExt();
4477 if (Args[i].isSExt)
4478 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004479 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004480 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004481 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004482 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004483 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004484 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004485 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004486 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004487 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004488 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004489 // For ByVal, alignment should come from FE. BE will guess if this
4490 // info is not there but there are cases it cannot get right.
4491 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004492 FrameAlign = Args[i].Alignment;
4493 Flags.setByValAlign(FrameAlign);
4494 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004495 }
Duncan Sands36397f52007-07-27 12:58:54 +00004496 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004497 Flags.setNest();
4498 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004499
Duncan Sandsb988bac2008-02-11 20:58:28 +00004500 MVT::ValueType PartVT = getRegisterType(VT);
4501 unsigned NumParts = getNumRegisters(VT);
4502 SmallVector<SDOperand, 4> Parts(NumParts);
4503 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4504
4505 if (Args[i].isSExt)
4506 ExtendKind = ISD::SIGN_EXTEND;
4507 else if (Args[i].isZExt)
4508 ExtendKind = ISD::ZERO_EXTEND;
4509
4510 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4511
4512 for (unsigned i = 0; i != NumParts; ++i) {
4513 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004514 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004515 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004516 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004517 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004518 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004519
4520 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004521 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004522 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004523 }
4524
Dan Gohmanef5d1942008-03-11 21:11:25 +00004525 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004526 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004527 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4528 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004529 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004530
Dan Gohman23ce5022008-04-25 18:27:55 +00004531 // Then we translate that to a list of legal types.
4532 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4533 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004534 MVT::ValueType RegisterVT = getRegisterType(VT);
4535 unsigned NumRegs = getNumRegisters(VT);
4536 for (unsigned i = 0; i != NumRegs; ++i)
4537 LoweredRetTys.push_back(RegisterVT);
4538 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004539
Dan Gohmanef5d1942008-03-11 21:11:25 +00004540 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004541
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004542 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004543 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004544 DAG.getVTList(&LoweredRetTys[0],
4545 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004546 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004547 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004548
4549 // Gather up the call result into a single value.
4550 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004551 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4552
4553 if (RetSExt)
4554 AssertOp = ISD::AssertSext;
4555 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004556 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004557
Dan Gohmanef5d1942008-03-11 21:11:25 +00004558 SmallVector<SDOperand, 4> ReturnValues;
4559 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004560 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4561 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004562 MVT::ValueType RegisterVT = getRegisterType(VT);
4563 unsigned NumRegs = getNumRegisters(VT);
4564 unsigned RegNoEnd = NumRegs + RegNo;
4565 SmallVector<SDOperand, 4> Results;
4566 for (; RegNo != RegNoEnd; ++RegNo)
4567 Results.push_back(Res.getValue(RegNo));
4568 SDOperand ReturnValue =
4569 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4570 AssertOp);
4571 ReturnValues.push_back(ReturnValue);
4572 }
4573 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4574 DAG.getNode(ISD::MERGE_VALUES,
4575 DAG.getVTList(&RetTys[0], RetTys.size()),
4576 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004577 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004578
4579 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004580}
4581
Chris Lattner50381b62005-05-14 05:50:48 +00004582SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004583 assert(0 && "LowerOperation not implemented for this target!");
4584 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004585 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004586}
4587
Nate Begeman0aed7842006-01-28 03:14:31 +00004588SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4589 SelectionDAG &DAG) {
4590 assert(0 && "CustomPromoteOperation not implemented for this target!");
4591 abort();
4592 return SDOperand();
4593}
4594
Chris Lattner7041ee32005-01-11 05:56:49 +00004595//===----------------------------------------------------------------------===//
4596// SelectionDAGISel code
4597//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004598
4599unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004600 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004601}
4602
Chris Lattner495a0b52005-08-17 06:37:43 +00004603void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004604 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004605 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004606 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004607}
Chris Lattner1c08c712005-01-07 07:47:53 +00004608
Chris Lattner1c08c712005-01-07 07:47:53 +00004609bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004610 // Get alias analysis for load/store combining.
4611 AA = &getAnalysis<AliasAnalysis>();
4612
Chris Lattner1c08c712005-01-07 07:47:53 +00004613 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004614 if (MF.getFunction()->hasCollector())
4615 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4616 else
4617 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004618 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004619 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004620
4621 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4622
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004623 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4624 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4625 // Mark landing pad.
4626 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004627
4628 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004629 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004630
Evan Chengad2070c2007-02-10 02:43:39 +00004631 // Add function live-ins to entry block live-in set.
4632 BasicBlock *EntryBB = &Fn.getEntryBlock();
4633 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004634 if (!RegInfo->livein_empty())
4635 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4636 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004637 BB->addLiveIn(I->first);
4638
Duncan Sandsf4070822007-06-15 19:04:19 +00004639#ifndef NDEBUG
4640 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4641 "Not all catch info was assigned to a landing pad!");
4642#endif
4643
Chris Lattner1c08c712005-01-07 07:47:53 +00004644 return true;
4645}
4646
Chris Lattner6833b062008-04-28 07:16:35 +00004647void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004648 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004649 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004650 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004651 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004652 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004653
Dan Gohman23ce5022008-04-25 18:27:55 +00004654 RegsForValue RFV(TLI, Reg, V->getType());
4655 SDOperand Chain = DAG.getEntryNode();
4656 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4657 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004658}
4659
Chris Lattner068a81e2005-01-17 17:15:02 +00004660void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004661LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004662 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004663 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004664 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004665 SDOperand OldRoot = SDL.DAG.getRoot();
4666 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004667
Chris Lattnerbf209482005-10-30 19:42:35 +00004668 unsigned a = 0;
4669 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4670 AI != E; ++AI, ++a)
4671 if (!AI->use_empty()) {
4672 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004673
Chris Lattnerbf209482005-10-30 19:42:35 +00004674 // If this argument is live outside of the entry block, insert a copy from
4675 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004676 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4677 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004678 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004679 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004680 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004681
Chris Lattnerbf209482005-10-30 19:42:35 +00004682 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004683 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004684 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004685}
4686
Duncan Sandsf4070822007-06-15 19:04:19 +00004687static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4688 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004689 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004690 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004691 // Apply the catch info to DestBB.
4692 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4693#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004694 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4695 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004696#endif
4697 }
4698}
4699
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004700/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4701/// whether object offset >= 0.
4702static bool
4703IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4704 if (!isa<FrameIndexSDNode>(Op)) return false;
4705
4706 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4707 int FrameIdx = FrameIdxNode->getIndex();
4708 return MFI->isFixedObjectIndex(FrameIdx) &&
4709 MFI->getObjectOffset(FrameIdx) >= 0;
4710}
4711
4712/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4713/// possibly be overwritten when lowering the outgoing arguments in a tail
4714/// call. Currently the implementation of this call is very conservative and
4715/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4716/// virtual registers would be overwritten by direct lowering.
4717static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4718 MachineFrameInfo * MFI) {
4719 RegisterSDNode * OpReg = NULL;
4720 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4721 (Op.getOpcode()== ISD::CopyFromReg &&
4722 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4723 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4724 (Op.getOpcode() == ISD::LOAD &&
4725 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4726 (Op.getOpcode() == ISD::MERGE_VALUES &&
4727 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4728 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4729 getOperand(1))))
4730 return true;
4731 return false;
4732}
4733
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004734/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004735/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004736static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4737 TargetLowering& TLI) {
4738 SDNode * Ret = NULL;
4739 SDOperand Terminator = DAG.getRoot();
4740
4741 // Find RET node.
4742 if (Terminator.getOpcode() == ISD::RET) {
4743 Ret = Terminator.Val;
4744 }
4745
4746 // Fix tail call attribute of CALL nodes.
4747 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4748 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4749 if (BI->getOpcode() == ISD::CALL) {
4750 SDOperand OpRet(Ret, 0);
4751 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4752 bool isMarkedTailCall =
4753 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4754 // If CALL node has tail call attribute set to true and the call is not
4755 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004756 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004757 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004758 if (!isMarkedTailCall) continue;
4759 if (Ret==NULL ||
4760 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4761 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004762 SmallVector<SDOperand, 32> Ops;
4763 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004764 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4765 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004766 if (idx!=3)
4767 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004768 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004769 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4770 }
4771 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004772 } else {
4773 // Look for tail call clobbered arguments. Emit a series of
4774 // copyto/copyfrom virtual register nodes to protect them.
4775 SmallVector<SDOperand, 32> Ops;
4776 SDOperand Chain = OpCall.getOperand(0), InFlag;
4777 unsigned idx=0;
4778 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4779 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4780 SDOperand Arg = *I;
4781 if (idx > 4 && (idx % 2)) {
4782 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4783 getArgFlags().isByVal();
4784 MachineFunction &MF = DAG.getMachineFunction();
4785 MachineFrameInfo *MFI = MF.getFrameInfo();
4786 if (!isByVal &&
4787 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4788 MVT::ValueType VT = Arg.getValueType();
4789 unsigned VReg = MF.getRegInfo().
4790 createVirtualRegister(TLI.getRegClassFor(VT));
4791 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4792 InFlag = Chain.getValue(1);
4793 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4794 Chain = Arg.getValue(1);
4795 InFlag = Arg.getValue(2);
4796 }
4797 }
4798 Ops.push_back(Arg);
4799 }
4800 // Link in chain of CopyTo/CopyFromReg.
4801 Ops[0] = Chain;
4802 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004803 }
4804 }
4805 }
4806}
4807
Chris Lattner1c08c712005-01-07 07:47:53 +00004808void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4809 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004810 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004811 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004812
Chris Lattnerbf209482005-10-30 19:42:35 +00004813 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004814 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004815 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004816
4817 BB = FuncInfo.MBBMap[LLVMBB];
4818 SDL.setCurrentBasicBlock(BB);
4819
Duncan Sandsf4070822007-06-15 19:04:19 +00004820 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004821
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004822 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004823 // Add a label to mark the beginning of the landing pad. Deletion of the
4824 // landing pad can thus be detected via the MachineModuleInfo.
4825 unsigned LabelID = MMI->addLandingPad(BB);
4826 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004827 DAG.getConstant(LabelID, MVT::i32),
4828 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004829
Evan Chenge47c3332007-06-27 18:45:32 +00004830 // Mark exception register as live in.
4831 unsigned Reg = TLI.getExceptionAddressRegister();
4832 if (Reg) BB->addLiveIn(Reg);
4833
4834 // Mark exception selector register as live in.
4835 Reg = TLI.getExceptionSelectorRegister();
4836 if (Reg) BB->addLiveIn(Reg);
4837
Duncan Sandsf4070822007-06-15 19:04:19 +00004838 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4839 // function and list of typeids logically belong to the invoke (or, if you
4840 // like, the basic block containing the invoke), and need to be associated
4841 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004842 // information is provided by an intrinsic (eh.selector) that can be moved
4843 // to unexpected places by the optimizers: if the unwind edge is critical,
4844 // then breaking it can result in the intrinsics being in the successor of
4845 // the landing pad, not the landing pad itself. This results in exceptions
4846 // not being caught because no typeids are associated with the invoke.
4847 // This may not be the only way things can go wrong, but it is the only way
4848 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004849 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4850
4851 if (Br && Br->isUnconditional()) { // Critical edge?
4852 BasicBlock::iterator I, E;
4853 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004854 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004855 break;
4856
4857 if (I == E)
4858 // No catch info found - try to extract some from the successor.
4859 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004860 }
4861 }
4862
Chris Lattner1c08c712005-01-07 07:47:53 +00004863 // Lower all of the non-terminator instructions.
4864 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4865 I != E; ++I)
4866 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004867
Chris Lattner1c08c712005-01-07 07:47:53 +00004868 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004869 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004870 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004871 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004872 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004873 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004874 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004875 }
4876
4877 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4878 // ensure constants are generated when needed. Remember the virtual registers
4879 // that need to be added to the Machine PHI nodes as input. We cannot just
4880 // directly add them, because expansion might result in multiple MBB's for one
4881 // BB. As such, the start of the BB might correspond to a different MBB than
4882 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004883 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004884 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004885
4886 // Emit constants only once even if used by multiple PHI nodes.
4887 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004888
Chris Lattner8c494ab2006-10-27 23:50:33 +00004889 // Vector bool would be better, but vector<bool> is really slow.
4890 std::vector<unsigned char> SuccsHandled;
4891 if (TI->getNumSuccessors())
4892 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4893
Dan Gohman532dc2e2007-07-09 20:59:04 +00004894 // Check successor nodes' PHI nodes that expect a constant to be available
4895 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004896 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4897 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004898 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004899 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004900
Chris Lattner8c494ab2006-10-27 23:50:33 +00004901 // If this terminator has multiple identical successors (common for
4902 // switches), only handle each succ once.
4903 unsigned SuccMBBNo = SuccMBB->getNumber();
4904 if (SuccsHandled[SuccMBBNo]) continue;
4905 SuccsHandled[SuccMBBNo] = true;
4906
4907 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004908 PHINode *PN;
4909
4910 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4911 // nodes and Machine PHI nodes, but the incoming operands have not been
4912 // emitted yet.
4913 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004914 (PN = dyn_cast<PHINode>(I)); ++I) {
4915 // Ignore dead phi's.
4916 if (PN->use_empty()) continue;
4917
4918 unsigned Reg;
4919 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004920
Chris Lattner8c494ab2006-10-27 23:50:33 +00004921 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4922 unsigned &RegOut = ConstantsOut[C];
4923 if (RegOut == 0) {
4924 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004925 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004926 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004927 Reg = RegOut;
4928 } else {
4929 Reg = FuncInfo.ValueMap[PHIOp];
4930 if (Reg == 0) {
4931 assert(isa<AllocaInst>(PHIOp) &&
4932 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4933 "Didn't codegen value into a register!??");
4934 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004935 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004936 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004937 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004938
4939 // Remember that this register needs to added to the machine PHI node as
4940 // the input for this MBB.
4941 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004942 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004943 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004944 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4945 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004946 }
4947 ConstantsOut.clear();
4948
4949 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004950 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004951
Nate Begemanf15485a2006-03-27 01:32:24 +00004952 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004953 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004954 SwitchCases.clear();
4955 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004956 JTCases.clear();
4957 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004958 BitTestCases.clear();
4959 BitTestCases = SDL.BitTestCases;
4960
Chris Lattnera651cf62005-01-17 19:43:36 +00004961 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004962 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004963
4964 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4965 // with correct tailcall attribute so that the target can rely on the tailcall
4966 // attribute indicating whether the call is really eligible for tail call
4967 // optimization.
4968 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004969}
4970
Nate Begemanf15485a2006-03-27 01:32:24 +00004971void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004972 DOUT << "Lowered selection DAG:\n";
4973 DEBUG(DAG.dump());
4974
Chris Lattneraf21d552005-10-10 16:47:10 +00004975 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004976 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004977
Dan Gohman417e11b2007-10-08 15:12:17 +00004978 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004979 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004980
Chris Lattner1c08c712005-01-07 07:47:53 +00004981 // Second step, hack on the DAG until it only uses operations and types that
4982 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004983#if 0 // Enable this some day.
4984 DAG.LegalizeTypes();
4985 // Someday even later, enable a dag combine pass here.
4986#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004987 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004988
Bill Wendling832171c2006-12-07 20:04:42 +00004989 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004990 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004991
Chris Lattneraf21d552005-10-10 16:47:10 +00004992 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004993 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004994
Dan Gohman417e11b2007-10-08 15:12:17 +00004995 DOUT << "Optimized legalized selection DAG:\n";
4996 DEBUG(DAG.dump());
4997
Evan Chenga9c20912006-01-21 02:32:06 +00004998 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004999
Chris Lattnera33ef482005-03-30 01:10:47 +00005000 // Third, instruction select all of the operations to machine code, adding the
5001 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005002 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005003
Bill Wendling832171c2006-12-07 20:04:42 +00005004 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005005 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005006}
Chris Lattner1c08c712005-01-07 07:47:53 +00005007
Nate Begemanf15485a2006-03-27 01:32:24 +00005008void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5009 FunctionLoweringInfo &FuncInfo) {
5010 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5011 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005012 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005013 CurDAG = &DAG;
5014
5015 // First step, lower LLVM code to some DAG. This DAG may use operations and
5016 // types that are not supported by the target.
5017 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5018
5019 // Second step, emit the lowered DAG as machine code.
5020 CodeGenAndEmitDAG(DAG);
5021 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005022
5023 DOUT << "Total amount of phi nodes to update: "
5024 << PHINodesToUpdate.size() << "\n";
5025 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5026 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5027 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005028
Chris Lattnera33ef482005-03-30 01:10:47 +00005029 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005030 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005031 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005032 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5033 MachineInstr *PHI = PHINodesToUpdate[i].first;
5034 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5035 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005036 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5037 false));
5038 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005039 }
5040 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005041 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005042
5043 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5044 // Lower header first, if it wasn't already lowered
5045 if (!BitTestCases[i].Emitted) {
5046 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5047 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005048 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005049 // Set the current basic block to the mbb we wish to insert the code into
5050 BB = BitTestCases[i].Parent;
5051 HSDL.setCurrentBasicBlock(BB);
5052 // Emit the code
5053 HSDL.visitBitTestHeader(BitTestCases[i]);
5054 HSDAG.setRoot(HSDL.getRoot());
5055 CodeGenAndEmitDAG(HSDAG);
5056 }
5057
5058 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5059 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5060 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005061 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = BitTestCases[i].Cases[j].ThisBB;
5064 BSDL.setCurrentBasicBlock(BB);
5065 // Emit the code
5066 if (j+1 != ej)
5067 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5068 BitTestCases[i].Reg,
5069 BitTestCases[i].Cases[j]);
5070 else
5071 BSDL.visitBitTestCase(BitTestCases[i].Default,
5072 BitTestCases[i].Reg,
5073 BitTestCases[i].Cases[j]);
5074
5075
5076 BSDAG.setRoot(BSDL.getRoot());
5077 CodeGenAndEmitDAG(BSDAG);
5078 }
5079
5080 // Update PHI Nodes
5081 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5082 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5083 MachineBasicBlock *PHIBB = PHI->getParent();
5084 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5085 "This is not a machine PHI node that we are updating!");
5086 // This is "default" BB. We have two jumps to it. From "header" BB and
5087 // from last "case" BB.
5088 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005089 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5090 false));
5091 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5092 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5093 false));
5094 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5095 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005096 }
5097 // One of "cases" BB.
5098 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5099 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5100 if (cBB->succ_end() !=
5101 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005102 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5103 false));
5104 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005105 }
5106 }
5107 }
5108 }
5109
Nate Begeman9453eea2006-04-23 06:26:20 +00005110 // If the JumpTable record is filled in, then we need to emit a jump table.
5111 // Updating the PHI nodes is tricky in this case, since we need to determine
5112 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005113 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5114 // Lower header first, if it wasn't already lowered
5115 if (!JTCases[i].first.Emitted) {
5116 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5117 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005118 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005119 // Set the current basic block to the mbb we wish to insert the code into
5120 BB = JTCases[i].first.HeaderBB;
5121 HSDL.setCurrentBasicBlock(BB);
5122 // Emit the code
5123 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5124 HSDAG.setRoot(HSDL.getRoot());
5125 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005126 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005127
5128 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5129 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005130 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005131 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005132 BB = JTCases[i].second.MBB;
5133 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005134 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005135 JSDL.visitJumpTable(JTCases[i].second);
5136 JSDAG.setRoot(JSDL.getRoot());
5137 CodeGenAndEmitDAG(JSDAG);
5138
Nate Begeman37efe672006-04-22 18:53:45 +00005139 // Update PHI Nodes
5140 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5141 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5142 MachineBasicBlock *PHIBB = PHI->getParent();
5143 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5144 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005145 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005146 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005147 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5148 false));
5149 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005150 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005151 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005152 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005153 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5154 false));
5155 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005156 }
5157 }
Nate Begeman37efe672006-04-22 18:53:45 +00005158 }
5159
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005160 // If the switch block involved a branch to one of the actual successors, we
5161 // need to update PHI nodes in that block.
5162 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5163 MachineInstr *PHI = PHINodesToUpdate[i].first;
5164 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5165 "This is not a machine PHI node that we are updating!");
5166 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005167 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5168 false));
5169 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005170 }
5171 }
5172
Nate Begemanf15485a2006-03-27 01:32:24 +00005173 // If we generated any switch lowering information, build and codegen any
5174 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005175 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005176 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005177 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005178 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005179
Nate Begemanf15485a2006-03-27 01:32:24 +00005180 // Set the current basic block to the mbb we wish to insert the code into
5181 BB = SwitchCases[i].ThisBB;
5182 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005183
Nate Begemanf15485a2006-03-27 01:32:24 +00005184 // Emit the code
5185 SDL.visitSwitchCase(SwitchCases[i]);
5186 SDAG.setRoot(SDL.getRoot());
5187 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005188
5189 // Handle any PHI nodes in successors of this chunk, as if we were coming
5190 // from the original BB before switch expansion. Note that PHI nodes can
5191 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5192 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005193 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005194 for (MachineBasicBlock::iterator Phi = BB->begin();
5195 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5196 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5197 for (unsigned pn = 0; ; ++pn) {
5198 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5199 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005200 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5201 second, false));
5202 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005203 break;
5204 }
5205 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005206 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005207
5208 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005209 if (BB == SwitchCases[i].FalseBB)
5210 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005211
5212 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005213 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005214 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005215 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005216 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005217 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005218}
Evan Chenga9c20912006-01-21 02:32:06 +00005219
Jim Laskey13ec7022006-08-01 14:21:23 +00005220
Evan Chenga9c20912006-01-21 02:32:06 +00005221//===----------------------------------------------------------------------===//
5222/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5223/// target node in the graph.
5224void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5225 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005226
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005227 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005228
5229 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005230 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005231 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005232 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005233
Jim Laskey9ff542f2006-08-01 18:29:48 +00005234 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005235 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005236
5237 if (ViewSUnitDAGs) SL->viewGraph();
5238
Evan Chengcccf1232006-02-04 06:49:00 +00005239 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005240}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005241
Chris Lattner03fc53c2006-03-06 00:22:00 +00005242
Jim Laskey9ff542f2006-08-01 18:29:48 +00005243HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5244 return new HazardRecognizer();
5245}
5246
Chris Lattner75548062006-10-11 03:58:02 +00005247//===----------------------------------------------------------------------===//
5248// Helper functions used by the generated instruction selector.
5249//===----------------------------------------------------------------------===//
5250// Calls to these methods are generated by tblgen.
5251
5252/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5253/// the dag combiner simplified the 255, we still want to match. RHS is the
5254/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5255/// specified in the .td file (e.g. 255).
5256bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005257 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005258 const APInt &ActualMask = RHS->getAPIntValue();
5259 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005260
5261 // If the actual mask exactly matches, success!
5262 if (ActualMask == DesiredMask)
5263 return true;
5264
5265 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005266 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005267 return false;
5268
5269 // Otherwise, the DAG Combiner may have proven that the value coming in is
5270 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005271 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005272 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005273 return true;
5274
5275 // TODO: check to see if missing bits are just not demanded.
5276
5277 // Otherwise, this pattern doesn't match.
5278 return false;
5279}
5280
5281/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5282/// the dag combiner simplified the 255, we still want to match. RHS is the
5283/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5284/// specified in the .td file (e.g. 255).
5285bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005286 int64_t DesiredMaskS) const {
5287 const APInt &ActualMask = RHS->getAPIntValue();
5288 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005289
5290 // If the actual mask exactly matches, success!
5291 if (ActualMask == DesiredMask)
5292 return true;
5293
5294 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005295 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005296 return false;
5297
5298 // Otherwise, the DAG Combiner may have proven that the value coming in is
5299 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005300 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005301
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005302 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005303 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005304
5305 // If all the missing bits in the or are already known to be set, match!
5306 if ((NeededMask & KnownOne) == NeededMask)
5307 return true;
5308
5309 // TODO: check to see if missing bits are just not demanded.
5310
5311 // Otherwise, this pattern doesn't match.
5312 return false;
5313}
5314
Jim Laskey9ff542f2006-08-01 18:29:48 +00005315
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005316/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5317/// by tblgen. Others should not call it.
5318void SelectionDAGISel::
5319SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5320 std::vector<SDOperand> InOps;
5321 std::swap(InOps, Ops);
5322
5323 Ops.push_back(InOps[0]); // input chain.
5324 Ops.push_back(InOps[1]); // input asm string.
5325
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005326 unsigned i = 2, e = InOps.size();
5327 if (InOps[e-1].getValueType() == MVT::Flag)
5328 --e; // Don't process a flag operand if it is here.
5329
5330 while (i != e) {
5331 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5332 if ((Flags & 7) != 4 /*MEM*/) {
5333 // Just skip over this operand, copying the operands verbatim.
5334 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5335 i += (Flags >> 3) + 1;
5336 } else {
5337 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5338 // Otherwise, this is a memory operand. Ask the target to select it.
5339 std::vector<SDOperand> SelOps;
5340 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005341 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005342 exit(1);
5343 }
5344
5345 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005346 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005347 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005348 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005349 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5350 i += 2;
5351 }
5352 }
5353
5354 // Add the flag input back if present.
5355 if (e != InOps.size())
5356 Ops.push_back(InOps.back());
5357}
Devang Patel794fd752007-05-01 21:15:47 +00005358
Devang Patel19974732007-05-03 01:11:54 +00005359char SelectionDAGISel::ID = 0;