blob: 9ee419251c6b54f4291ada681112b0796f9911cb [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"
Bill Wendling305635a2008-06-27 00:09:40 +000030#include "llvm/CodeGen/MachineDebugInfoDesc.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000034#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000037#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000038#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000039#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000040#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetFrameInfo.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000045#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000047#include "llvm/Support/Debug.h"
48#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/Timer.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattneread0d882008-06-17 06:09:18 +000053static cl::opt<bool>
54EnableValueProp("enable-value-prop", cl::Hidden, cl::init(false));
55
56
Chris Lattnerda8abb02005-09-01 18:44:10 +000057#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000058static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000059ViewISelDAGs("view-isel-dags", cl::Hidden,
60 cl::desc("Pop up a window to show isel dags as they are selected"));
61static cl::opt<bool>
62ViewSchedDAGs("view-sched-dags", cl::Hidden,
63 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000064static cl::opt<bool>
65ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000066 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000067#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000068static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000069#endif
70
Jim Laskeyeb577ba2006-08-02 12:30:23 +000071//===---------------------------------------------------------------------===//
72///
73/// RegisterScheduler class - Track the registration of instruction schedulers.
74///
75//===---------------------------------------------------------------------===//
76MachinePassRegistry RegisterScheduler::Registry;
77
78//===---------------------------------------------------------------------===//
79///
80/// ISHeuristic command line option for instruction schedulers.
81///
82//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000083static cl::opt<RegisterScheduler::FunctionPassCtor, false,
84 RegisterPassParser<RegisterScheduler> >
85ISHeuristic("pre-RA-sched",
86 cl::init(&createDefaultScheduler),
87 cl::desc("Instruction schedulers available (before register"
88 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000089
Dan Gohman844731a2008-05-13 00:00:25 +000090static RegisterScheduler
91defaultListDAGScheduler("default", " Best scheduler for the target",
92 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000093
Evan Cheng5c807602008-02-26 02:33:44 +000094namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000095
Dan Gohman1d685a42008-06-07 02:02:36 +000096/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
97/// insertvalue or extractvalue indices that identify a member, return
98/// the linearized index of the start of the member.
99///
100static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
101 const unsigned *Indices,
102 const unsigned *IndicesEnd,
103 unsigned CurIndex = 0) {
104 // Base case: We're done.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000105 if (Indices && Indices == IndicesEnd)
Dan Gohman1d685a42008-06-07 02:02:36 +0000106 return CurIndex;
107
Chris Lattnerf899fce2008-04-27 23:48:12 +0000108 // Given a struct type, recursively traverse the elements.
109 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000110 for (StructType::element_iterator EB = STy->element_begin(),
111 EI = EB,
Dan Gohman1d685a42008-06-07 02:02:36 +0000112 EE = STy->element_end();
113 EI != EE; ++EI) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000114 if (Indices && *Indices == unsigned(EI - EB))
115 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
116 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000117 }
118 }
119 // Given an array type, recursively traverse the elements.
120 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
121 const Type *EltTy = ATy->getElementType();
122 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000123 if (Indices && *Indices == i)
124 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
125 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000126 }
127 }
128 // We haven't found the type we're looking for, so keep searching.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000129 return CurIndex + 1;
Dan Gohman1d685a42008-06-07 02:02:36 +0000130}
131
132/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133/// MVTs that represent all the individual underlying
134/// non-aggregate types that comprise it.
135///
136/// If Offsets is non-null, it points to a vector to be filled in
137/// with the in-memory offsets of each of the individual values.
138///
139static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140 SmallVectorImpl<MVT> &ValueVTs,
141 SmallVectorImpl<uint64_t> *Offsets = 0,
142 uint64_t StartingOffset = 0) {
143 // Given a struct type, recursively traverse the elements.
144 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146 for (StructType::element_iterator EB = STy->element_begin(),
147 EI = EB,
148 EE = STy->element_end();
149 EI != EE; ++EI)
150 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151 StartingOffset + SL->getElementOffset(EI - EB));
Chris Lattnerf899fce2008-04-27 23:48:12 +0000152 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000154 // Given an array type, recursively traverse the elements.
155 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156 const Type *EltTy = ATy->getElementType();
Dan Gohman1d685a42008-06-07 02:02:36 +0000157 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000158 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
Dan Gohman1d685a42008-06-07 02:02:36 +0000159 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160 StartingOffset + i * EltSize);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000161 return;
162 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000163 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000164 ValueVTs.push_back(TLI.getValueType(Ty));
Dan Gohman1d685a42008-06-07 02:02:36 +0000165 if (Offsets)
166 Offsets->push_back(StartingOffset);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000167}
Dan Gohman23ce5022008-04-25 18:27:55 +0000168
Chris Lattnerf899fce2008-04-27 23:48:12 +0000169namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000170 /// RegsForValue - This struct represents the registers (physical or virtual)
171 /// that a particular set of values is assigned, and the type information about
172 /// the value. The most common situation is to represent one value at a time,
173 /// but struct or array values are handled element-wise as multiple values.
174 /// The splitting of aggregates is performed recursively, so that we never
175 /// have aggregate-typed registers. The values at this point do not necessarily
176 /// have legal types, so each value may require one or more registers of some
177 /// legal type.
178 ///
Chris Lattner95255282006-06-28 23:17:24 +0000179 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000180 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000181 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000182 const TargetLowering *TLI;
183
Dan Gohman0fe00902008-04-28 18:10:39 +0000184 /// ValueVTs - The value types of the values, which may not be legal, and
185 /// may need be promoted or synthesized from one or more registers.
186 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000187 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000188
Dan Gohman0fe00902008-04-28 18:10:39 +0000189 /// RegVTs - The value types of the registers. This is the same size as
190 /// ValueVTs and it records, for each value, what the type of the assigned
191 /// register or registers are. (Individual values are never synthesized
192 /// from more than one type of register.)
193 ///
194 /// With virtual registers, the contents of RegVTs is redundant with TLI's
195 /// getRegisterType member function, however when with physical registers
196 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000197 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000198 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000199
Dan Gohman0fe00902008-04-28 18:10:39 +0000200 /// Regs - This list holds the registers assigned to the values.
201 /// Each legal or promoted value requires one register, and each
202 /// expanded value requires multiple registers.
203 ///
204 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000205
Dan Gohman23ce5022008-04-25 18:27:55 +0000206 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000207
Dan Gohman23ce5022008-04-25 18:27:55 +0000208 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000209 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000210 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000211 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000212 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000213 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000214 const SmallVector<MVT, 4> &regvts,
215 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000216 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000217 RegsForValue(const TargetLowering &tli,
218 unsigned Reg, const Type *Ty) : TLI(&tli) {
219 ComputeValueVTs(tli, Ty, ValueVTs);
220
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000221 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000222 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000223 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000224 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000225 for (unsigned i = 0; i != NumRegs; ++i)
226 Regs.push_back(Reg + i);
227 RegVTs.push_back(RegisterVT);
228 Reg += NumRegs;
229 }
Chris Lattner864635a2006-02-22 22:37:12 +0000230 }
231
Chris Lattner41f62592008-04-29 04:29:54 +0000232 /// append - Add the specified values to this one.
233 void append(const RegsForValue &RHS) {
234 TLI = RHS.TLI;
235 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
238 }
239
240
Chris Lattner864635a2006-02-22 22:37:12 +0000241 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000242 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000243 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000244 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000245 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000246 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000247
248 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249 /// specified value into the registers specified by this object. This uses
250 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000251 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000252 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000253 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000254
255 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256 /// operand list. This adds the code marker and includes the number of
257 /// values added into it.
258 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000259 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000260 };
261}
Evan Cheng4ef10862006-01-23 07:01:07 +0000262
Chris Lattner1c08c712005-01-07 07:47:53 +0000263namespace llvm {
264 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000265 /// createDefaultScheduler - This creates an instruction scheduler appropriate
266 /// for the target.
267 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
268 SelectionDAG *DAG,
Evan Cheng4576f6d2008-07-01 18:05:03 +0000269 MachineBasicBlock *BB,
270 bool Fast) {
Jim Laskey9373beb2006-08-01 19:14:14 +0000271 TargetLowering &TLI = IS->getTargetLowering();
272
273 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
Evan Cheng4576f6d2008-07-01 18:05:03 +0000274 return createTDListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000275 } else {
276 assert(TLI.getSchedulingPreference() ==
277 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Evan Cheng4576f6d2008-07-01 18:05:03 +0000278 return createBURRListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000279 }
280 }
281
282
283 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000284 /// FunctionLoweringInfo - This contains information that is global to a
285 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000286 class FunctionLoweringInfo {
287 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000288 TargetLowering &TLI;
289 Function &Fn;
290 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000291 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000292
293 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
294
295 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
296 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
297
298 /// ValueMap - Since we emit code for the function a basic block at a time,
299 /// we must remember which virtual registers hold the values for
300 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000301 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000302
303 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
304 /// the entry block. This allows the allocas to be efficiently referenced
305 /// anywhere in the function.
306 std::map<const AllocaInst*, int> StaticAllocaMap;
307
Duncan Sandsf4070822007-06-15 19:04:19 +0000308#ifndef NDEBUG
309 SmallSet<Instruction*, 8> CatchInfoLost;
310 SmallSet<Instruction*, 8> CatchInfoFound;
311#endif
312
Duncan Sands83ec4b62008-06-06 12:08:01 +0000313 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000314 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000315 }
Chris Lattner571e4342006-10-27 21:36:01 +0000316
317 /// isExportedInst - Return true if the specified value is an instruction
318 /// exported from its block.
319 bool isExportedInst(const Value *V) {
320 return ValueMap.count(V);
321 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000322
Chris Lattner3c384492006-03-16 19:51:18 +0000323 unsigned CreateRegForValue(const Value *V);
324
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 unsigned InitializeRegForValue(const Value *V) {
326 unsigned &R = ValueMap[V];
327 assert(R == 0 && "Already initialized this value register!");
328 return R = CreateRegForValue(V);
329 }
Chris Lattneread0d882008-06-17 06:09:18 +0000330
331 struct LiveOutInfo {
332 unsigned NumSignBits;
333 APInt KnownOne, KnownZero;
334 LiveOutInfo() : NumSignBits(0) {}
335 };
336
337 /// LiveOutRegInfo - Information about live out vregs, indexed by their
338 /// register number offset by 'FirstVirtualRegister'.
339 std::vector<LiveOutInfo> LiveOutRegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000340 };
341}
342
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000343/// isSelector - Return true if this instruction is a call to the
344/// eh.selector intrinsic.
345static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000346 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000347 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
348 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000349 return false;
350}
351
Chris Lattner1c08c712005-01-07 07:47:53 +0000352/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000353/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000354/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000355static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
356 if (isa<PHINode>(I)) return true;
357 BasicBlock *BB = I->getParent();
358 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000359 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000360 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000361 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000362 return true;
363 return false;
364}
365
Chris Lattnerbf209482005-10-30 19:42:35 +0000366/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000367/// entry block, return true. This includes arguments used by switches, since
368/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000369static bool isOnlyUsedInEntryBlock(Argument *A) {
370 BasicBlock *Entry = A->getParent()->begin();
371 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000372 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000373 return false; // Use not in entry block.
374 return true;
375}
376
Chris Lattner1c08c712005-01-07 07:47:53 +0000377FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000378 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000379 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000380
Chris Lattnerbf209482005-10-30 19:42:35 +0000381 // Create a vreg for each argument register that is not dead and is used
382 // outside of the entry block for the function.
383 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
384 AI != E; ++AI)
385 if (!isOnlyUsedInEntryBlock(AI))
386 InitializeRegForValue(AI);
387
Chris Lattner1c08c712005-01-07 07:47:53 +0000388 // Initialize the mapping of values to registers. This is only set up for
389 // instruction values that are used outside of the block that defines
390 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000391 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000392 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
393 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000394 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000395 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000396 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000397 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000398 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000399 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000400
Reid Spencerb83eb642006-10-20 07:07:24 +0000401 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000402 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000403 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000404 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000405 }
406
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000407 for (; BB != EB; ++BB)
408 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000409 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
410 if (!isa<AllocaInst>(I) ||
411 !StaticAllocaMap.count(cast<AllocaInst>(I)))
412 InitializeRegForValue(I);
413
414 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
415 // also creates the initial PHI MachineInstrs, though none of the input
416 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000417 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000418 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
419 MBBMap[BB] = MBB;
420 MF.getBasicBlockList().push_back(MBB);
421
422 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
423 // appropriate.
424 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000425 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
426 if (PN->use_empty()) continue;
427
Duncan Sands83ec4b62008-06-06 12:08:01 +0000428 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000429 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000430 unsigned PHIReg = ValueMap[PN];
431 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000432 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000433 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000434 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000435 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000436 }
437}
438
Chris Lattner3c384492006-03-16 19:51:18 +0000439/// CreateRegForValue - Allocate the appropriate number of virtual registers of
440/// the correctly promoted or expanded types. Assign these registers
441/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000442///
443/// In the case that the given value has struct or array type, this function
444/// will assign registers for each member or element.
445///
Chris Lattner3c384492006-03-16 19:51:18 +0000446unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000447 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000448 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000449
Dan Gohman23ce5022008-04-25 18:27:55 +0000450 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000451 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000452 MVT ValueVT = ValueVTs[Value];
453 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000454
Chris Lattnerb606dba2008-04-28 06:44:42 +0000455 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000456 for (unsigned i = 0; i != NumRegs; ++i) {
457 unsigned R = MakeReg(RegisterVT);
458 if (!FirstReg) FirstReg = R;
459 }
460 }
461 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000462}
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
464//===----------------------------------------------------------------------===//
465/// SelectionDAGLowering - This is the common target-independent lowering
466/// implementation that is parameterized by a TargetLowering object.
467/// Also, targets can overload any lowering method.
468///
469namespace llvm {
470class SelectionDAGLowering {
471 MachineBasicBlock *CurMBB;
472
Chris Lattner0da331f2007-02-04 01:31:47 +0000473 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000474
Chris Lattnerd3948112005-01-17 22:19:26 +0000475 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
476 /// them up and then emit token factor nodes when possible. This allows us to
477 /// get simple disambiguation between loads without worrying about alias
478 /// analysis.
Dan Gohmana44b6742008-06-30 20:31:15 +0000479 SmallVector<SDOperand, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000480
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000481 /// PendingExports - CopyToReg nodes that copy values to virtual registers
482 /// for export to other blocks need to be emitted before any terminator
483 /// instruction, but they have no other ordering requirements. We bunch them
484 /// up and the emit a single tokenfactor for them just before terminator
485 /// instructions.
486 std::vector<SDOperand> PendingExports;
487
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000488 /// Case - A struct to record the Value for a switch case, and the
489 /// case's target basic block.
490 struct Case {
491 Constant* Low;
492 Constant* High;
493 MachineBasicBlock* BB;
494
495 Case() : Low(0), High(0), BB(0) { }
496 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
497 Low(low), High(high), BB(bb) { }
498 uint64_t size() const {
499 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
500 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
501 return (rHigh - rLow + 1ULL);
502 }
503 };
504
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000505 struct CaseBits {
506 uint64_t Mask;
507 MachineBasicBlock* BB;
508 unsigned Bits;
509
510 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
511 Mask(mask), BB(bb), Bits(bits) { }
512 };
513
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000514 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000515 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000516 typedef CaseVector::iterator CaseItr;
517 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000518
519 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
520 /// of conditional branches.
521 struct CaseRec {
522 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
523 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
524
525 /// CaseBB - The MBB in which to emit the compare and branch
526 MachineBasicBlock *CaseBB;
527 /// LT, GE - If nonzero, we know the current case value must be less-than or
528 /// greater-than-or-equal-to these Constants.
529 Constant *LT;
530 Constant *GE;
531 /// Range - A pair of iterators representing the range of case values to be
532 /// processed at this point in the binary search tree.
533 CaseRange Range;
534 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000535
536 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000537
538 /// The comparison function for sorting the switch case values in the vector.
539 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000540 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000541 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000542 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
543 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
544 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
545 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000546 }
547 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000548
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000549 struct CaseBitsCmp {
550 bool operator () (const CaseBits& C1, const CaseBits& C2) {
551 return C1.Bits > C2.Bits;
552 }
553 };
554
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000555 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000556
Chris Lattner1c08c712005-01-07 07:47:53 +0000557public:
558 // TLI - This is information that describes the available target features we
559 // need for lowering. This indicates when operations are unavailable,
560 // implemented with a libcall, etc.
561 TargetLowering &TLI;
562 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000563 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000564 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000565
Nate Begemanf15485a2006-03-27 01:32:24 +0000566 /// SwitchCases - Vector of CaseBlock structures used to communicate
567 /// SwitchInst code generation information.
568 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000569 /// JTCases - Vector of JumpTable structures used to communicate
570 /// SwitchInst code generation information.
571 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000572 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000573
Chris Lattner1c08c712005-01-07 07:47:53 +0000574 /// FuncInfo - Information about the function as a whole.
575 ///
576 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000577
578 /// GCI - Garbage collection metadata for the function.
579 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000580
581 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000582 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000583 FunctionLoweringInfo &funcinfo,
584 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000585 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000586 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000587 }
588
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000589 /// getRoot - Return the current virtual root of the Selection DAG,
590 /// flushing any PendingLoad items. This must be done before emitting
591 /// a store or any other node that may need to be ordered after any
592 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000593 ///
594 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000595 if (PendingLoads.empty())
596 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000597
Chris Lattnerd3948112005-01-17 22:19:26 +0000598 if (PendingLoads.size() == 1) {
599 SDOperand Root = PendingLoads[0];
600 DAG.setRoot(Root);
601 PendingLoads.clear();
602 return Root;
603 }
604
605 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000606 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
607 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000608 PendingLoads.clear();
609 DAG.setRoot(Root);
610 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000611 }
612
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000613 /// getControlRoot - Similar to getRoot, but instead of flushing all the
614 /// PendingLoad items, flush all the PendingExports items. It is necessary
615 /// to do this before emitting a terminator instruction.
616 ///
617 SDOperand getControlRoot() {
618 SDOperand Root = DAG.getRoot();
619
620 if (PendingExports.empty())
621 return Root;
622
623 // Turn all of the CopyToReg chains into one factored node.
624 if (Root.getOpcode() != ISD::EntryToken) {
625 unsigned i = 0, e = PendingExports.size();
626 for (; i != e; ++i) {
627 assert(PendingExports[i].Val->getNumOperands() > 1);
628 if (PendingExports[i].Val->getOperand(0) == Root)
629 break; // Don't add the root if we already indirectly depend on it.
630 }
631
632 if (i == e)
633 PendingExports.push_back(Root);
634 }
635
636 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
637 &PendingExports[0],
638 PendingExports.size());
639 PendingExports.clear();
640 DAG.setRoot(Root);
641 return Root;
642 }
643
644 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000645
Chris Lattner1c08c712005-01-07 07:47:53 +0000646 void visit(Instruction &I) { visit(I.getOpcode(), I); }
647
648 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000649 // Note: this doesn't use InstVisitor, because it has to work with
650 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000651 switch (Opcode) {
652 default: assert(0 && "Unknown instruction type encountered!");
653 abort();
654 // Build the switch statement using the Instruction.def file.
655#define HANDLE_INST(NUM, OPCODE, CLASS) \
656 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
657#include "llvm/Instruction.def"
658 }
659 }
660
661 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
662
Chris Lattner199862b2006-03-16 19:57:50 +0000663 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000664
Chris Lattner0da331f2007-02-04 01:31:47 +0000665 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000666 SDOperand &N = NodeMap[V];
667 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000668 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000669 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000670
Evan Cheng5c807602008-02-26 02:33:44 +0000671 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000672 std::set<unsigned> &OutputRegs,
673 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000674
Chris Lattner571e4342006-10-27 21:36:01 +0000675 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
676 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
677 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000678 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000679 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000680 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000681 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000682
Chris Lattner1c08c712005-01-07 07:47:53 +0000683 // Terminator instructions.
684 void visitRet(ReturnInst &I);
685 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000686 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000687 void visitUnreachable(UnreachableInst &I) { /* noop */ }
688
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000689 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000690 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000691 CaseRecVector& WorkList,
692 Value* SV,
693 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000694 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000695 CaseRecVector& WorkList,
696 Value* SV,
697 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000698 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000699 CaseRecVector& WorkList,
700 Value* SV,
701 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000702 bool handleBitTestsSwitchCase(CaseRec& CR,
703 CaseRecVector& WorkList,
704 Value* SV,
705 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000706 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000707 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
708 void visitBitTestCase(MachineBasicBlock* NextMBB,
709 unsigned Reg,
710 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000711 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000712 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
713 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000714
Chris Lattner1c08c712005-01-07 07:47:53 +0000715 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000716 void visitInvoke(InvokeInst &I);
717 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000718
Dan Gohman7f321562007-06-25 16:23:39 +0000719 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000720 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000721 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000722 if (I.getType()->isFPOrFPVector())
723 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000724 else
Dan Gohman7f321562007-06-25 16:23:39 +0000725 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000726 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000727 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000728 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000729 if (I.getType()->isFPOrFPVector())
730 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000731 else
Dan Gohman7f321562007-06-25 16:23:39 +0000732 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000733 }
Dan Gohman7f321562007-06-25 16:23:39 +0000734 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
735 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
736 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
737 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
738 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
739 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
740 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
741 void visitOr (User &I) { visitBinary(I, ISD::OR); }
742 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000743 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000744 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
745 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000746 void visitICmp(User &I);
747 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000748 void visitVICmp(User &I);
749 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000750 // Visit the conversion instructions
751 void visitTrunc(User &I);
752 void visitZExt(User &I);
753 void visitSExt(User &I);
754 void visitFPTrunc(User &I);
755 void visitFPExt(User &I);
756 void visitFPToUI(User &I);
757 void visitFPToSI(User &I);
758 void visitUIToFP(User &I);
759 void visitSIToFP(User &I);
760 void visitPtrToInt(User &I);
761 void visitIntToPtr(User &I);
762 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000763
Chris Lattner2bbd8102006-03-29 00:11:43 +0000764 void visitExtractElement(User &I);
765 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000766 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000767
Dan Gohman1d685a42008-06-07 02:02:36 +0000768 void visitExtractValue(ExtractValueInst &I);
769 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000770
Chris Lattner1c08c712005-01-07 07:47:53 +0000771 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000772 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000773
774 void visitMalloc(MallocInst &I);
775 void visitFree(FreeInst &I);
776 void visitAlloca(AllocaInst &I);
777 void visitLoad(LoadInst &I);
778 void visitStore(StoreInst &I);
779 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
780 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000781 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000782 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000783 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000784
Chris Lattner1c08c712005-01-07 07:47:53 +0000785 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000786 void visitVAArg(VAArgInst &I);
787 void visitVAEnd(CallInst &I);
788 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000789
Dan Gohmanef5d1942008-03-11 21:11:25 +0000790 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000791
Chris Lattner1c08c712005-01-07 07:47:53 +0000792 void visitUserOp1(Instruction &I) {
793 assert(0 && "UserOp1 should not exist at instruction selection time!");
794 abort();
795 }
796 void visitUserOp2(Instruction &I) {
797 assert(0 && "UserOp2 should not exist at instruction selection time!");
798 abort();
799 }
Mon P Wang63307c32008-05-05 19:05:59 +0000800
801private:
802 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
803
Chris Lattner1c08c712005-01-07 07:47:53 +0000804};
805} // end namespace llvm
806
Dan Gohman6183f782007-07-05 20:12:34 +0000807
Duncan Sandsb988bac2008-02-11 20:58:28 +0000808/// getCopyFromParts - Create a value that contains the specified legal parts
809/// combined into the value they represent. If the parts combine to a type
810/// larger then ValueVT then AssertOp can be used to specify whether the extra
811/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000812/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000813static SDOperand getCopyFromParts(SelectionDAG &DAG,
814 const SDOperand *Parts,
815 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000816 MVT PartVT,
817 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000818 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000819 assert(NumParts > 0 && "No parts to assemble!");
820 TargetLowering &TLI = DAG.getTargetLoweringInfo();
821 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000822
Duncan Sands014e04a2008-02-12 20:46:31 +0000823 if (NumParts > 1) {
824 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000825 if (!ValueVT.isVector()) {
826 unsigned PartBits = PartVT.getSizeInBits();
827 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000828
Duncan Sands014e04a2008-02-12 20:46:31 +0000829 // Assemble the power of 2 part.
830 unsigned RoundParts = NumParts & (NumParts - 1) ?
831 1 << Log2_32(NumParts) : NumParts;
832 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000833 MVT RoundVT = RoundBits == ValueBits ?
834 ValueVT : MVT::getIntegerVT(RoundBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000835 SDOperand Lo, Hi;
836
837 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000838 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000839 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
840 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
841 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000842 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000843 Lo = Parts[0];
844 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000845 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 if (TLI.isBigEndian())
847 std::swap(Lo, Hi);
848 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
849
850 if (RoundParts < NumParts) {
851 // Assemble the trailing non-power-of-2 part.
852 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000853 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000854 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
855
856 // Combine the round and odd parts.
857 Lo = Val;
858 if (TLI.isBigEndian())
859 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000860 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000861 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
862 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000863 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000864 TLI.getShiftAmountTy()));
865 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
866 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
867 }
868 } else {
869 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000870 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000871 unsigned NumIntermediates;
872 unsigned NumRegs =
873 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
874 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000875 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000876 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000877 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
878 assert(RegisterVT == Parts[0].getValueType() &&
879 "Part type doesn't match part!");
880
881 // Assemble the parts into intermediate operands.
882 SmallVector<SDOperand, 8> Ops(NumIntermediates);
883 if (NumIntermediates == NumParts) {
884 // If the register was not expanded, truncate or copy the value,
885 // as appropriate.
886 for (unsigned i = 0; i != NumParts; ++i)
887 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
888 PartVT, IntermediateVT);
889 } else if (NumParts > 0) {
890 // If the intermediate type was expanded, build the intermediate operands
891 // from the parts.
892 assert(NumParts % NumIntermediates == 0 &&
893 "Must expand into a divisible number of parts!");
894 unsigned Factor = NumParts / NumIntermediates;
895 for (unsigned i = 0; i != NumIntermediates; ++i)
896 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
897 PartVT, IntermediateVT);
898 }
899
900 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
901 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000902 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000903 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
904 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000905 }
Dan Gohman6183f782007-07-05 20:12:34 +0000906 }
907
Duncan Sands014e04a2008-02-12 20:46:31 +0000908 // There is now one part, held in Val. Correct it to match ValueVT.
909 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000910
Duncan Sands014e04a2008-02-12 20:46:31 +0000911 if (PartVT == ValueVT)
912 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000913
Duncan Sands83ec4b62008-06-06 12:08:01 +0000914 if (PartVT.isVector()) {
915 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000916 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000917 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000918
Duncan Sands83ec4b62008-06-06 12:08:01 +0000919 if (ValueVT.isVector()) {
920 assert(ValueVT.getVectorElementType() == PartVT &&
921 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000922 "Only trivial scalar-to-vector conversions should get here!");
923 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
924 }
925
Duncan Sands83ec4b62008-06-06 12:08:01 +0000926 if (PartVT.isInteger() &&
927 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000928 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000929 // For a truncate, see if we have any information to
930 // indicate whether the truncated bits will always be
931 // zero or sign-extension.
932 if (AssertOp != ISD::DELETED_NODE)
933 Val = DAG.getNode(AssertOp, PartVT, Val,
934 DAG.getValueType(ValueVT));
935 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
936 } else {
937 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
938 }
939 }
940
Duncan Sands83ec4b62008-06-06 12:08:01 +0000941 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000942 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000943 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000944 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000945 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000946 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
947 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000948
Duncan Sands83ec4b62008-06-06 12:08:01 +0000949 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000950 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
951
952 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000953 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000954}
955
Duncan Sandsb988bac2008-02-11 20:58:28 +0000956/// getCopyToParts - Create a series of nodes that contain the specified value
957/// split into legal parts. If the parts contain more bits than Val, then, for
958/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000959static void getCopyToParts(SelectionDAG &DAG,
960 SDOperand Val,
961 SDOperand *Parts,
962 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000963 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000964 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000965 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000966 MVT PtrVT = TLI.getPointerTy();
967 MVT ValueVT = Val.getValueType();
968 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +0000969 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000970
Duncan Sands014e04a2008-02-12 20:46:31 +0000971 if (!NumParts)
972 return;
973
Duncan Sands83ec4b62008-06-06 12:08:01 +0000974 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000975 if (PartVT == ValueVT) {
976 assert(NumParts == 1 && "No-op copy with multiple parts!");
977 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000978 return;
979 }
980
Duncan Sands83ec4b62008-06-06 12:08:01 +0000981 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000982 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000983 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000984 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000985 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000986 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
987 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000988 Val = DAG.getNode(ExtendKind, ValueVT, Val);
989 } else {
990 assert(0 && "Unknown mismatch!");
991 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000992 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000993 // Different types of the same size.
994 assert(NumParts == 1 && PartVT != ValueVT);
995 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000996 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000997 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000998 if (PartVT.isInteger() && ValueVT.isInteger()) {
999 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001000 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001001 } else {
1002 assert(0 && "Unknown mismatch!");
1003 }
1004 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001005
1006 // The value may have changed - recompute ValueVT.
1007 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001008 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001009 "Failed to tile the value with PartVT!");
1010
1011 if (NumParts == 1) {
1012 assert(PartVT == ValueVT && "Type conversion failed!");
1013 Parts[0] = Val;
1014 return;
1015 }
1016
1017 // Expand the value into multiple parts.
1018 if (NumParts & (NumParts - 1)) {
1019 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001020 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001021 "Do not know what to expand to!");
1022 unsigned RoundParts = 1 << Log2_32(NumParts);
1023 unsigned RoundBits = RoundParts * PartBits;
1024 unsigned OddParts = NumParts - RoundParts;
1025 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1026 DAG.getConstant(RoundBits,
1027 TLI.getShiftAmountTy()));
1028 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1029 if (TLI.isBigEndian())
1030 // The odd parts were reversed by getCopyToParts - unreverse them.
1031 std::reverse(Parts + RoundParts, Parts + NumParts);
1032 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001033 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001034 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1035 }
1036
1037 // The number of parts is a power of 2. Repeatedly bisect the value using
1038 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001039 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001040 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001041 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001042 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1043 for (unsigned i = 0; i < NumParts; i += StepSize) {
1044 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001045 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Duncan Sands25eb0432008-03-12 20:30:08 +00001046 SDOperand &Part0 = Parts[i];
1047 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001048
Duncan Sands25eb0432008-03-12 20:30:08 +00001049 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1050 DAG.getConstant(1, PtrVT));
1051 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1052 DAG.getConstant(0, PtrVT));
1053
1054 if (ThisBits == PartBits && ThisVT != PartVT) {
1055 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1056 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1057 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001058 }
1059 }
1060
1061 if (TLI.isBigEndian())
1062 std::reverse(Parts, Parts + NumParts);
1063
1064 return;
1065 }
1066
1067 // Vector ValueVT.
1068 if (NumParts == 1) {
1069 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001070 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001071 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1072 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001073 assert(ValueVT.getVectorElementType() == PartVT &&
1074 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001075 "Only trivial vector-to-scalar conversions should get here!");
1076 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1077 DAG.getConstant(0, PtrVT));
1078 }
1079 }
1080
Dan Gohman6183f782007-07-05 20:12:34 +00001081 Parts[0] = Val;
1082 return;
1083 }
1084
1085 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001086 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001087 unsigned NumIntermediates;
1088 unsigned NumRegs =
1089 DAG.getTargetLoweringInfo()
1090 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1091 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001092 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001093
1094 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001095 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001096 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1097
1098 // Split the vector into intermediate operands.
1099 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1100 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001101 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001102 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1103 IntermediateVT, Val,
1104 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001105 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001106 else
1107 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1108 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001109 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001110
1111 // Split the intermediate operands into legal parts.
1112 if (NumParts == NumIntermediates) {
1113 // If the register was not expanded, promote or copy the value,
1114 // as appropriate.
1115 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001116 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001117 } else if (NumParts > 0) {
1118 // If the intermediate type was expanded, split each the value into
1119 // legal parts.
1120 assert(NumParts % NumIntermediates == 0 &&
1121 "Must expand into a divisible number of parts!");
1122 unsigned Factor = NumParts / NumIntermediates;
1123 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001124 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001125 }
1126}
1127
1128
Chris Lattner199862b2006-03-16 19:57:50 +00001129SDOperand SelectionDAGLowering::getValue(const Value *V) {
1130 SDOperand &N = NodeMap[V];
1131 if (N.Val) return N;
1132
Chris Lattner199862b2006-03-16 19:57:50 +00001133 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001134 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001135
1136 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1137 return N = DAG.getConstant(CI->getValue(), VT);
1138
1139 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001140 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001141
1142 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001143 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001144
1145 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1146 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1147
Dan Gohman1d685a42008-06-07 02:02:36 +00001148 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1149 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001150 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001151
1152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1153 visit(CE->getOpcode(), *CE);
1154 SDOperand N1 = NodeMap[V];
1155 assert(N1.Val && "visit didn't populate the ValueMap!");
1156 return N1;
1157 }
1158
Dan Gohman1d685a42008-06-07 02:02:36 +00001159 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1160 SmallVector<SDOperand, 4> Constants;
1161 SmallVector<MVT, 4> ValueVTs;
1162 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1163 OI != OE; ++OI) {
1164 SDNode *Val = getValue(*OI).Val;
1165 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1166 Constants.push_back(SDOperand(Val, i));
1167 ValueVTs.push_back(Val->getValueType(i));
1168 }
1169 }
Duncan Sandsf9516202008-06-30 10:19:09 +00001170 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1171 &Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001172 }
1173
1174 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1175 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1176 "Unknown array constant!");
1177 unsigned NumElts = ATy->getNumElements();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001178 if (NumElts == 0)
1179 return SDOperand(); // empty array
Dan Gohman1d685a42008-06-07 02:02:36 +00001180 MVT EltVT = TLI.getValueType(ATy->getElementType());
1181 SmallVector<SDOperand, 4> Constants(NumElts);
1182 SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1183 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1184 if (isa<UndefValue>(C))
1185 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1186 else if (EltVT.isFloatingPoint())
1187 Constants[i] = DAG.getConstantFP(0, EltVT);
1188 else
1189 Constants[i] = DAG.getConstant(0, EltVT);
1190 }
Duncan Sandsf9516202008-06-30 10:19:09 +00001191 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1192 &Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001193 }
1194
1195 if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1196 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1197 "Unknown struct constant!");
1198 unsigned NumElts = STy->getNumElements();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001199 if (NumElts == 0)
1200 return SDOperand(); // empty struct
Dan Gohman1d685a42008-06-07 02:02:36 +00001201 SmallVector<SDOperand, 4> Constants(NumElts);
1202 SmallVector<MVT, 4> ValueVTs(NumElts);
1203 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1204 MVT EltVT = TLI.getValueType(STy->getElementType(i));
1205 ValueVTs[i] = EltVT;
1206 if (isa<UndefValue>(C))
1207 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1208 else if (EltVT.isFloatingPoint())
1209 Constants[i] = DAG.getConstantFP(0, EltVT);
1210 else
1211 Constants[i] = DAG.getConstant(0, EltVT);
1212 }
Duncan Sandsf9516202008-06-30 10:19:09 +00001213 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1214 &Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001215 }
1216
Chris Lattner6833b062008-04-28 07:16:35 +00001217 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001218 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001219
Chris Lattner6833b062008-04-28 07:16:35 +00001220 // Now that we know the number and type of the elements, get that number of
1221 // elements into the Ops array based on what kind of constant it is.
1222 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001223 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1224 for (unsigned i = 0; i != NumElements; ++i)
1225 Ops.push_back(getValue(CP->getOperand(i)));
1226 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001227 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1228 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001229 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001230
Chris Lattnerb606dba2008-04-28 06:44:42 +00001231 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001232 if (isa<UndefValue>(C))
1233 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001234 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001235 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001236 else
Chris Lattner6833b062008-04-28 07:16:35 +00001237 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001238 Ops.assign(NumElements, Op);
1239 }
1240
1241 // Create a BUILD_VECTOR node.
1242 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001243 }
1244
Chris Lattnerb606dba2008-04-28 06:44:42 +00001245 // If this is a static alloca, generate it as the frameindex instead of
1246 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001247 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1248 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001249 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001250 if (SI != FuncInfo.StaticAllocaMap.end())
1251 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1252 }
1253
Chris Lattner251db182007-02-25 18:40:32 +00001254 unsigned InReg = FuncInfo.ValueMap[V];
1255 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001256
Chris Lattner6833b062008-04-28 07:16:35 +00001257 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001258 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001259 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001260}
1261
1262
Chris Lattner1c08c712005-01-07 07:47:53 +00001263void SelectionDAGLowering::visitRet(ReturnInst &I) {
1264 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001265 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001266 return;
1267 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001268
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001269 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001270 NewValues.push_back(getControlRoot());
1271 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001272 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001273
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001274 SmallVector<MVT, 4> ValueVTs;
1275 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1276 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1277 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001278
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001279 // FIXME: C calling convention requires the return type to be promoted to
1280 // at least 32-bit. But this is not necessary for non-C calling conventions.
1281 if (VT.isInteger()) {
1282 MVT MinVT = TLI.getRegisterType(MVT::i32);
1283 if (VT.bitsLT(MinVT))
1284 VT = MinVT;
1285 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001286
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001287 unsigned NumParts = TLI.getNumRegisters(VT);
1288 MVT PartVT = TLI.getRegisterType(VT);
1289 SmallVector<SDOperand, 4> Parts(NumParts);
1290 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1291
1292 const Function *F = I.getParent()->getParent();
1293 if (F->paramHasAttr(0, ParamAttr::SExt))
1294 ExtendKind = ISD::SIGN_EXTEND;
1295 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1296 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001297
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001298 getCopyToParts(DAG, SDOperand(RetOp.Val, RetOp.ResNo + j),
1299 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001300
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001301 for (unsigned i = 0; i < NumParts; ++i) {
1302 NewValues.push_back(Parts[i]);
1303 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1304 }
Nate Begemanee625572006-01-27 21:09:22 +00001305 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001306 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001307 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1308 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001309}
1310
Chris Lattner571e4342006-10-27 21:36:01 +00001311/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1312/// the current basic block, add it to ValueMap now so that we'll get a
1313/// CopyTo/FromReg.
1314void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1315 // No need to export constants.
1316 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1317
1318 // Already exported?
1319 if (FuncInfo.isExportedInst(V)) return;
1320
1321 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001322 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001323}
1324
Chris Lattner8c494ab2006-10-27 23:50:33 +00001325bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1326 const BasicBlock *FromBB) {
1327 // The operands of the setcc have to be in this block. We don't know
1328 // how to export them from some other block.
1329 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1330 // Can export from current BB.
1331 if (VI->getParent() == FromBB)
1332 return true;
1333
1334 // Is already exported, noop.
1335 return FuncInfo.isExportedInst(V);
1336 }
1337
1338 // If this is an argument, we can export it if the BB is the entry block or
1339 // if it is already exported.
1340 if (isa<Argument>(V)) {
1341 if (FromBB == &FromBB->getParent()->getEntryBlock())
1342 return true;
1343
1344 // Otherwise, can only export this if it is already exported.
1345 return FuncInfo.isExportedInst(V);
1346 }
1347
1348 // Otherwise, constants can always be exported.
1349 return true;
1350}
1351
Chris Lattner6a586c82006-10-29 21:01:20 +00001352static bool InBlock(const Value *V, const BasicBlock *BB) {
1353 if (const Instruction *I = dyn_cast<Instruction>(V))
1354 return I->getParent() == BB;
1355 return true;
1356}
1357
Chris Lattner571e4342006-10-27 21:36:01 +00001358/// FindMergedConditions - If Cond is an expression like
1359void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1360 MachineBasicBlock *TBB,
1361 MachineBasicBlock *FBB,
1362 MachineBasicBlock *CurBB,
1363 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001364 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001365 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001366
Reid Spencere4d87aa2006-12-23 06:05:41 +00001367 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1368 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001369 BOp->getParent() != CurBB->getBasicBlock() ||
1370 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1371 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001372 const BasicBlock *BB = CurBB->getBasicBlock();
1373
Reid Spencere4d87aa2006-12-23 06:05:41 +00001374 // If the leaf of the tree is a comparison, merge the condition into
1375 // the caseblock.
1376 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1377 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001378 // how to export them from some other block. If this is the first block
1379 // of the sequence, no exporting is needed.
1380 (CurBB == CurMBB ||
1381 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1382 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001383 BOp = cast<Instruction>(Cond);
1384 ISD::CondCode Condition;
1385 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1386 switch (IC->getPredicate()) {
1387 default: assert(0 && "Unknown icmp predicate opcode!");
1388 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1389 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1390 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1391 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1392 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1393 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1394 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1395 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1396 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1397 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1398 }
1399 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1400 ISD::CondCode FPC, FOC;
1401 switch (FC->getPredicate()) {
1402 default: assert(0 && "Unknown fcmp predicate opcode!");
1403 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1404 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1405 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1406 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1407 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1408 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1409 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001410 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1411 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001412 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1413 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1414 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1415 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1416 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1417 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1418 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1419 }
1420 if (FiniteOnlyFPMath())
1421 Condition = FOC;
1422 else
1423 Condition = FPC;
1424 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001425 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001426 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001427 }
1428
Chris Lattner571e4342006-10-27 21:36:01 +00001429 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001430 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001431 SwitchCases.push_back(CB);
1432 return;
1433 }
1434
1435 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001436 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001437 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001438 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001439 return;
1440 }
1441
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001442
1443 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001444 MachineFunction::iterator BBI = CurBB;
1445 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1446 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1447
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001448 if (Opc == Instruction::Or) {
1449 // Codegen X | Y as:
1450 // jmp_if_X TBB
1451 // jmp TmpBB
1452 // TmpBB:
1453 // jmp_if_Y TBB
1454 // jmp FBB
1455 //
Chris Lattner571e4342006-10-27 21:36:01 +00001456
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001457 // Emit the LHS condition.
1458 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1459
1460 // Emit the RHS condition into TmpBB.
1461 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1462 } else {
1463 assert(Opc == Instruction::And && "Unknown merge op!");
1464 // Codegen X & Y as:
1465 // jmp_if_X TmpBB
1466 // jmp FBB
1467 // TmpBB:
1468 // jmp_if_Y TBB
1469 // jmp FBB
1470 //
1471 // This requires creation of TmpBB after CurBB.
1472
1473 // Emit the LHS condition.
1474 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1475
1476 // Emit the RHS condition into TmpBB.
1477 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1478 }
Chris Lattner571e4342006-10-27 21:36:01 +00001479}
1480
Chris Lattnerdf19f272006-10-31 22:37:42 +00001481/// If the set of cases should be emitted as a series of branches, return true.
1482/// If we should emit this as a bunch of and/or'd together conditions, return
1483/// false.
1484static bool
1485ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1486 if (Cases.size() != 2) return true;
1487
Chris Lattner0ccb5002006-10-31 23:06:00 +00001488 // If this is two comparisons of the same values or'd or and'd together, they
1489 // will get folded into a single comparison, so don't emit two blocks.
1490 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1491 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1492 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1493 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1494 return false;
1495 }
1496
Chris Lattnerdf19f272006-10-31 22:37:42 +00001497 return true;
1498}
1499
Chris Lattner1c08c712005-01-07 07:47:53 +00001500void SelectionDAGLowering::visitBr(BranchInst &I) {
1501 // Update machine-CFG edges.
1502 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001503
1504 // Figure out which block is immediately after the current one.
1505 MachineBasicBlock *NextBlock = 0;
1506 MachineFunction::iterator BBI = CurMBB;
1507 if (++BBI != CurMBB->getParent()->end())
1508 NextBlock = BBI;
1509
1510 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001511 // Update machine-CFG edges.
1512 CurMBB->addSuccessor(Succ0MBB);
1513
Chris Lattner1c08c712005-01-07 07:47:53 +00001514 // If this is not a fall-through branch, emit the branch.
1515 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001516 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001517 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001518 return;
1519 }
1520
1521 // If this condition is one of the special cases we handle, do special stuff
1522 // now.
1523 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001524 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001525
1526 // If this is a series of conditions that are or'd or and'd together, emit
1527 // this as a sequence of branches instead of setcc's with and/or operations.
1528 // For example, instead of something like:
1529 // cmp A, B
1530 // C = seteq
1531 // cmp D, E
1532 // F = setle
1533 // or C, F
1534 // jnz foo
1535 // Emit:
1536 // cmp A, B
1537 // je foo
1538 // cmp D, E
1539 // jle foo
1540 //
1541 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1542 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001543 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001544 BOp->getOpcode() == Instruction::Or)) {
1545 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001546 // If the compares in later blocks need to use values not currently
1547 // exported from this block, export them now. This block should always
1548 // be the first entry.
1549 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1550
Chris Lattnerdf19f272006-10-31 22:37:42 +00001551 // Allow some cases to be rejected.
1552 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001553 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1554 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1555 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1556 }
1557
1558 // Emit the branch for this block.
1559 visitSwitchCase(SwitchCases[0]);
1560 SwitchCases.erase(SwitchCases.begin());
1561 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001562 }
1563
Chris Lattner0ccb5002006-10-31 23:06:00 +00001564 // Okay, we decided not to do this, remove any inserted MBB's and clear
1565 // SwitchCases.
1566 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1567 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1568
Chris Lattnerdf19f272006-10-31 22:37:42 +00001569 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001570 }
1571 }
Chris Lattner24525952006-10-24 18:07:37 +00001572
1573 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001574 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001575 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001576 // Use visitSwitchCase to actually insert the fast branch sequence for this
1577 // cond branch.
1578 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001579}
1580
Nate Begemanf15485a2006-03-27 01:32:24 +00001581/// visitSwitchCase - Emits the necessary code to represent a single node in
1582/// the binary search tree resulting from lowering a switch instruction.
1583void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001584 SDOperand Cond;
1585 SDOperand CondLHS = getValue(CB.CmpLHS);
1586
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001587 // Build the setcc now.
1588 if (CB.CmpMHS == NULL) {
1589 // Fold "(X == true)" to X and "(X == false)" to !X to
1590 // handle common cases produced by branch lowering.
1591 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1592 Cond = CondLHS;
1593 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1594 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1595 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1596 } else
1597 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1598 } else {
1599 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001600
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001601 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1602 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1603
1604 SDOperand CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001605 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001606
1607 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1608 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1609 } else {
1610 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1611 Cond = DAG.getSetCC(MVT::i1, SUB,
1612 DAG.getConstant(High-Low, VT), ISD::SETULE);
1613 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001614 }
1615
Owen Anderson2d389e82008-06-07 00:00:23 +00001616 // Update successor info
1617 CurMBB->addSuccessor(CB.TrueBB);
1618 CurMBB->addSuccessor(CB.FalseBB);
1619
Nate Begemanf15485a2006-03-27 01:32:24 +00001620 // Set NextBlock to be the MBB immediately after the current one, if any.
1621 // This is used to avoid emitting unnecessary branches to the next block.
1622 MachineBasicBlock *NextBlock = 0;
1623 MachineFunction::iterator BBI = CurMBB;
1624 if (++BBI != CurMBB->getParent()->end())
1625 NextBlock = BBI;
1626
1627 // If the lhs block is the next block, invert the condition so that we can
1628 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001629 if (CB.TrueBB == NextBlock) {
1630 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001631 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1632 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1633 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001634 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001635 DAG.getBasicBlock(CB.TrueBB));
1636 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001637 DAG.setRoot(BrCond);
1638 else
1639 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001640 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001641}
1642
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001643/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001644void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001645 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001646 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001647 MVT PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001648 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001649 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1650 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1651 Table, Index));
1652 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001653}
1654
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001655/// visitJumpTableHeader - This function emits necessary code to produce index
1656/// in the JumpTable from switch case.
1657void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1658 SelectionDAGISel::JumpTableHeader &JTH) {
1659 // Subtract the lowest switch case value from the value being switched on
1660 // and conditional branch to default mbb if the result is greater than the
1661 // difference between smallest and largest cases.
1662 SDOperand SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001663 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001664 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1665 DAG.getConstant(JTH.First, VT));
1666
1667 // The SDNode we just created, which holds the value being switched on
1668 // minus the the smallest case value, needs to be copied to a virtual
1669 // register so it can be used as an index into the jump table in a
1670 // subsequent basic block. This value may be smaller or larger than the
1671 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001672 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001673 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1674 else
1675 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1676
1677 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001678 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001679 JT.Reg = JumpTableReg;
1680
1681 // Emit the range check for the jump table, and branch to the default
1682 // block for the switch statement if the value being switched on exceeds
1683 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001684 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001685 DAG.getConstant(JTH.Last-JTH.First,VT),
1686 ISD::SETUGT);
1687
1688 // Set NextBlock to be the MBB immediately after the current one, if any.
1689 // This is used to avoid emitting unnecessary branches to the next block.
1690 MachineBasicBlock *NextBlock = 0;
1691 MachineFunction::iterator BBI = CurMBB;
1692 if (++BBI != CurMBB->getParent()->end())
1693 NextBlock = BBI;
1694
1695 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1696 DAG.getBasicBlock(JT.Default));
1697
1698 if (JT.MBB == NextBlock)
1699 DAG.setRoot(BrCond);
1700 else
1701 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001702 DAG.getBasicBlock(JT.MBB)));
1703
1704 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001705}
1706
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001707/// visitBitTestHeader - This function emits necessary code to produce value
1708/// suitable for "bit tests"
1709void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1710 // Subtract the minimum value
1711 SDOperand SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001712 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001713 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1714 DAG.getConstant(B.First, VT));
1715
1716 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001717 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001718 DAG.getConstant(B.Range, VT),
1719 ISD::SETUGT);
1720
1721 SDOperand ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001722 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001723 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1724 else
1725 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1726
1727 // Make desired shift
1728 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1729 DAG.getConstant(1, TLI.getPointerTy()),
1730 ShiftOp);
1731
1732 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001733 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001734 B.Reg = SwitchReg;
1735
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001736 // Set NextBlock to be the MBB immediately after the current one, if any.
1737 // This is used to avoid emitting unnecessary branches to the next block.
1738 MachineBasicBlock *NextBlock = 0;
1739 MachineFunction::iterator BBI = CurMBB;
1740 if (++BBI != CurMBB->getParent()->end())
1741 NextBlock = BBI;
1742
1743 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001744
1745 CurMBB->addSuccessor(B.Default);
1746 CurMBB->addSuccessor(MBB);
1747
1748 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1749 DAG.getBasicBlock(B.Default));
1750
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001751 if (MBB == NextBlock)
1752 DAG.setRoot(BrRange);
1753 else
1754 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1755 DAG.getBasicBlock(MBB)));
1756
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001757 return;
1758}
1759
1760/// visitBitTestCase - this function produces one "bit test"
1761void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1762 unsigned Reg,
1763 SelectionDAGISel::BitTestCase &B) {
1764 // Emit bit tests and jumps
Chris Lattneread0d882008-06-17 06:09:18 +00001765 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1766 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001767
Chris Lattneread0d882008-06-17 06:09:18 +00001768 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1769 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001770 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001771 DAG.getConstant(0, TLI.getPointerTy()),
1772 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001773
1774 CurMBB->addSuccessor(B.TargetBB);
1775 CurMBB->addSuccessor(NextMBB);
1776
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001777 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001778 AndCmp, DAG.getBasicBlock(B.TargetBB));
1779
1780 // Set NextBlock to be the MBB immediately after the current one, if any.
1781 // This is used to avoid emitting unnecessary branches to the next block.
1782 MachineBasicBlock *NextBlock = 0;
1783 MachineFunction::iterator BBI = CurMBB;
1784 if (++BBI != CurMBB->getParent()->end())
1785 NextBlock = BBI;
1786
1787 if (NextMBB == NextBlock)
1788 DAG.setRoot(BrAnd);
1789 else
1790 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1791 DAG.getBasicBlock(NextMBB)));
1792
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001793 return;
1794}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001795
Jim Laskeyb180aa12007-02-21 22:53:45 +00001796void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1797 // Retrieve successors.
1798 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001799 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001800
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001801 if (isa<InlineAsm>(I.getCalledValue()))
1802 visitInlineAsm(&I);
1803 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001804 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001805
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001806 // If the value of the invoke is used outside of its defining block, make it
1807 // available as a virtual register.
1808 if (!I.use_empty()) {
1809 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1810 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001811 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001812 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001813
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001814 // Update successor info
1815 CurMBB->addSuccessor(Return);
1816 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001817
1818 // Drop into normal successor.
1819 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1820 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001821}
1822
1823void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1824}
1825
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001826/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001827/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001828bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001829 CaseRecVector& WorkList,
1830 Value* SV,
1831 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001832 Case& BackCase = *(CR.Range.second-1);
1833
1834 // Size is the number of Cases represented by this range.
1835 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001836 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001837 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001838
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001839 // Get the MachineFunction which holds the current MBB. This is used when
1840 // inserting any additional MBBs necessary to represent the switch.
1841 MachineFunction *CurMF = CurMBB->getParent();
1842
1843 // Figure out which block is immediately after the current one.
1844 MachineBasicBlock *NextBlock = 0;
1845 MachineFunction::iterator BBI = CR.CaseBB;
1846
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001847 if (++BBI != CurMBB->getParent()->end())
1848 NextBlock = BBI;
1849
1850 // TODO: If any two of the cases has the same destination, and if one value
1851 // is the same as the other, but has one bit unset that the other has set,
1852 // use bit manipulation to do two compares at once. For example:
1853 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1854
1855 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001856 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001857 // The last case block won't fall through into 'NextBlock' if we emit the
1858 // branches in this order. See if rearranging a case value would help.
1859 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001860 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001861 std::swap(*I, BackCase);
1862 break;
1863 }
1864 }
1865 }
1866
1867 // Create a CaseBlock record representing a conditional branch to
1868 // the Case's target mbb if the value being switched on SV is equal
1869 // to C.
1870 MachineBasicBlock *CurBlock = CR.CaseBB;
1871 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1872 MachineBasicBlock *FallThrough;
1873 if (I != E-1) {
1874 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1875 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1876 } else {
1877 // If the last case doesn't match, go to the default block.
1878 FallThrough = Default;
1879 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001880
1881 Value *RHS, *LHS, *MHS;
1882 ISD::CondCode CC;
1883 if (I->High == I->Low) {
1884 // This is just small small case range :) containing exactly 1 case
1885 CC = ISD::SETEQ;
1886 LHS = SV; RHS = I->High; MHS = NULL;
1887 } else {
1888 CC = ISD::SETLE;
1889 LHS = I->Low; MHS = SV; RHS = I->High;
1890 }
1891 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1892 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001893
1894 // If emitting the first comparison, just call visitSwitchCase to emit the
1895 // code into the current block. Otherwise, push the CaseBlock onto the
1896 // vector to be later processed by SDISel, and insert the node's MBB
1897 // before the next MBB.
1898 if (CurBlock == CurMBB)
1899 visitSwitchCase(CB);
1900 else
1901 SwitchCases.push_back(CB);
1902
1903 CurBlock = FallThrough;
1904 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001905
1906 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001907}
1908
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001909static inline bool areJTsAllowed(const TargetLowering &TLI) {
1910 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1911 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1912}
1913
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001914/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001915bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001916 CaseRecVector& WorkList,
1917 Value* SV,
1918 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001919 Case& FrontCase = *CR.Range.first;
1920 Case& BackCase = *(CR.Range.second-1);
1921
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001922 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1923 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1924
1925 uint64_t TSize = 0;
1926 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1927 I!=E; ++I)
1928 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001929
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001930 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001931 return false;
1932
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001933 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1934 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001935 return false;
1936
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001937 DOUT << "Lowering jump table\n"
1938 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001939 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001940
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001941 // Get the MachineFunction which holds the current MBB. This is used when
1942 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001943 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001944
1945 // Figure out which block is immediately after the current one.
1946 MachineBasicBlock *NextBlock = 0;
1947 MachineFunction::iterator BBI = CR.CaseBB;
1948
1949 if (++BBI != CurMBB->getParent()->end())
1950 NextBlock = BBI;
1951
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001952 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1953
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001954 // Create a new basic block to hold the code for loading the address
1955 // of the jump table, and jumping to it. Update successor information;
1956 // we will either branch to the default case for the switch, or the jump
1957 // table.
1958 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1959 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1960 CR.CaseBB->addSuccessor(Default);
1961 CR.CaseBB->addSuccessor(JumpTableBB);
1962
1963 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001964 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001965 // a case statement, push the case's BB onto the vector, otherwise, push
1966 // the default BB.
1967 std::vector<MachineBasicBlock*> DestBBs;
1968 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001969 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1970 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1971 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1972
1973 if ((Low <= TEI) && (TEI <= High)) {
1974 DestBBs.push_back(I->BB);
1975 if (TEI==High)
1976 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001977 } else {
1978 DestBBs.push_back(Default);
1979 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001980 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001981
1982 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001983 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001984 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1985 E = DestBBs.end(); I != E; ++I) {
1986 if (!SuccsHandled[(*I)->getNumber()]) {
1987 SuccsHandled[(*I)->getNumber()] = true;
1988 JumpTableBB->addSuccessor(*I);
1989 }
1990 }
1991
1992 // Create a jump table index for this jump table, or return an existing
1993 // one.
1994 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1995
1996 // Set the jump table information so that we can codegen it as a second
1997 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001998 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001999 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2000 (CR.CaseBB == CurMBB));
2001 if (CR.CaseBB == CurMBB)
2002 visitJumpTableHeader(JT, JTH);
2003
2004 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002005
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002006 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002007}
2008
2009/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2010/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002011bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002012 CaseRecVector& WorkList,
2013 Value* SV,
2014 MachineBasicBlock* Default) {
2015 // Get the MachineFunction which holds the current MBB. This is used when
2016 // inserting any additional MBBs necessary to represent the switch.
2017 MachineFunction *CurMF = CurMBB->getParent();
2018
2019 // Figure out which block is immediately after the current one.
2020 MachineBasicBlock *NextBlock = 0;
2021 MachineFunction::iterator BBI = CR.CaseBB;
2022
2023 if (++BBI != CurMBB->getParent()->end())
2024 NextBlock = BBI;
2025
2026 Case& FrontCase = *CR.Range.first;
2027 Case& BackCase = *(CR.Range.second-1);
2028 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2029
2030 // Size is the number of Cases represented by this range.
2031 unsigned Size = CR.Range.second - CR.Range.first;
2032
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002033 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2034 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002035 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002036 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002037
2038 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2039 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002040 uint64_t TSize = 0;
2041 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2042 I!=E; ++I)
2043 TSize += I->size();
2044
2045 uint64_t LSize = FrontCase.size();
2046 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002047 DOUT << "Selecting best pivot: \n"
2048 << "First: " << First << ", Last: " << Last <<"\n"
2049 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002050 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002051 J!=E; ++I, ++J) {
2052 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2053 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002054 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002055 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2056 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002057 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002058 // Should always split in some non-trivial place
2059 DOUT <<"=>Step\n"
2060 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2061 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2062 << "Metric: " << Metric << "\n";
2063 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002064 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002065 FMetric = Metric;
2066 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002067 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002068
2069 LSize += J->size();
2070 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002071 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002072 if (areJTsAllowed(TLI)) {
2073 // If our case is dense we *really* should handle it earlier!
2074 assert((FMetric > 0) && "Should handle dense range earlier!");
2075 } else {
2076 Pivot = CR.Range.first + Size/2;
2077 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002078
2079 CaseRange LHSR(CR.Range.first, Pivot);
2080 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002081 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002082 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2083
2084 // We know that we branch to the LHS if the Value being switched on is
2085 // less than the Pivot value, C. We use this to optimize our binary
2086 // tree a bit, by recognizing that if SV is greater than or equal to the
2087 // LHS's Case Value, and that Case Value is exactly one less than the
2088 // Pivot's Value, then we can branch directly to the LHS's Target,
2089 // rather than creating a leaf node for it.
2090 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002091 LHSR.first->High == CR.GE &&
2092 cast<ConstantInt>(C)->getSExtValue() ==
2093 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2094 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002095 } else {
2096 TrueBB = new MachineBasicBlock(LLVMBB);
2097 CurMF->getBasicBlockList().insert(BBI, TrueBB);
2098 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2099 }
2100
2101 // Similar to the optimization above, if the Value being switched on is
2102 // known to be less than the Constant CR.LT, and the current Case Value
2103 // is CR.LT - 1, then we can branch directly to the target block for
2104 // the current Case Value, rather than emitting a RHS leaf node for it.
2105 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002106 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2107 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2108 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002109 } else {
2110 FalseBB = new MachineBasicBlock(LLVMBB);
2111 CurMF->getBasicBlockList().insert(BBI, FalseBB);
2112 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2113 }
2114
2115 // Create a CaseBlock record representing a conditional branch to
2116 // the LHS node if the value being switched on SV is less than C.
2117 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002118 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2119 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002120
2121 if (CR.CaseBB == CurMBB)
2122 visitSwitchCase(CB);
2123 else
2124 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002125
2126 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002127}
2128
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002129/// handleBitTestsSwitchCase - if current case range has few destination and
2130/// range span less, than machine word bitwidth, encode case range into series
2131/// of masks and emit bit tests with these masks.
2132bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2133 CaseRecVector& WorkList,
2134 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002135 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002136 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002137
2138 Case& FrontCase = *CR.Range.first;
2139 Case& BackCase = *(CR.Range.second-1);
2140
2141 // Get the MachineFunction which holds the current MBB. This is used when
2142 // inserting any additional MBBs necessary to represent the switch.
2143 MachineFunction *CurMF = CurMBB->getParent();
2144
2145 unsigned numCmps = 0;
2146 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2147 I!=E; ++I) {
2148 // Single case counts one, case range - two.
2149 if (I->Low == I->High)
2150 numCmps +=1;
2151 else
2152 numCmps +=2;
2153 }
2154
2155 // Count unique destinations
2156 SmallSet<MachineBasicBlock*, 4> Dests;
2157 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2158 Dests.insert(I->BB);
2159 if (Dests.size() > 3)
2160 // Don't bother the code below, if there are too much unique destinations
2161 return false;
2162 }
2163 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2164 << "Total number of comparisons: " << numCmps << "\n";
2165
2166 // Compute span of values.
2167 Constant* minValue = FrontCase.Low;
2168 Constant* maxValue = BackCase.High;
2169 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2170 cast<ConstantInt>(minValue)->getSExtValue();
2171 DOUT << "Compare range: " << range << "\n"
2172 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2173 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2174
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002175 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002176 (!(Dests.size() == 1 && numCmps >= 3) &&
2177 !(Dests.size() == 2 && numCmps >= 5) &&
2178 !(Dests.size() >= 3 && numCmps >= 6)))
2179 return false;
2180
2181 DOUT << "Emitting bit tests\n";
2182 int64_t lowBound = 0;
2183
2184 // Optimize the case where all the case values fit in a
2185 // word without having to subtract minValue. In this case,
2186 // we can optimize away the subtraction.
2187 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002188 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002189 range = cast<ConstantInt>(maxValue)->getSExtValue();
2190 } else {
2191 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2192 }
2193
2194 CaseBitsVector CasesBits;
2195 unsigned i, count = 0;
2196
2197 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2198 MachineBasicBlock* Dest = I->BB;
2199 for (i = 0; i < count; ++i)
2200 if (Dest == CasesBits[i].BB)
2201 break;
2202
2203 if (i == count) {
2204 assert((count < 3) && "Too much destinations to test!");
2205 CasesBits.push_back(CaseBits(0, Dest, 0));
2206 count++;
2207 }
2208
2209 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2210 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2211
2212 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002213 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002214 CasesBits[i].Bits++;
2215 }
2216
2217 }
2218 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2219
2220 SelectionDAGISel::BitTestInfo BTC;
2221
2222 // Figure out which block is immediately after the current one.
2223 MachineFunction::iterator BBI = CR.CaseBB;
2224 ++BBI;
2225
2226 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2227
2228 DOUT << "Cases:\n";
2229 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2230 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2231 << ", BB: " << CasesBits[i].BB << "\n";
2232
2233 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2234 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2235 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2236 CaseBB,
2237 CasesBits[i].BB));
2238 }
2239
2240 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002241 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002242 CR.CaseBB, Default, BTC);
2243
2244 if (CR.CaseBB == CurMBB)
2245 visitBitTestHeader(BTB);
2246
2247 BitTestCases.push_back(BTB);
2248
2249 return true;
2250}
2251
2252
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002253/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002254unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2255 const SwitchInst& SI) {
2256 unsigned numCmps = 0;
2257
2258 // Start with "simple" cases
2259 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2260 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2261 Cases.push_back(Case(SI.getSuccessorValue(i),
2262 SI.getSuccessorValue(i),
2263 SMBB));
2264 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002265 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002266
2267 // Merge case into clusters
2268 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002269 // Must recompute end() each iteration because it may be
2270 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002271 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002272 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2273 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2274 MachineBasicBlock* nextBB = J->BB;
2275 MachineBasicBlock* currentBB = I->BB;
2276
2277 // If the two neighboring cases go to the same destination, merge them
2278 // into a single case.
2279 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2280 I->High = J->High;
2281 J = Cases.erase(J);
2282 } else {
2283 I = J++;
2284 }
2285 }
2286
2287 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2288 if (I->Low != I->High)
2289 // A range counts double, since it requires two compares.
2290 ++numCmps;
2291 }
2292
2293 return numCmps;
2294}
2295
2296void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002297 // Figure out which block is immediately after the current one.
2298 MachineBasicBlock *NextBlock = 0;
2299 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002300
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002301 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002302
Nate Begemanf15485a2006-03-27 01:32:24 +00002303 // If there is only the default destination, branch to it if it is not the
2304 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002305 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002306 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002307
Nate Begemanf15485a2006-03-27 01:32:24 +00002308 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002309 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002310 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002311 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002312 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002313
Nate Begemanf15485a2006-03-27 01:32:24 +00002314 return;
2315 }
2316
2317 // If there are any non-default case statements, create a vector of Cases
2318 // representing each one, and sort the vector so that we can efficiently
2319 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002320 CaseVector Cases;
2321 unsigned numCmps = Clusterify(Cases, SI);
2322 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2323 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002324
Nate Begemanf15485a2006-03-27 01:32:24 +00002325 // Get the Value to be switched on and default basic blocks, which will be
2326 // inserted into CaseBlock records, representing basic blocks in the binary
2327 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002328 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002329
Nate Begemanf15485a2006-03-27 01:32:24 +00002330 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002331 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002332 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2333
2334 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002335 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002336 CaseRec CR = WorkList.back();
2337 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002338
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002339 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2340 continue;
2341
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002342 // If the range has few cases (two or less) emit a series of specific
2343 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002344 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2345 continue;
2346
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002347 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002348 // target supports indirect branches, then emit a jump table rather than
2349 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002350 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2351 continue;
2352
2353 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2354 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2355 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002356 }
2357}
2358
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002359
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002360void SelectionDAGLowering::visitSub(User &I) {
2361 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002362 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002363 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002364 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2365 const VectorType *DestTy = cast<VectorType>(I.getType());
2366 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002367 if (ElTy->isFloatingPoint()) {
2368 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002369 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002370 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2371 if (CV == CNZ) {
2372 SDOperand Op2 = getValue(I.getOperand(1));
2373 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2374 return;
2375 }
Dan Gohman7f321562007-06-25 16:23:39 +00002376 }
2377 }
2378 }
2379 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002381 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002382 SDOperand Op2 = getValue(I.getOperand(1));
2383 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2384 return;
2385 }
Dan Gohman7f321562007-06-25 16:23:39 +00002386 }
2387
2388 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002389}
2390
Dan Gohman7f321562007-06-25 16:23:39 +00002391void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002392 SDOperand Op1 = getValue(I.getOperand(0));
2393 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002394
2395 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002396}
2397
Nate Begemane21ea612005-11-18 07:42:56 +00002398void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2399 SDOperand Op1 = getValue(I.getOperand(0));
2400 SDOperand Op2 = getValue(I.getOperand(1));
2401
Duncan Sands8e4eb092008-06-08 20:54:56 +00002402 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002403 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002404 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002405 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002406
Chris Lattner1c08c712005-01-07 07:47:53 +00002407 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2408}
2409
Reid Spencer45fb3f32006-11-20 01:22:35 +00002410void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002411 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2412 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2413 predicate = IC->getPredicate();
2414 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2415 predicate = ICmpInst::Predicate(IC->getPredicate());
2416 SDOperand Op1 = getValue(I.getOperand(0));
2417 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002418 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002419 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002420 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2421 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2422 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2423 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2424 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2425 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2426 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2427 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2428 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2429 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2430 default:
2431 assert(!"Invalid ICmp predicate value");
2432 Opcode = ISD::SETEQ;
2433 break;
2434 }
2435 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2436}
2437
2438void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002439 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2440 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2441 predicate = FC->getPredicate();
2442 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2443 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002444 SDOperand Op1 = getValue(I.getOperand(0));
2445 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 ISD::CondCode Condition, FOC, FPC;
2447 switch (predicate) {
2448 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2449 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2450 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2451 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2452 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2453 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2454 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002455 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2456 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002457 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2458 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2459 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2460 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2461 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2462 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2463 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2464 default:
2465 assert(!"Invalid FCmp predicate value");
2466 FOC = FPC = ISD::SETFALSE;
2467 break;
2468 }
2469 if (FiniteOnlyFPMath())
2470 Condition = FOC;
2471 else
2472 Condition = FPC;
2473 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002474}
2475
Nate Begemanb43e9c12008-05-12 19:40:03 +00002476void SelectionDAGLowering::visitVICmp(User &I) {
2477 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2478 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2479 predicate = IC->getPredicate();
2480 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2481 predicate = ICmpInst::Predicate(IC->getPredicate());
2482 SDOperand Op1 = getValue(I.getOperand(0));
2483 SDOperand Op2 = getValue(I.getOperand(1));
2484 ISD::CondCode Opcode;
2485 switch (predicate) {
2486 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2487 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2488 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2489 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2490 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2491 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2492 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2493 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2494 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2495 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2496 default:
2497 assert(!"Invalid ICmp predicate value");
2498 Opcode = ISD::SETEQ;
2499 break;
2500 }
2501 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2502}
2503
2504void SelectionDAGLowering::visitVFCmp(User &I) {
2505 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2506 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2507 predicate = FC->getPredicate();
2508 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2509 predicate = FCmpInst::Predicate(FC->getPredicate());
2510 SDOperand Op1 = getValue(I.getOperand(0));
2511 SDOperand Op2 = getValue(I.getOperand(1));
2512 ISD::CondCode Condition, FOC, FPC;
2513 switch (predicate) {
2514 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2515 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2516 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2517 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2518 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2519 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2520 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2521 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2522 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2523 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2524 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2525 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2526 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2527 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2528 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2529 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2530 default:
2531 assert(!"Invalid VFCmp predicate value");
2532 FOC = FPC = ISD::SETFALSE;
2533 break;
2534 }
2535 if (FiniteOnlyFPMath())
2536 Condition = FOC;
2537 else
2538 Condition = FPC;
2539
Duncan Sands83ec4b62008-06-06 12:08:01 +00002540 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002541
2542 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2543}
2544
Chris Lattner1c08c712005-01-07 07:47:53 +00002545void SelectionDAGLowering::visitSelect(User &I) {
2546 SDOperand Cond = getValue(I.getOperand(0));
2547 SDOperand TrueVal = getValue(I.getOperand(1));
2548 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002549 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2550 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002551}
2552
Reid Spencer3da59db2006-11-27 01:05:10 +00002553
2554void SelectionDAGLowering::visitTrunc(User &I) {
2555 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2556 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002557 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002558 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2559}
2560
2561void SelectionDAGLowering::visitZExt(User &I) {
2562 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2563 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2564 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002565 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002566 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2567}
2568
2569void SelectionDAGLowering::visitSExt(User &I) {
2570 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2571 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2572 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002573 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002574 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2575}
2576
2577void SelectionDAGLowering::visitFPTrunc(User &I) {
2578 // FPTrunc is never a no-op cast, no need to check
2579 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002580 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002581 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002582}
2583
2584void SelectionDAGLowering::visitFPExt(User &I){
2585 // FPTrunc is never a no-op cast, no need to check
2586 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002587 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002588 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2589}
2590
2591void SelectionDAGLowering::visitFPToUI(User &I) {
2592 // FPToUI is never a no-op cast, no need to check
2593 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002594 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002595 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2596}
2597
2598void SelectionDAGLowering::visitFPToSI(User &I) {
2599 // FPToSI is never a no-op cast, no need to check
2600 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002601 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002602 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2603}
2604
2605void SelectionDAGLowering::visitUIToFP(User &I) {
2606 // UIToFP is never a no-op cast, no need to check
2607 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002608 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002609 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2610}
2611
2612void SelectionDAGLowering::visitSIToFP(User &I){
2613 // UIToFP is never a no-op cast, no need to check
2614 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002615 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002616 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2617}
2618
2619void SelectionDAGLowering::visitPtrToInt(User &I) {
2620 // What to do depends on the size of the integer and the size of the pointer.
2621 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002622 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002623 MVT SrcVT = N.getValueType();
2624 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002625 SDOperand Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002626 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002627 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2628 else
2629 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2630 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2631 setValue(&I, Result);
2632}
Chris Lattner1c08c712005-01-07 07:47:53 +00002633
Reid Spencer3da59db2006-11-27 01:05:10 +00002634void SelectionDAGLowering::visitIntToPtr(User &I) {
2635 // What to do depends on the size of the integer and the size of the pointer.
2636 // We can either truncate, zero extend, or no-op, accordingly.
2637 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002638 MVT SrcVT = N.getValueType();
2639 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002640 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002641 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2642 else
2643 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2644 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2645}
2646
2647void SelectionDAGLowering::visitBitCast(User &I) {
2648 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002649 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002650
2651 // BitCast assures us that source and destination are the same size so this
2652 // is either a BIT_CONVERT or a no-op.
2653 if (DestVT != N.getValueType())
2654 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2655 else
2656 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002657}
2658
Chris Lattner2bbd8102006-03-29 00:11:43 +00002659void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002660 SDOperand InVec = getValue(I.getOperand(0));
2661 SDOperand InVal = getValue(I.getOperand(1));
2662 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2663 getValue(I.getOperand(2)));
2664
Dan Gohman7f321562007-06-25 16:23:39 +00002665 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2666 TLI.getValueType(I.getType()),
2667 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002668}
2669
Chris Lattner2bbd8102006-03-29 00:11:43 +00002670void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002671 SDOperand InVec = getValue(I.getOperand(0));
2672 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2673 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002674 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002675 TLI.getValueType(I.getType()), InVec, InIdx));
2676}
Chris Lattnerc7029802006-03-18 01:44:44 +00002677
Chris Lattner3e104b12006-04-08 04:15:24 +00002678void SelectionDAGLowering::visitShuffleVector(User &I) {
2679 SDOperand V1 = getValue(I.getOperand(0));
2680 SDOperand V2 = getValue(I.getOperand(1));
2681 SDOperand Mask = getValue(I.getOperand(2));
2682
Dan Gohman7f321562007-06-25 16:23:39 +00002683 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2684 TLI.getValueType(I.getType()),
2685 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002686}
2687
Dan Gohman1d685a42008-06-07 02:02:36 +00002688void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2689 const Value *Op0 = I.getOperand(0);
2690 const Value *Op1 = I.getOperand(1);
2691 const Type *AggTy = I.getType();
2692 const Type *ValTy = Op1->getType();
2693 bool IntoUndef = isa<UndefValue>(Op0);
2694 bool FromUndef = isa<UndefValue>(Op1);
2695
2696 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2697 I.idx_begin(), I.idx_end());
2698
2699 SmallVector<MVT, 4> AggValueVTs;
2700 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2701 SmallVector<MVT, 4> ValValueVTs;
2702 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2703
2704 unsigned NumAggValues = AggValueVTs.size();
2705 unsigned NumValValues = ValValueVTs.size();
2706 SmallVector<SDOperand, 4> Values(NumAggValues);
2707
2708 SDOperand Agg = getValue(Op0);
2709 SDOperand Val = getValue(Op1);
2710 unsigned i = 0;
2711 // Copy the beginning value(s) from the original aggregate.
2712 for (; i != LinearIndex; ++i)
2713 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2714 SDOperand(Agg.Val, Agg.ResNo + i);
2715 // Copy values from the inserted value(s).
2716 for (; i != LinearIndex + NumValValues; ++i)
2717 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2718 SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2719 // Copy remaining value(s) from the original aggregate.
2720 for (; i != NumAggValues; ++i)
2721 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2722 SDOperand(Agg.Val, Agg.ResNo + i);
2723
Duncan Sandsf9516202008-06-30 10:19:09 +00002724 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2725 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002726}
2727
Dan Gohman1d685a42008-06-07 02:02:36 +00002728void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2729 const Value *Op0 = I.getOperand(0);
2730 const Type *AggTy = Op0->getType();
2731 const Type *ValTy = I.getType();
2732 bool OutOfUndef = isa<UndefValue>(Op0);
2733
2734 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2735 I.idx_begin(), I.idx_end());
2736
2737 SmallVector<MVT, 4> ValValueVTs;
2738 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2739
2740 unsigned NumValValues = ValValueVTs.size();
2741 SmallVector<SDOperand, 4> Values(NumValValues);
2742
2743 SDOperand Agg = getValue(Op0);
2744 // Copy out the selected value(s).
2745 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2746 Values[i - LinearIndex] =
Dan Gohmandded0fd2008-06-20 00:54:19 +00002747 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
2748 SDOperand(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002749
Duncan Sandsf9516202008-06-30 10:19:09 +00002750 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2751 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002752}
2753
Chris Lattner3e104b12006-04-08 04:15:24 +00002754
Chris Lattner1c08c712005-01-07 07:47:53 +00002755void SelectionDAGLowering::visitGetElementPtr(User &I) {
2756 SDOperand N = getValue(I.getOperand(0));
2757 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002758
2759 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2760 OI != E; ++OI) {
2761 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002762 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002763 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002764 if (Field) {
2765 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002766 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002767 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002768 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002769 }
2770 Ty = StTy->getElementType(Field);
2771 } else {
2772 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002773
Chris Lattner7c0104b2005-11-09 04:45:33 +00002774 // If this is a constant subscript, handle it quickly.
2775 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002776 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002777 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002778 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002779 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2780 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002781 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002782 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002783
2784 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002785 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002786 SDOperand IdxN = getValue(Idx);
2787
2788 // If the index is smaller or larger than intptr_t, truncate or extend
2789 // it.
Duncan Sands8e4eb092008-06-08 20:54:56 +00002790 if (IdxN.getValueType().bitsLT(N.getValueType())) {
Reid Spencer47857812006-12-31 05:55:36 +00002791 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002792 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002793 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2794
2795 // If this is a multiply by a power of two, turn it into a shl
2796 // immediately. This is a very common case.
2797 if (isPowerOf2_64(ElementSize)) {
2798 unsigned Amt = Log2_64(ElementSize);
2799 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002800 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002801 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2802 continue;
2803 }
2804
Chris Lattner0bd48932008-01-17 07:00:52 +00002805 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002806 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2807 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002808 }
2809 }
2810 setValue(&I, N);
2811}
2812
2813void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2814 // If this is a fixed sized alloca in the entry block of the function,
2815 // allocate it statically on the stack.
2816 if (FuncInfo.StaticAllocaMap.count(&I))
2817 return; // getValue will auto-populate this.
2818
2819 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002820 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002821 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002822 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002823 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002824
2825 SDOperand AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002826 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002827 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002828 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002829 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002830 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002831
Chris Lattner68cd65e2005-01-22 23:04:37 +00002832 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002833 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002834
Evan Cheng45157792007-08-16 23:46:29 +00002835 // Handle alignment. If the requested alignment is less than or equal to
2836 // the stack alignment, ignore it. If the size is greater than or equal to
2837 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002838 unsigned StackAlign =
2839 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002840 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002841 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002842
2843 // Round the size of the allocation up to the stack alignment size
2844 // by add SA-1 to the size.
2845 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002846 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002847 // Mask out the low bits for alignment purposes.
2848 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002849 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002850
Chris Lattner0bd48932008-01-17 07:00:52 +00002851 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002852 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002853 MVT::Other);
2854 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002855 setValue(&I, DSA);
2856 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002857
2858 // Inform the Frame Information that we have just allocated a variable-sized
2859 // object.
2860 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2861}
2862
Chris Lattner1c08c712005-01-07 07:47:53 +00002863void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002864 const Value *SV = I.getOperand(0);
2865 SDOperand Ptr = getValue(SV);
2866
2867 const Type *Ty = I.getType();
2868 bool isVolatile = I.isVolatile();
2869 unsigned Alignment = I.getAlignment();
2870
2871 SmallVector<MVT, 4> ValueVTs;
2872 SmallVector<uint64_t, 4> Offsets;
2873 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2874 unsigned NumValues = ValueVTs.size();
2875 if (NumValues == 0)
2876 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002877
Chris Lattnerd3948112005-01-17 22:19:26 +00002878 SDOperand Root;
2879 if (I.isVolatile())
2880 Root = getRoot();
2881 else {
2882 // Do not serialize non-volatile loads against each other.
2883 Root = DAG.getRoot();
2884 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002885
Dan Gohman1d685a42008-06-07 02:02:36 +00002886 SmallVector<SDOperand, 4> Values(NumValues);
2887 SmallVector<SDOperand, 4> Chains(NumValues);
2888 MVT PtrVT = Ptr.getValueType();
2889 for (unsigned i = 0; i != NumValues; ++i) {
2890 SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2891 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2892 DAG.getConstant(Offsets[i], PtrVT)),
2893 SV, Offsets[i],
2894 isVolatile, Alignment);
2895 Values[i] = L;
2896 Chains[i] = L.getValue(1);
2897 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002898
Dan Gohman1d685a42008-06-07 02:02:36 +00002899 SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2900 &Chains[0], NumValues);
2901 if (isVolatile)
2902 DAG.setRoot(Chain);
2903 else
2904 PendingLoads.push_back(Chain);
2905
Duncan Sandsf9516202008-06-30 10:19:09 +00002906 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2907 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002908}
2909
2910
2911void SelectionDAGLowering::visitStore(StoreInst &I) {
2912 Value *SrcV = I.getOperand(0);
2913 SDOperand Src = getValue(SrcV);
Dan Gohman1d685a42008-06-07 02:02:36 +00002914 Value *PtrV = I.getOperand(1);
2915 SDOperand Ptr = getValue(PtrV);
2916
2917 SmallVector<MVT, 4> ValueVTs;
2918 SmallVector<uint64_t, 4> Offsets;
2919 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2920 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002921 if (NumValues == 0)
2922 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002923
2924 SDOperand Root = getRoot();
2925 SmallVector<SDOperand, 4> Chains(NumValues);
2926 MVT PtrVT = Ptr.getValueType();
2927 bool isVolatile = I.isVolatile();
2928 unsigned Alignment = I.getAlignment();
2929 for (unsigned i = 0; i != NumValues; ++i)
2930 Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2931 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2932 DAG.getConstant(Offsets[i], PtrVT)),
2933 PtrV, Offsets[i],
2934 isVolatile, Alignment);
2935
2936 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002937}
2938
Chris Lattner0eade312006-03-24 02:22:33 +00002939/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2940/// node.
2941void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2942 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002943 bool HasChain = !I.doesNotAccessMemory();
2944 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2945
Chris Lattner0eade312006-03-24 02:22:33 +00002946 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002947 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002948 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2949 if (OnlyLoad) {
2950 // We don't need to serialize loads against other loads.
2951 Ops.push_back(DAG.getRoot());
2952 } else {
2953 Ops.push_back(getRoot());
2954 }
2955 }
Chris Lattner0eade312006-03-24 02:22:33 +00002956
2957 // Add the intrinsic ID as an integer operand.
2958 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2959
2960 // Add all operands of the call to the operand list.
2961 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2962 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002963 assert(TLI.isTypeLegal(Op.getValueType()) &&
2964 "Intrinsic uses a non-legal type?");
2965 Ops.push_back(Op);
2966 }
2967
Duncan Sands83ec4b62008-06-06 12:08:01 +00002968 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00002969 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002970 MVT VT = TLI.getValueType(I.getType());
2971 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002972 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002973 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00002974
Duncan Sands83ec4b62008-06-06 12:08:01 +00002975 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00002976 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2977 }
2978
2979 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2980 VTs.push_back(VT);
2981 }
2982 if (HasChain)
2983 VTs.push_back(MVT::Other);
2984
Duncan Sands83ec4b62008-06-06 12:08:01 +00002985 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002986
Chris Lattner0eade312006-03-24 02:22:33 +00002987 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002988 SDOperand Result;
2989 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002990 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2991 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002992 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002993 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2994 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002995 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002996 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2997 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002998
Chris Lattnere58a7802006-04-02 03:41:14 +00002999 if (HasChain) {
3000 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
3001 if (OnlyLoad)
3002 PendingLoads.push_back(Chain);
3003 else
3004 DAG.setRoot(Chain);
3005 }
Chris Lattner0eade312006-03-24 02:22:33 +00003006 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003007 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003008 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003009 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003010 }
3011 setValue(&I, Result);
3012 }
3013}
3014
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003015/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003016static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003017 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003018 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003019 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003020 "TypeInfo must be a global variable or NULL");
3021 return GV;
3022}
3023
Duncan Sandsf4070822007-06-15 19:04:19 +00003024/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003025/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003026static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3027 MachineBasicBlock *MBB) {
3028 // Inform the MachineModuleInfo of the personality for this landing pad.
3029 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3030 assert(CE->getOpcode() == Instruction::BitCast &&
3031 isa<Function>(CE->getOperand(0)) &&
3032 "Personality should be a function");
3033 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3034
3035 // Gather all the type infos for this landing pad and pass them along to
3036 // MachineModuleInfo.
3037 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003038 unsigned N = I.getNumOperands();
3039
3040 for (unsigned i = N - 1; i > 2; --i) {
3041 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3042 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003043 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003044 assert (FirstCatch <= N && "Invalid filter length");
3045
3046 if (FirstCatch < N) {
3047 TyInfo.reserve(N - FirstCatch);
3048 for (unsigned j = FirstCatch; j < N; ++j)
3049 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050 MMI->addCatchTypeInfo(MBB, TyInfo);
3051 TyInfo.clear();
3052 }
3053
Duncan Sands6590b042007-08-27 15:47:50 +00003054 if (!FilterLength) {
3055 // Cleanup.
3056 MMI->addCleanup(MBB);
3057 } else {
3058 // Filter.
3059 TyInfo.reserve(FilterLength - 1);
3060 for (unsigned j = i + 1; j < FirstCatch; ++j)
3061 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062 MMI->addFilterTypeInfo(MBB, TyInfo);
3063 TyInfo.clear();
3064 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003065
3066 N = i;
3067 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003068 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003069
3070 if (N > 3) {
3071 TyInfo.reserve(N - 3);
3072 for (unsigned j = 3; j < N; ++j)
3073 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003074 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003075 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003076}
3077
Mon P Wang63307c32008-05-05 19:05:59 +00003078
3079/// Inlined utility function to implement binary input atomic intrinsics for
3080// visitIntrinsicCall: I is a call instruction
3081// Op is the associated NodeType for I
3082const char *
3083SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3084 SDOperand Root = getRoot();
Mon P Wang63307c32008-05-05 19:05:59 +00003085 SDOperand L = DAG.getAtomic(Op, Root,
3086 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003087 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003088 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003089 setValue(&I, L);
3090 DAG.setRoot(L.getValue(1));
3091 return 0;
3092}
3093
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003094/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3095/// we want to emit this as a call to a named external function, return the name
3096/// otherwise lower it and return null.
3097const char *
3098SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3099 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003100 default:
3101 // By default, turn this into a target intrinsic node.
3102 visitTargetIntrinsic(I, Intrinsic);
3103 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003104 case Intrinsic::vastart: visitVAStart(I); return 0;
3105 case Intrinsic::vaend: visitVAEnd(I); return 0;
3106 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003107 case Intrinsic::returnaddress:
3108 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3109 getValue(I.getOperand(1))));
3110 return 0;
3111 case Intrinsic::frameaddress:
3112 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3113 getValue(I.getOperand(1))));
3114 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003115 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003116 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003117 break;
3118 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003119 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003120 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003121 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003122 case Intrinsic::memcpy_i64: {
3123 SDOperand Op1 = getValue(I.getOperand(1));
3124 SDOperand Op2 = getValue(I.getOperand(2));
3125 SDOperand Op3 = getValue(I.getOperand(3));
3126 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3128 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003129 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003130 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003131 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003132 case Intrinsic::memset_i64: {
3133 SDOperand Op1 = getValue(I.getOperand(1));
3134 SDOperand Op2 = getValue(I.getOperand(2));
3135 SDOperand Op3 = getValue(I.getOperand(3));
3136 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3137 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3138 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003139 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003140 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003141 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003142 case Intrinsic::memmove_i64: {
3143 SDOperand Op1 = getValue(I.getOperand(1));
3144 SDOperand Op2 = getValue(I.getOperand(2));
3145 SDOperand Op3 = getValue(I.getOperand(3));
3146 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3147
3148 // If the source and destination are known to not be aliases, we can
3149 // lower memmove as memcpy.
3150 uint64_t Size = -1ULL;
3151 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3152 Size = C->getValue();
3153 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3154 AliasAnalysis::NoAlias) {
3155 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3156 I.getOperand(1), 0, I.getOperand(2), 0));
3157 return 0;
3158 }
3159
3160 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3161 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003162 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003163 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003164 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003165 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003166 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003167 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003168 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003169 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003170 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3171 SPI.getLine(),
3172 SPI.getColumn(),
3173 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003174 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003175
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003176 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003177 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003178 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003179 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003180 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003181 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3182 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003183 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003184 }
3185
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003186 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003187 }
3188 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003189 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003190 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003191 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003193 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003194 }
3195
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003196 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003197 }
3198 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003199 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003200 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003201 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003202 Value *SP = FSI.getSubprogram();
3203 if (SP && MMI->Verify(SP)) {
3204 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3205 // what (most?) gdb expects.
3206 DebugInfoDesc *DD = MMI->getDescFor(SP);
3207 assert(DD && "Not a debug information descriptor");
3208 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3209 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003210 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003211 // Record the source line but does create a label. It will be emitted
3212 // at asm emission time.
3213 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003214 }
3215
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003216 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003217 }
3218 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003219 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003220 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003221 Value *Variable = DI.getVariable();
3222 if (MMI && Variable && MMI->Verify(Variable))
3223 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3224 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003225 return 0;
3226 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003227
Jim Laskeyb180aa12007-02-21 22:53:45 +00003228 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003229 if (!CurMBB->isLandingPad()) {
3230 // FIXME: Mark exception register as live in. Hack for PR1508.
3231 unsigned Reg = TLI.getExceptionAddressRegister();
3232 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003233 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003234 // Insert the EXCEPTIONADDR instruction.
3235 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3236 SDOperand Ops[1];
3237 Ops[0] = DAG.getRoot();
3238 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3239 setValue(&I, Op);
3240 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003241 return 0;
3242 }
3243
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003244 case Intrinsic::eh_selector_i32:
3245 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003246 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003247 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003248 MVT::i32 : MVT::i64);
3249
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003250 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003251 if (CurMBB->isLandingPad())
3252 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003253 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003254#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003255 FuncInfo.CatchInfoLost.insert(&I);
3256#endif
Duncan Sands90291952007-07-06 09:18:59 +00003257 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3258 unsigned Reg = TLI.getExceptionSelectorRegister();
3259 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003260 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003261
3262 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003263 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003264 SDOperand Ops[2];
3265 Ops[0] = getValue(I.getOperand(1));
3266 Ops[1] = getRoot();
3267 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3268 setValue(&I, Op);
3269 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003270 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003271 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003272 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003273
3274 return 0;
3275 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003276
3277 case Intrinsic::eh_typeid_for_i32:
3278 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003279 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003280 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003281 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003282
Jim Laskey735b6f82007-02-22 15:38:06 +00003283 if (MMI) {
3284 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003285 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003286
Jim Laskey735b6f82007-02-22 15:38:06 +00003287 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003288 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003289 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003290 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003291 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003292 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003293
3294 return 0;
3295 }
3296
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003297 case Intrinsic::eh_return: {
3298 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3299
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003300 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003301 MMI->setCallsEHReturn(true);
3302 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3303 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003304 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003305 getValue(I.getOperand(1)),
3306 getValue(I.getOperand(2))));
3307 } else {
3308 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3309 }
3310
3311 return 0;
3312 }
3313
3314 case Intrinsic::eh_unwind_init: {
3315 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3316 MMI->setCallsUnwindInit(true);
3317 }
3318
3319 return 0;
3320 }
3321
3322 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003323 MVT VT = getValue(I.getOperand(1)).getValueType();
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003324 SDOperand CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003325 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003326 CfaArg = DAG.getNode(ISD::TRUNCATE,
3327 TLI.getPointerTy(), getValue(I.getOperand(1)));
3328 else
3329 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3330 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003331
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003332 SDOperand Offset = DAG.getNode(ISD::ADD,
3333 TLI.getPointerTy(),
3334 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3335 TLI.getPointerTy()),
3336 CfaArg);
3337 setValue(&I, DAG.getNode(ISD::ADD,
3338 TLI.getPointerTy(),
3339 DAG.getNode(ISD::FRAMEADDR,
3340 TLI.getPointerTy(),
3341 DAG.getConstant(0,
3342 TLI.getPointerTy())),
3343 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003344 return 0;
3345 }
3346
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003347 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003348 setValue(&I, DAG.getNode(ISD::FSQRT,
3349 getValue(I.getOperand(1)).getValueType(),
3350 getValue(I.getOperand(1))));
3351 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003352 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003353 setValue(&I, DAG.getNode(ISD::FPOWI,
3354 getValue(I.getOperand(1)).getValueType(),
3355 getValue(I.getOperand(1)),
3356 getValue(I.getOperand(2))));
3357 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003358 case Intrinsic::sin:
3359 setValue(&I, DAG.getNode(ISD::FSIN,
3360 getValue(I.getOperand(1)).getValueType(),
3361 getValue(I.getOperand(1))));
3362 return 0;
3363 case Intrinsic::cos:
3364 setValue(&I, DAG.getNode(ISD::FCOS,
3365 getValue(I.getOperand(1)).getValueType(),
3366 getValue(I.getOperand(1))));
3367 return 0;
3368 case Intrinsic::pow:
3369 setValue(&I, DAG.getNode(ISD::FPOW,
3370 getValue(I.getOperand(1)).getValueType(),
3371 getValue(I.getOperand(1)),
3372 getValue(I.getOperand(2))));
3373 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003374 case Intrinsic::pcmarker: {
3375 SDOperand Tmp = getValue(I.getOperand(1));
3376 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3377 return 0;
3378 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003379 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003380 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003381 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3382 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3383 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003384 setValue(&I, Tmp);
3385 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003386 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003387 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003388 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003389 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003390 assert(0 && "part_select intrinsic not implemented");
3391 abort();
3392 }
3393 case Intrinsic::part_set: {
3394 // Currently not implemented: just abort
3395 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003396 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003397 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003398 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003399 setValue(&I, DAG.getNode(ISD::BSWAP,
3400 getValue(I.getOperand(1)).getValueType(),
3401 getValue(I.getOperand(1))));
3402 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003403 case Intrinsic::cttz: {
3404 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003405 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003406 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003407 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003408 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003409 }
3410 case Intrinsic::ctlz: {
3411 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003412 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003413 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003414 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003415 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003416 }
3417 case Intrinsic::ctpop: {
3418 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003419 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003420 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003421 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003422 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003423 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003424 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003425 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003426 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3427 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003428 setValue(&I, Tmp);
3429 DAG.setRoot(Tmp.getValue(1));
3430 return 0;
3431 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003432 case Intrinsic::stackrestore: {
3433 SDOperand Tmp = getValue(I.getOperand(1));
3434 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003435 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003436 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003437 case Intrinsic::var_annotation:
3438 // Discard annotate attributes
3439 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003440
Duncan Sands36397f52007-07-27 12:58:54 +00003441 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003442 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003443
3444 SDOperand Ops[6];
3445 Ops[0] = getRoot();
3446 Ops[1] = getValue(I.getOperand(1));
3447 Ops[2] = getValue(I.getOperand(2));
3448 Ops[3] = getValue(I.getOperand(3));
3449 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3450 Ops[5] = DAG.getSrcValue(F);
3451
Duncan Sandsf7331b32007-09-11 14:10:23 +00003452 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3453 DAG.getNodeValueTypes(TLI.getPointerTy(),
3454 MVT::Other), 2,
3455 Ops, 6);
3456
3457 setValue(&I, Tmp);
3458 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003459 return 0;
3460 }
Gordon Henriksence224772008-01-07 01:30:38 +00003461
3462 case Intrinsic::gcroot:
3463 if (GCI) {
3464 Value *Alloca = I.getOperand(1);
3465 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3466
3467 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3468 GCI->addStackRoot(FI->getIndex(), TypeMap);
3469 }
3470 return 0;
3471
3472 case Intrinsic::gcread:
3473 case Intrinsic::gcwrite:
3474 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3475 return 0;
3476
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003477 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003478 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003479 return 0;
3480 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003481
3482 case Intrinsic::trap: {
3483 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3484 return 0;
3485 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003486 case Intrinsic::prefetch: {
3487 SDOperand Ops[4];
3488 Ops[0] = getRoot();
3489 Ops[1] = getValue(I.getOperand(1));
3490 Ops[2] = getValue(I.getOperand(2));
3491 Ops[3] = getValue(I.getOperand(3));
3492 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3493 return 0;
3494 }
3495
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003496 case Intrinsic::memory_barrier: {
3497 SDOperand Ops[6];
3498 Ops[0] = getRoot();
3499 for (int x = 1; x < 6; ++x)
3500 Ops[x] = getValue(I.getOperand(x));
3501
3502 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3503 return 0;
3504 }
Mon P Wang28873102008-06-25 08:15:39 +00003505 case Intrinsic::atomic_cmp_swap: {
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003506 SDOperand Root = getRoot();
Mon P Wang28873102008-06-25 08:15:39 +00003507 SDOperand L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003508 getValue(I.getOperand(1)),
3509 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003510 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003511 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003512 setValue(&I, L);
3513 DAG.setRoot(L.getValue(1));
3514 return 0;
3515 }
Mon P Wang28873102008-06-25 08:15:39 +00003516 case Intrinsic::atomic_load_add:
3517 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3518 case Intrinsic::atomic_load_sub:
3519 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003520 case Intrinsic::atomic_load_and:
3521 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3522 case Intrinsic::atomic_load_or:
3523 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3524 case Intrinsic::atomic_load_xor:
3525 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003526 case Intrinsic::atomic_load_nand:
3527 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003528 case Intrinsic::atomic_load_min:
3529 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3530 case Intrinsic::atomic_load_max:
3531 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3532 case Intrinsic::atomic_load_umin:
3533 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3534 case Intrinsic::atomic_load_umax:
3535 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3536 case Intrinsic::atomic_swap:
3537 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003538 }
3539}
3540
3541
Duncan Sands6f74b482007-12-19 09:48:52 +00003542void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003543 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003544 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003545 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003546 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003547 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3548 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003549
Jim Laskey735b6f82007-02-22 15:38:06 +00003550 TargetLowering::ArgListTy Args;
3551 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003552 Args.reserve(CS.arg_size());
3553 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3554 i != e; ++i) {
3555 SDOperand ArgNode = getValue(*i);
3556 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003557
Duncan Sands6f74b482007-12-19 09:48:52 +00003558 unsigned attrInd = i - CS.arg_begin() + 1;
3559 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3560 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3561 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3562 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3563 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3564 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003565 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003566 Args.push_back(Entry);
3567 }
3568
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003569 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003570 // Insert a label before the invoke call to mark the try range. This can be
3571 // used to detect deletion of the invoke via the MachineModuleInfo.
3572 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003573 // Both PendingLoads and PendingExports must be flushed here;
3574 // this call might not return.
3575 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003576 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003577 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003578
Jim Laskey735b6f82007-02-22 15:38:06 +00003579 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003580 TLI.LowerCallTo(getRoot(), CS.getType(),
3581 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003582 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003583 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003584 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003585 if (CS.getType() != Type::VoidTy)
3586 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003587 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003588
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003589 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003590 // Insert a label at the end of the invoke call to mark the try range. This
3591 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3592 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003593 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003594
Duncan Sands6f74b482007-12-19 09:48:52 +00003595 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003596 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3597 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003598}
3599
3600
Chris Lattner1c08c712005-01-07 07:47:53 +00003601void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003602 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003603 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003604 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003605 if (unsigned IID = F->getIntrinsicID()) {
3606 RenameFn = visitIntrinsicCall(I, IID);
3607 if (!RenameFn)
3608 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003609 }
3610 }
3611
3612 // Check for well-known libc/libm calls. If the function is internal, it
3613 // can't be a library call.
3614 unsigned NameLen = F->getNameLen();
3615 if (!F->hasInternalLinkage() && NameLen) {
3616 const char *NameStr = F->getNameStart();
3617 if (NameStr[0] == 'c' &&
3618 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3619 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3620 if (I.getNumOperands() == 3 && // Basic sanity checks.
3621 I.getOperand(1)->getType()->isFloatingPoint() &&
3622 I.getType() == I.getOperand(1)->getType() &&
3623 I.getType() == I.getOperand(2)->getType()) {
3624 SDOperand LHS = getValue(I.getOperand(1));
3625 SDOperand RHS = getValue(I.getOperand(2));
3626 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3627 LHS, RHS));
3628 return;
3629 }
3630 } else if (NameStr[0] == 'f' &&
3631 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003632 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3633 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003634 if (I.getNumOperands() == 2 && // Basic sanity checks.
3635 I.getOperand(1)->getType()->isFloatingPoint() &&
3636 I.getType() == I.getOperand(1)->getType()) {
3637 SDOperand Tmp = getValue(I.getOperand(1));
3638 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3639 return;
3640 }
3641 } else if (NameStr[0] == 's' &&
3642 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003643 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3644 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003645 if (I.getNumOperands() == 2 && // Basic sanity checks.
3646 I.getOperand(1)->getType()->isFloatingPoint() &&
3647 I.getType() == I.getOperand(1)->getType()) {
3648 SDOperand Tmp = getValue(I.getOperand(1));
3649 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3650 return;
3651 }
3652 } else if (NameStr[0] == 'c' &&
3653 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003654 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3655 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003656 if (I.getNumOperands() == 2 && // Basic sanity checks.
3657 I.getOperand(1)->getType()->isFloatingPoint() &&
3658 I.getType() == I.getOperand(1)->getType()) {
3659 SDOperand Tmp = getValue(I.getOperand(1));
3660 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3661 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003662 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003663 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003664 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003665 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003666 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003667 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003668 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003669
Chris Lattner64e14b12005-01-08 22:48:57 +00003670 SDOperand Callee;
3671 if (!RenameFn)
3672 Callee = getValue(I.getOperand(0));
3673 else
3674 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003675
Duncan Sands6f74b482007-12-19 09:48:52 +00003676 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003677}
3678
Jim Laskey735b6f82007-02-22 15:38:06 +00003679
Dan Gohmanef5d1942008-03-11 21:11:25 +00003680void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003681 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003682 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3683 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003684 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003685 }
Chris Lattner6833b062008-04-28 07:16:35 +00003686
3687 // To add support for individual return values with aggregate types,
3688 // we'd need a way to take a getresult index and determine which
3689 // values of the Call SDNode are associated with it.
3690 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3691 "Individual return values must not be aggregates!");
3692
3693 SDOperand Call = getValue(I.getOperand(0));
3694 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003695}
3696
3697
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003698/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3699/// this value and returns the result as a ValueVT value. This uses
3700/// Chain/Flag as the input and updates them for the output Chain/Flag.
3701/// If the Flag pointer is NULL, no flag is used.
Chris Lattneread0d882008-06-17 06:09:18 +00003702SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003703 SDOperand &Chain,
3704 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003705 // Assemble the legal parts into the final values.
3706 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003707 SmallVector<SDOperand, 8> Parts;
3708 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003709 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003710 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003711 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003712 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003713
Chris Lattner6833b062008-04-28 07:16:35 +00003714 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003715 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003716 SDOperand P;
3717 if (Flag == 0)
3718 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3719 else {
3720 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003721 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003722 }
3723 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003724
3725 // If the source register was virtual and if we know something about it,
3726 // add an assert node.
3727 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3728 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3729 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3730 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3731 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3732 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3733
3734 unsigned RegSize = RegisterVT.getSizeInBits();
3735 unsigned NumSignBits = LOI.NumSignBits;
3736 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3737
3738 // FIXME: We capture more information than the dag can represent. For
3739 // now, just use the tightest assertzext/assertsext possible.
3740 bool isSExt = true;
3741 MVT FromVT(MVT::Other);
3742 if (NumSignBits == RegSize)
3743 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3744 else if (NumZeroBits >= RegSize-1)
3745 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3746 else if (NumSignBits > RegSize-8)
3747 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3748 else if (NumZeroBits >= RegSize-9)
3749 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3750 else if (NumSignBits > RegSize-16)
3751 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3752 else if (NumZeroBits >= RegSize-17)
3753 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3754 else if (NumSignBits > RegSize-32)
3755 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3756 else if (NumZeroBits >= RegSize-33)
3757 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3758
3759 if (FromVT != MVT::Other) {
3760 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3761 RegisterVT, P, DAG.getValueType(FromVT));
3762
3763 }
3764 }
3765 }
3766
Dan Gohman23ce5022008-04-25 18:27:55 +00003767 Parts[Part+i] = P;
3768 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003769
Dan Gohman23ce5022008-04-25 18:27:55 +00003770 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3771 ValueVT);
3772 Part += NumRegs;
3773 }
Chris Lattner6833b062008-04-28 07:16:35 +00003774
3775 if (ValueVTs.size() == 1)
3776 return Values[0];
3777
Duncan Sandsf9516202008-06-30 10:19:09 +00003778 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3779 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003780}
3781
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003782/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3783/// specified value into the registers specified by this object. This uses
3784/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003785/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003786void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003787 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003788 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003789 unsigned NumRegs = Regs.size();
3790 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003791 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003792 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003793 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003794 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003795
3796 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3797 &Parts[Part], NumParts, RegisterVT);
3798 Part += NumParts;
3799 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003800
3801 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003802 SmallVector<SDOperand, 8> Chains(NumRegs);
3803 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003804 SDOperand Part;
3805 if (Flag == 0)
3806 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3807 else {
3808 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003809 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003810 }
3811 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003812 }
Chris Lattner6833b062008-04-28 07:16:35 +00003813
Evan Cheng33bf38a2008-04-28 22:07:13 +00003814 if (NumRegs == 1 || Flag)
3815 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3816 // flagged to it. That is the CopyToReg nodes and the user are considered
3817 // a single scheduling unit. If we create a TokenFactor and return it as
3818 // chain, then the TokenFactor is both a predecessor (operand) of the
3819 // user as well as a successor (the TF operands are flagged to the user).
3820 // c1, f1 = CopyToReg
3821 // c2, f2 = CopyToReg
3822 // c3 = TokenFactor c1, c2
3823 // ...
3824 // = op c3, ..., f2
3825 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003826 else
3827 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003828}
Chris Lattner864635a2006-02-22 22:37:12 +00003829
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003830/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3831/// operand list. This adds the code marker and includes the number of
3832/// values added into it.
3833void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003834 std::vector<SDOperand> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003835 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003836 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003837 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3838 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003839 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003840 for (unsigned i = 0; i != NumRegs; ++i)
3841 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003842 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003843}
Chris Lattner864635a2006-02-22 22:37:12 +00003844
3845/// isAllocatableRegister - If the specified register is safe to allocate,
3846/// i.e. it isn't a stack pointer or some other special register, return the
3847/// register class for the register. Otherwise, return null.
3848static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003849isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003850 const TargetLowering &TLI,
3851 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003852 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003853 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003854 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3855 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003856 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003857
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003858 const TargetRegisterClass *RC = *RCI;
3859 // If none of the the value types for this register class are valid, we
3860 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003861 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3862 I != E; ++I) {
3863 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003864 // If we have already found this register in a different register class,
3865 // choose the one with the largest VT specified. For example, on
3866 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003867 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003868 ThisVT = *I;
3869 break;
3870 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003871 }
3872 }
3873
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003874 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003875
Chris Lattner864635a2006-02-22 22:37:12 +00003876 // NOTE: This isn't ideal. In particular, this might allocate the
3877 // frame pointer in functions that need it (due to them not being taken
3878 // out of allocation, because a variable sized allocation hasn't been seen
3879 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003880 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3881 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003882 if (*I == Reg) {
3883 // We found a matching register class. Keep looking at others in case
3884 // we find one with larger registers that this physreg is also in.
3885 FoundRC = RC;
3886 FoundVT = ThisVT;
3887 break;
3888 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003889 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003890 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003891}
3892
Chris Lattner4e4b5762006-02-01 18:59:47 +00003893
Chris Lattner0c583402007-04-28 20:49:53 +00003894namespace {
3895/// AsmOperandInfo - This contains information for each constraint that we are
3896/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003897struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3898 /// CallOperand - If this is the result output operand or a clobber
3899 /// this is null, otherwise it is the incoming operand to the CallInst.
3900 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003901 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003902
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003903 /// AssignedRegs - If this is a register or register class operand, this
3904 /// contains the set of register corresponding to the operand.
3905 RegsForValue AssignedRegs;
3906
Dan Gohman23ce5022008-04-25 18:27:55 +00003907 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003908 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003909 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003910
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003911 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3912 /// busy in OutputRegs/InputRegs.
3913 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3914 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003915 std::set<unsigned> &InputRegs,
3916 const TargetRegisterInfo &TRI) const {
3917 if (isOutReg) {
3918 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3919 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3920 }
3921 if (isInReg) {
3922 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3923 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3924 }
3925 }
3926
3927private:
3928 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3929 /// specified set.
3930 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3931 const TargetRegisterInfo &TRI) {
3932 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3933 Regs.insert(Reg);
3934 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3935 for (; *Aliases; ++Aliases)
3936 Regs.insert(*Aliases);
3937 }
Chris Lattner0c583402007-04-28 20:49:53 +00003938};
3939} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003940
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003941
Chris Lattner0fe71e92008-02-21 19:43:13 +00003942/// GetRegistersForValue - Assign registers (virtual or physical) for the
3943/// specified operand. We prefer to assign virtual registers, to allow the
3944/// register allocator handle the assignment process. However, if the asm uses
3945/// features that we can't model on machineinstrs, we have SDISel do the
3946/// allocation. This produces generally horrible, but correct, code.
3947///
3948/// OpInfo describes the operand.
3949/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3950/// or any explicitly clobbered registers.
3951/// Input and OutputRegs are the set of already allocated physical registers.
3952///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003953void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003954GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003955 std::set<unsigned> &OutputRegs,
3956 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003957 // Compute whether this value requires an input register, an output register,
3958 // or both.
3959 bool isOutReg = false;
3960 bool isInReg = false;
3961 switch (OpInfo.Type) {
3962 case InlineAsm::isOutput:
3963 isOutReg = true;
3964
3965 // If this is an early-clobber output, or if there is an input
3966 // constraint that matches this, we need to reserve the input register
3967 // so no other inputs allocate to it.
3968 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3969 break;
3970 case InlineAsm::isInput:
3971 isInReg = true;
3972 isOutReg = false;
3973 break;
3974 case InlineAsm::isClobber:
3975 isOutReg = true;
3976 isInReg = true;
3977 break;
3978 }
3979
3980
3981 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003982 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003983
3984 // If this is a constraint for a single physreg, or a constraint for a
3985 // register class, find it.
3986 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3987 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3988 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003989
3990 unsigned NumRegs = 1;
3991 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003992 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003993 MVT RegVT;
3994 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003995
Chris Lattnerbf996f12007-04-30 17:29:31 +00003996
3997 // If this is a constraint for a specific physical register, like {r17},
3998 // assign it now.
3999 if (PhysReg.first) {
4000 if (OpInfo.ConstraintVT == MVT::Other)
4001 ValueVT = *PhysReg.second->vt_begin();
4002
4003 // Get the actual register value type. This is important, because the user
4004 // may have asked for (e.g.) the AX register in i32 type. We need to
4005 // remember that AX is actually i16 to get the right extension.
4006 RegVT = *PhysReg.second->vt_begin();
4007
4008 // This is a explicit reference to a physical register.
4009 Regs.push_back(PhysReg.first);
4010
4011 // If this is an expanded reference, add the rest of the regs to Regs.
4012 if (NumRegs != 1) {
4013 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004014 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004015 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004016
4017 // Already added the first reg.
4018 --NumRegs; ++I;
4019 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004020 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004021 Regs.push_back(*I);
4022 }
4023 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004024 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004025 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4026 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004027 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004028 }
4029
4030 // Otherwise, if this was a reference to an LLVM register class, create vregs
4031 // for this reference.
4032 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004033 const TargetRegisterClass *RC = PhysReg.second;
4034 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004035 // If this is an early clobber or tied register, our regalloc doesn't know
4036 // how to maintain the constraint. If it isn't, go ahead and create vreg
4037 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004038 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4039 // If there is some other early clobber and this is an input register,
4040 // then we are forced to pre-allocate the input reg so it doesn't
4041 // conflict with the earlyclobber.
4042 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004043 RegVT = *PhysReg.second->vt_begin();
4044
4045 if (OpInfo.ConstraintVT == MVT::Other)
4046 ValueVT = RegVT;
4047
4048 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004049 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004050 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004051 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004052
Dan Gohman23ce5022008-04-25 18:27:55 +00004053 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004054 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004055 }
4056
4057 // Otherwise, we can't allocate it. Let the code below figure out how to
4058 // maintain these constraints.
4059 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4060
4061 } else {
4062 // This is a reference to a register class that doesn't directly correspond
4063 // to an LLVM register class. Allocate NumRegs consecutive, available,
4064 // registers from the class.
4065 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4066 OpInfo.ConstraintVT);
4067 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004068
Dan Gohman6f0d0242008-02-10 18:45:23 +00004069 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004070 unsigned NumAllocated = 0;
4071 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4072 unsigned Reg = RegClassRegs[i];
4073 // See if this register is available.
4074 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4075 (isInReg && InputRegs.count(Reg))) { // Already used.
4076 // Make sure we find consecutive registers.
4077 NumAllocated = 0;
4078 continue;
4079 }
4080
4081 // Check to see if this register is allocatable (i.e. don't give out the
4082 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004083 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004084 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004085 if (!RC) { // Couldn't allocate this register.
4086 // Reset NumAllocated to make sure we return consecutive registers.
4087 NumAllocated = 0;
4088 continue;
4089 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004090 }
4091
4092 // Okay, this register is good, we can use it.
4093 ++NumAllocated;
4094
4095 // If we allocated enough consecutive registers, succeed.
4096 if (NumAllocated == NumRegs) {
4097 unsigned RegStart = (i-NumAllocated)+1;
4098 unsigned RegEnd = i+1;
4099 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004100 for (unsigned i = RegStart; i != RegEnd; ++i)
4101 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004102
Dan Gohman23ce5022008-04-25 18:27:55 +00004103 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004104 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004105 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004106 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004107 }
4108 }
4109
4110 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004111}
4112
4113
Chris Lattnerce7518c2006-01-26 22:24:51 +00004114/// visitInlineAsm - Handle a call to an InlineAsm object.
4115///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004116void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4117 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004118
Chris Lattner0c583402007-04-28 20:49:53 +00004119 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004120 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004121
4122 SDOperand Chain = getRoot();
4123 SDOperand Flag;
4124
Chris Lattner4e4b5762006-02-01 18:59:47 +00004125 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004126
Chris Lattner0c583402007-04-28 20:49:53 +00004127 // Do a prepass over the constraints, canonicalizing them, and building up the
4128 // ConstraintOperands list.
4129 std::vector<InlineAsm::ConstraintInfo>
4130 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004131
4132 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4133 // constraint. If so, we can't let the register allocator allocate any input
4134 // registers, because it will not know to avoid the earlyclobbered output reg.
4135 bool SawEarlyClobber = false;
4136
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004137 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004138 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004139 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004140 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4141 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004142
Duncan Sands83ec4b62008-06-06 12:08:01 +00004143 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004144
4145 // Compute the value type for each operand.
4146 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004147 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004148 // Indirect outputs just consume an argument.
4149 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004150 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004151 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004152 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004153 // The return value of the call is this value. As such, there is no
4154 // corresponding argument.
4155 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4156 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4157 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4158 } else {
4159 assert(ResNo == 0 && "Asm only has one result!");
4160 OpVT = TLI.getValueType(CS.getType());
4161 }
4162 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004163 break;
4164 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004165 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004166 break;
4167 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004168 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004169 break;
4170 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004171
Chris Lattner0c583402007-04-28 20:49:53 +00004172 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004173 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004174 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004175 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4176 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004177 else {
4178 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4179 const Type *OpTy = OpInfo.CallOperandVal->getType();
4180 // If this is an indirect operand, the operand is a pointer to the
4181 // accessed type.
4182 if (OpInfo.isIndirect)
4183 OpTy = cast<PointerType>(OpTy)->getElementType();
4184
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004185 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004186 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004187 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004188 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4189 switch (BitSize) {
4190 default: break;
4191 case 1:
4192 case 8:
4193 case 16:
4194 case 32:
4195 case 64:
4196 OpTy = IntegerType::get(BitSize);
4197 break;
4198 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004199 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004200
4201 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004202 }
4203 }
4204
4205 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004206
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004207 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004208 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004209
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004210 // Keep track of whether we see an earlyclobber.
4211 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004212
Chris Lattner0fe71e92008-02-21 19:43:13 +00004213 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004214 if (!SawEarlyClobber &&
4215 OpInfo.Type == InlineAsm::isClobber &&
4216 OpInfo.ConstraintType == TargetLowering::C_Register) {
4217 // Note that we want to ignore things that we don't trick here, like
4218 // dirflag, fpsr, flags, etc.
4219 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4220 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4221 OpInfo.ConstraintVT);
4222 if (PhysReg.first || PhysReg.second) {
4223 // This is a register we know of.
4224 SawEarlyClobber = true;
4225 }
4226 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004227
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004228 // If this is a memory input, and if the operand is not indirect, do what we
4229 // need to to provide an address for the memory input.
4230 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4231 !OpInfo.isIndirect) {
4232 assert(OpInfo.Type == InlineAsm::isInput &&
4233 "Can only indirectify direct input operands!");
4234
4235 // Memory operands really want the address of the value. If we don't have
4236 // an indirect input, put it in the constpool if we can, otherwise spill
4237 // it to a stack slot.
4238
4239 // If the operand is a float, integer, or vector constant, spill to a
4240 // constant pool entry to get its address.
4241 Value *OpVal = OpInfo.CallOperandVal;
4242 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4243 isa<ConstantVector>(OpVal)) {
4244 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4245 TLI.getPointerTy());
4246 } else {
4247 // Otherwise, create a stack slot and emit a store to it before the
4248 // asm.
4249 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004250 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004251 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4252 MachineFunction &MF = DAG.getMachineFunction();
4253 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4254 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4255 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4256 OpInfo.CallOperand = StackSlot;
4257 }
4258
4259 // There is no longer a Value* corresponding to this operand.
4260 OpInfo.CallOperandVal = 0;
4261 // It is now an indirect operand.
4262 OpInfo.isIndirect = true;
4263 }
4264
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004265 // If this constraint is for a specific register, allocate it before
4266 // anything else.
4267 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4268 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004269 }
Chris Lattner0c583402007-04-28 20:49:53 +00004270 ConstraintInfos.clear();
4271
4272
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004273 // Second pass - Loop over all of the operands, assigning virtual or physregs
4274 // to registerclass operands.
4275 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004276 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004277
4278 // C_Register operands have already been allocated, Other/Memory don't need
4279 // to be.
4280 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4281 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4282 }
4283
Chris Lattner0c583402007-04-28 20:49:53 +00004284 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4285 std::vector<SDOperand> AsmNodeOperands;
4286 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4287 AsmNodeOperands.push_back(
4288 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4289
Chris Lattner2cc2f662006-02-01 01:28:23 +00004290
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004291 // Loop over all of the inputs, copying the operand values into the
4292 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004293 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004294
Chris Lattner0c583402007-04-28 20:49:53 +00004295 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4296 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4297
4298 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004299 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004300
Chris Lattner0c583402007-04-28 20:49:53 +00004301 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004302 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004303 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4304 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004305 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004306 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004307
Chris Lattner22873462006-02-27 23:45:39 +00004308 // Add information to the INLINEASM node to know about this output.
4309 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004310 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4311 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004312 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004313 break;
4314 }
4315
Chris Lattner2a600be2007-04-28 21:01:43 +00004316 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004317
Chris Lattner864635a2006-02-22 22:37:12 +00004318 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004319 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004320 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004321 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004322 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004323 exit(1);
4324 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004325
Chris Lattner41f62592008-04-29 04:29:54 +00004326 // If this is an indirect operand, store through the pointer after the
4327 // asm.
4328 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004329 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004330 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004331 } else {
4332 // This is the result value of the call.
4333 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4334 // Concatenate this output onto the outputs list.
4335 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004336 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004337
4338 // Add information to the INLINEASM node to know that this register is
4339 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004340 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4341 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004342 break;
4343 }
4344 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004345 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004346
Chris Lattner0c583402007-04-28 20:49:53 +00004347 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004348 // If this is required to match an output register we have already set,
4349 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004350 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004351
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004352 // Scan until we find the definition we already emitted of this operand.
4353 // When we find it, create a RegsForValue operand.
4354 unsigned CurOp = 2; // The first operand.
4355 for (; OperandNo; --OperandNo) {
4356 // Advance to the next operand.
4357 unsigned NumOps =
4358 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004359 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4360 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004361 "Skipped past definitions?");
4362 CurOp += (NumOps>>3)+1;
4363 }
4364
4365 unsigned NumOps =
4366 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004367 if ((NumOps & 7) == 2 /*REGDEF*/) {
4368 // Add NumOps>>3 registers to MatchedRegs.
4369 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004370 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004371 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4372 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004373 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4374 unsigned Reg =
4375 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4376 MatchedRegs.Regs.push_back(Reg);
4377 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004378
Chris Lattner527fae12007-02-01 01:21:12 +00004379 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004380 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004381 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4382 break;
4383 } else {
4384 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004385 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4386 // Add information to the INLINEASM node to know about this input.
4387 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4388 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4389 TLI.getPointerTy()));
4390 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4391 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004392 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004393 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004394
Chris Lattner2a600be2007-04-28 21:01:43 +00004395 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004396 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004397 "Don't know how to handle indirect other inputs yet!");
4398
Chris Lattner48884cd2007-08-25 00:47:38 +00004399 std::vector<SDOperand> Ops;
4400 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4401 Ops, DAG);
4402 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004403 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004404 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004405 exit(1);
4406 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004407
4408 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004409 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004410 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4411 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004412 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004413 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004414 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004415 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004416 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4417 "Memory operands expect pointer values");
4418
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004419 // Add information to the INLINEASM node to know about this input.
4420 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004421 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4422 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004423 AsmNodeOperands.push_back(InOperandVal);
4424 break;
4425 }
4426
Chris Lattner2a600be2007-04-28 21:01:43 +00004427 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4428 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4429 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004430 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004431 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004432
4433 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004434 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4435 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004436
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004437 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004438
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004439 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4440 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004441 break;
4442 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004443 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004444 // Add the clobbered value to the operand list, so that the register
4445 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004446 if (!OpInfo.AssignedRegs.Regs.empty())
4447 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4448 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004449 break;
4450 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004451 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004452 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004453
4454 // Finish up input operands.
4455 AsmNodeOperands[0] = Chain;
4456 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4457
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004458 Chain = DAG.getNode(ISD::INLINEASM,
4459 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004460 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004461 Flag = Chain.getValue(1);
4462
Chris Lattner6656dd12006-01-31 02:03:41 +00004463 // If this asm returns a register value, copy the result from that register
4464 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004465 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004466 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004467
4468 // If any of the results of the inline asm is a vector, it may have the
4469 // wrong width/num elts. This can happen for register classes that can
4470 // contain multiple different value types. The preg or vreg allocated may
4471 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004472 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004473 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4474 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004475 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004476 Val = DAG.getNode(ISD::BIT_CONVERT,
4477 TLI.getValueType(ResSTy->getElementType(i)), Val);
4478 }
4479 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004480 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004481 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4482 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004483 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004484
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004485 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004486 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004487
Chris Lattner6656dd12006-01-31 02:03:41 +00004488 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4489
4490 // Process indirect outputs, first output all of the flagged copies out of
4491 // physregs.
4492 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004493 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004494 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004495 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004496 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004497 }
4498
4499 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004500 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004501 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004502 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004503 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004504 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004505 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004506 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4507 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004508 DAG.setRoot(Chain);
4509}
4510
4511
Chris Lattner1c08c712005-01-07 07:47:53 +00004512void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4513 SDOperand Src = getValue(I.getOperand(0));
4514
Duncan Sands83ec4b62008-06-06 12:08:01 +00004515 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004516
Duncan Sands8e4eb092008-06-08 20:54:56 +00004517 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004518 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004519 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004520 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004521
4522 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004523 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004524 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004525 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004526
Reid Spencer47857812006-12-31 05:55:36 +00004527 TargetLowering::ArgListTy Args;
4528 TargetLowering::ArgListEntry Entry;
4529 Entry.Node = Src;
4530 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004531 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004532
4533 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004534 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4535 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004536 setValue(&I, Result.first); // Pointers always fit in registers
4537 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004538}
4539
4540void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004541 TargetLowering::ArgListTy Args;
4542 TargetLowering::ArgListEntry Entry;
4543 Entry.Node = getValue(I.getOperand(0));
4544 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004545 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004546 MVT IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004547 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004548 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4549 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004550 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4551 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004552}
4553
Evan Chengff9b3732008-01-30 18:18:23 +00004554// EmitInstrWithCustomInserter - This method should be implemented by targets
4555// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004556// instructions are special in various ways, which require special support to
4557// insert. The specified MachineInstr is created but not inserted into any
4558// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004559MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004560 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004561 cerr << "If a target marks an instruction with "
4562 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004563 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004564 abort();
4565 return 0;
4566}
4567
Chris Lattner39ae3622005-01-09 00:00:49 +00004568void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004569 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4570 getValue(I.getOperand(1)),
4571 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004572}
4573
4574void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004575 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4576 getValue(I.getOperand(0)),
4577 DAG.getSrcValue(I.getOperand(0)));
4578 setValue(&I, V);
4579 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004580}
4581
4582void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004583 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4584 getValue(I.getOperand(1)),
4585 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004586}
4587
4588void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004589 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4590 getValue(I.getOperand(1)),
4591 getValue(I.getOperand(2)),
4592 DAG.getSrcValue(I.getOperand(1)),
4593 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004594}
4595
Chris Lattnerfdfded52006-04-12 16:20:43 +00004596/// TargetLowering::LowerArguments - This is the default LowerArguments
4597/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004598/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4599/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004600void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4601 SmallVectorImpl<SDOperand> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004602 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohmana44b6742008-06-30 20:31:15 +00004603 SmallVector<SDOperand, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004604 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004605 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4606 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4607
4608 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004609 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004610 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004611 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4612 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004613 SmallVector<MVT, 4> ValueVTs;
4614 ComputeValueVTs(*this, I->getType(), ValueVTs);
4615 for (unsigned Value = 0, NumValues = ValueVTs.size();
4616 Value != NumValues; ++Value) {
4617 MVT VT = ValueVTs[Value];
4618 const Type *ArgTy = VT.getTypeForMVT();
4619 ISD::ArgFlagsTy Flags;
4620 unsigned OriginalAlignment =
4621 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004622
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004623 if (F.paramHasAttr(j, ParamAttr::ZExt))
4624 Flags.setZExt();
4625 if (F.paramHasAttr(j, ParamAttr::SExt))
4626 Flags.setSExt();
4627 if (F.paramHasAttr(j, ParamAttr::InReg))
4628 Flags.setInReg();
4629 if (F.paramHasAttr(j, ParamAttr::StructRet))
4630 Flags.setSRet();
4631 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4632 Flags.setByVal();
4633 const PointerType *Ty = cast<PointerType>(I->getType());
4634 const Type *ElementTy = Ty->getElementType();
4635 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4636 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4637 // For ByVal, alignment should be passed from FE. BE will guess if
4638 // this info is not there but there are cases it cannot get right.
4639 if (F.getParamAlignment(j))
4640 FrameAlign = F.getParamAlignment(j);
4641 Flags.setByValAlign(FrameAlign);
4642 Flags.setByValSize(FrameSize);
4643 }
4644 if (F.paramHasAttr(j, ParamAttr::Nest))
4645 Flags.setNest();
4646 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004647
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004648 MVT RegisterVT = getRegisterType(VT);
4649 unsigned NumRegs = getNumRegisters(VT);
4650 for (unsigned i = 0; i != NumRegs; ++i) {
4651 RetVals.push_back(RegisterVT);
4652 ISD::ArgFlagsTy MyFlags = Flags;
4653 if (NumRegs > 1 && i == 0)
4654 MyFlags.setSplit();
4655 // if it isn't first piece, alignment must be 1
4656 else if (i > 0)
4657 MyFlags.setOrigAlign(1);
4658 Ops.push_back(DAG.getArgFlags(MyFlags));
4659 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004660 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004661 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004662
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004663 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004664
4665 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004666 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004667 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004668 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004669
4670 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4671 // allows exposing the loads that may be part of the argument access to the
4672 // first DAGCombiner pass.
4673 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4674
4675 // The number of results should match up, except that the lowered one may have
4676 // an extra flag result.
4677 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4678 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4679 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4680 && "Lowering produced unexpected number of results!");
4681 Result = TmpRes.Val;
4682
Dan Gohman27a70be2007-07-02 16:18:06 +00004683 unsigned NumArgRegs = Result->getNumValues() - 1;
4684 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004685
4686 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004687 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004688 unsigned Idx = 1;
4689 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4690 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004691 SmallVector<MVT, 4> ValueVTs;
4692 ComputeValueVTs(*this, I->getType(), ValueVTs);
4693 for (unsigned Value = 0, NumValues = ValueVTs.size();
4694 Value != NumValues; ++Value) {
4695 MVT VT = ValueVTs[Value];
4696 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004697
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004698 unsigned NumParts = getNumRegisters(VT);
4699 SmallVector<SDOperand, 4> Parts(NumParts);
4700 for (unsigned j = 0; j != NumParts; ++j)
4701 Parts[j] = SDOperand(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004702
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004703 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4704 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4705 AssertOp = ISD::AssertSext;
4706 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4707 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004708
Dan Gohmana44b6742008-06-30 20:31:15 +00004709 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4710 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004711 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004712 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004713 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004714}
4715
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004716
4717/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4718/// implementation, which just inserts an ISD::CALL node, which is later custom
4719/// lowered by the target to something concrete. FIXME: When all targets are
4720/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4721std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004722TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4723 bool RetSExt, bool RetZExt, bool isVarArg,
4724 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004725 SDOperand Callee,
4726 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004727 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004728 Ops.push_back(Chain); // Op#0 - Chain
4729 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4730 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4731 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4732 Ops.push_back(Callee);
4733
4734 // Handle all of the outgoing arguments.
4735 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004736 SmallVector<MVT, 4> ValueVTs;
4737 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4738 for (unsigned Value = 0, NumValues = ValueVTs.size();
4739 Value != NumValues; ++Value) {
4740 MVT VT = ValueVTs[Value];
4741 const Type *ArgTy = VT.getTypeForMVT();
4742 SDOperand Op = SDOperand(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4743 ISD::ArgFlagsTy Flags;
4744 unsigned OriginalAlignment =
4745 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004746
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004747 if (Args[i].isZExt)
4748 Flags.setZExt();
4749 if (Args[i].isSExt)
4750 Flags.setSExt();
4751 if (Args[i].isInReg)
4752 Flags.setInReg();
4753 if (Args[i].isSRet)
4754 Flags.setSRet();
4755 if (Args[i].isByVal) {
4756 Flags.setByVal();
4757 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4758 const Type *ElementTy = Ty->getElementType();
4759 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4760 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4761 // For ByVal, alignment should come from FE. BE will guess if this
4762 // info is not there but there are cases it cannot get right.
4763 if (Args[i].Alignment)
4764 FrameAlign = Args[i].Alignment;
4765 Flags.setByValAlign(FrameAlign);
4766 Flags.setByValSize(FrameSize);
4767 }
4768 if (Args[i].isNest)
4769 Flags.setNest();
4770 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004771
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004772 MVT PartVT = getRegisterType(VT);
4773 unsigned NumParts = getNumRegisters(VT);
4774 SmallVector<SDOperand, 4> Parts(NumParts);
4775 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004776
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004777 if (Args[i].isSExt)
4778 ExtendKind = ISD::SIGN_EXTEND;
4779 else if (Args[i].isZExt)
4780 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004781
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004782 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004783
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004784 for (unsigned i = 0; i != NumParts; ++i) {
4785 // if it isn't first piece, alignment must be 1
4786 ISD::ArgFlagsTy MyFlags = Flags;
4787 if (NumParts > 1 && i == 0)
4788 MyFlags.setSplit();
4789 else if (i != 0)
4790 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004791
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004792 Ops.push_back(Parts[i]);
4793 Ops.push_back(DAG.getArgFlags(MyFlags));
4794 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004795 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004796 }
4797
Dan Gohmanef5d1942008-03-11 21:11:25 +00004798 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004799 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004800 SmallVector<MVT, 4> LoweredRetTys;
4801 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004802 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004803
Dan Gohman23ce5022008-04-25 18:27:55 +00004804 // Then we translate that to a list of legal types.
4805 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004806 MVT VT = RetTys[I];
4807 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004808 unsigned NumRegs = getNumRegisters(VT);
4809 for (unsigned i = 0; i != NumRegs; ++i)
4810 LoweredRetTys.push_back(RegisterVT);
4811 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004812
Dan Gohmanef5d1942008-03-11 21:11:25 +00004813 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004814
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004815 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004816 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004817 DAG.getVTList(&LoweredRetTys[0],
4818 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004819 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004820 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004821
4822 // Gather up the call result into a single value.
4823 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004824 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4825
4826 if (RetSExt)
4827 AssertOp = ISD::AssertSext;
4828 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004829 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004830
Dan Gohmanef5d1942008-03-11 21:11:25 +00004831 SmallVector<SDOperand, 4> ReturnValues;
4832 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004833 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004834 MVT VT = RetTys[I];
4835 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004836 unsigned NumRegs = getNumRegisters(VT);
4837 unsigned RegNoEnd = NumRegs + RegNo;
4838 SmallVector<SDOperand, 4> Results;
4839 for (; RegNo != RegNoEnd; ++RegNo)
4840 Results.push_back(Res.getValue(RegNo));
4841 SDOperand ReturnValue =
4842 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4843 AssertOp);
4844 ReturnValues.push_back(ReturnValue);
4845 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004846 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4847 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004848 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004849
4850 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004851}
4852
Chris Lattner50381b62005-05-14 05:50:48 +00004853SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004854 assert(0 && "LowerOperation not implemented for this target!");
4855 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004856 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004857}
4858
Nate Begeman0aed7842006-01-28 03:14:31 +00004859SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4860 SelectionDAG &DAG) {
4861 assert(0 && "CustomPromoteOperation not implemented for this target!");
4862 abort();
4863 return SDOperand();
4864}
4865
Chris Lattner7041ee32005-01-11 05:56:49 +00004866//===----------------------------------------------------------------------===//
4867// SelectionDAGISel code
4868//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004869
Duncan Sands83ec4b62008-06-06 12:08:01 +00004870unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004871 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004872}
4873
Chris Lattner495a0b52005-08-17 06:37:43 +00004874void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004875 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004876 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004877 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004878}
Chris Lattner1c08c712005-01-07 07:47:53 +00004879
Chris Lattner1c08c712005-01-07 07:47:53 +00004880bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004881 // Get alias analysis for load/store combining.
4882 AA = &getAnalysis<AliasAnalysis>();
4883
Chris Lattner1c08c712005-01-07 07:47:53 +00004884 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004885 if (MF.getFunction()->hasCollector())
4886 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4887 else
4888 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004889 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004890 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004891
4892 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4893
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004894 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4895 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4896 // Mark landing pad.
4897 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004898
4899 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004900 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004901
Evan Chengad2070c2007-02-10 02:43:39 +00004902 // Add function live-ins to entry block live-in set.
4903 BasicBlock *EntryBB = &Fn.getEntryBlock();
4904 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004905 if (!RegInfo->livein_empty())
4906 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4907 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004908 BB->addLiveIn(I->first);
4909
Duncan Sandsf4070822007-06-15 19:04:19 +00004910#ifndef NDEBUG
4911 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4912 "Not all catch info was assigned to a landing pad!");
4913#endif
4914
Chris Lattner1c08c712005-01-07 07:47:53 +00004915 return true;
4916}
4917
Chris Lattner6833b062008-04-28 07:16:35 +00004918void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004919 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004920 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004921 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004922 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004923 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004924
Dan Gohman23ce5022008-04-25 18:27:55 +00004925 RegsForValue RFV(TLI, Reg, V->getType());
4926 SDOperand Chain = DAG.getEntryNode();
4927 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4928 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004929}
4930
Chris Lattner068a81e2005-01-17 17:15:02 +00004931void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004932LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004933 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004934 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004935 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004936 SDOperand OldRoot = SDL.DAG.getRoot();
Dan Gohmana44b6742008-06-30 20:31:15 +00004937 SmallVector<SDOperand, 16> Args;
4938 TLI.LowerArguments(F, SDL.DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00004939
Chris Lattnerbf209482005-10-30 19:42:35 +00004940 unsigned a = 0;
4941 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004942 AI != E; ++AI) {
4943 SmallVector<MVT, 4> ValueVTs;
4944 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4945 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004946 if (!AI->use_empty()) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004947 SmallVector<MVT, 4> LegalValueVTs(NumValues);
4948 for (unsigned VI = 0; VI != NumValues; ++VI)
4949 LegalValueVTs[VI] = Args[a + VI].getValueType();
Duncan Sandsf9516202008-06-30 10:19:09 +00004950 SDL.setValue(AI,
4951 SDL.DAG.getMergeValues(SDL.DAG.getVTList(&LegalValueVTs[0],
4952 NumValues),
4953 &Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004954 // If this argument is live outside of the entry block, insert a copy from
4955 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004956 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4957 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004958 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004959 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004960 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004961 a += NumValues;
4962 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004963
Chris Lattnerbf209482005-10-30 19:42:35 +00004964 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004965 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004966 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004967}
4968
Duncan Sandsf4070822007-06-15 19:04:19 +00004969static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4970 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004971 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004972 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004973 // Apply the catch info to DestBB.
4974 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4975#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004976 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4977 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004978#endif
4979 }
4980}
4981
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004982/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4983/// whether object offset >= 0.
4984static bool
4985IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4986 if (!isa<FrameIndexSDNode>(Op)) return false;
4987
4988 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4989 int FrameIdx = FrameIdxNode->getIndex();
4990 return MFI->isFixedObjectIndex(FrameIdx) &&
4991 MFI->getObjectOffset(FrameIdx) >= 0;
4992}
4993
4994/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4995/// possibly be overwritten when lowering the outgoing arguments in a tail
4996/// call. Currently the implementation of this call is very conservative and
4997/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4998/// virtual registers would be overwritten by direct lowering.
4999static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
5000 MachineFrameInfo * MFI) {
5001 RegisterSDNode * OpReg = NULL;
5002 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5003 (Op.getOpcode()== ISD::CopyFromReg &&
5004 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5005 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5006 (Op.getOpcode() == ISD::LOAD &&
5007 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5008 (Op.getOpcode() == ISD::MERGE_VALUES &&
5009 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5010 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5011 getOperand(1))))
5012 return true;
5013 return false;
5014}
5015
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005016/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005017/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005018static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5019 TargetLowering& TLI) {
5020 SDNode * Ret = NULL;
5021 SDOperand Terminator = DAG.getRoot();
5022
5023 // Find RET node.
5024 if (Terminator.getOpcode() == ISD::RET) {
5025 Ret = Terminator.Val;
5026 }
5027
5028 // Fix tail call attribute of CALL nodes.
5029 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
5030 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
5031 if (BI->getOpcode() == ISD::CALL) {
5032 SDOperand OpRet(Ret, 0);
5033 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
5034 bool isMarkedTailCall =
5035 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5036 // If CALL node has tail call attribute set to true and the call is not
5037 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005038 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005039 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005040 if (!isMarkedTailCall) continue;
5041 if (Ret==NULL ||
5042 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5043 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005044 SmallVector<SDOperand, 32> Ops;
5045 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005046 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5047 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005048 if (idx!=3)
5049 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005050 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005051 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5052 }
5053 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005054 } else {
5055 // Look for tail call clobbered arguments. Emit a series of
5056 // copyto/copyfrom virtual register nodes to protect them.
5057 SmallVector<SDOperand, 32> Ops;
5058 SDOperand Chain = OpCall.getOperand(0), InFlag;
5059 unsigned idx=0;
5060 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5061 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5062 SDOperand Arg = *I;
5063 if (idx > 4 && (idx % 2)) {
5064 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5065 getArgFlags().isByVal();
5066 MachineFunction &MF = DAG.getMachineFunction();
5067 MachineFrameInfo *MFI = MF.getFrameInfo();
5068 if (!isByVal &&
5069 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005070 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005071 unsigned VReg = MF.getRegInfo().
5072 createVirtualRegister(TLI.getRegClassFor(VT));
5073 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5074 InFlag = Chain.getValue(1);
5075 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5076 Chain = Arg.getValue(1);
5077 InFlag = Arg.getValue(2);
5078 }
5079 }
5080 Ops.push_back(Arg);
5081 }
5082 // Link in chain of CopyTo/CopyFromReg.
5083 Ops[0] = Chain;
5084 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005085 }
5086 }
5087 }
5088}
5089
Chris Lattner1c08c712005-01-07 07:47:53 +00005090void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5091 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00005092 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00005093 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00005094
Chris Lattnerbf209482005-10-30 19:42:35 +00005095 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005096 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005097 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00005098
5099 BB = FuncInfo.MBBMap[LLVMBB];
5100 SDL.setCurrentBasicBlock(BB);
5101
Duncan Sandsf4070822007-06-15 19:04:19 +00005102 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005103
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005104 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005105 // Add a label to mark the beginning of the landing pad. Deletion of the
5106 // landing pad can thus be detected via the MachineModuleInfo.
5107 unsigned LabelID = MMI->addLandingPad(BB);
Dan Gohman44066042008-07-01 00:05:16 +00005108 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
Duncan Sandsf4070822007-06-15 19:04:19 +00005109
Evan Chenge47c3332007-06-27 18:45:32 +00005110 // Mark exception register as live in.
5111 unsigned Reg = TLI.getExceptionAddressRegister();
5112 if (Reg) BB->addLiveIn(Reg);
5113
5114 // Mark exception selector register as live in.
5115 Reg = TLI.getExceptionSelectorRegister();
5116 if (Reg) BB->addLiveIn(Reg);
5117
Duncan Sandsf4070822007-06-15 19:04:19 +00005118 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5119 // function and list of typeids logically belong to the invoke (or, if you
5120 // like, the basic block containing the invoke), and need to be associated
5121 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005122 // information is provided by an intrinsic (eh.selector) that can be moved
5123 // to unexpected places by the optimizers: if the unwind edge is critical,
5124 // then breaking it can result in the intrinsics being in the successor of
5125 // the landing pad, not the landing pad itself. This results in exceptions
5126 // not being caught because no typeids are associated with the invoke.
5127 // This may not be the only way things can go wrong, but it is the only way
5128 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00005129 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5130
5131 if (Br && Br->isUnconditional()) { // Critical edge?
5132 BasicBlock::iterator I, E;
5133 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005134 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00005135 break;
5136
5137 if (I == E)
5138 // No catch info found - try to extract some from the successor.
5139 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00005140 }
5141 }
5142
Chris Lattner1c08c712005-01-07 07:47:53 +00005143 // Lower all of the non-terminator instructions.
5144 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5145 I != E; ++I)
5146 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005147
Chris Lattner1c08c712005-01-07 07:47:53 +00005148 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005149 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00005150 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005151 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00005152 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00005153 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005154 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00005155 }
5156
5157 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5158 // ensure constants are generated when needed. Remember the virtual registers
5159 // that need to be added to the Machine PHI nodes as input. We cannot just
5160 // directly add them, because expansion might result in multiple MBB's for one
5161 // BB. As such, the start of the BB might correspond to a different MBB than
5162 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00005163 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00005164 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005165
5166 // Emit constants only once even if used by multiple PHI nodes.
5167 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005168
Chris Lattner8c494ab2006-10-27 23:50:33 +00005169 // Vector bool would be better, but vector<bool> is really slow.
5170 std::vector<unsigned char> SuccsHandled;
5171 if (TI->getNumSuccessors())
5172 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5173
Dan Gohman532dc2e2007-07-09 20:59:04 +00005174 // Check successor nodes' PHI nodes that expect a constant to be available
5175 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005176 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5177 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005178 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005179 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005180
Chris Lattner8c494ab2006-10-27 23:50:33 +00005181 // If this terminator has multiple identical successors (common for
5182 // switches), only handle each succ once.
5183 unsigned SuccMBBNo = SuccMBB->getNumber();
5184 if (SuccsHandled[SuccMBBNo]) continue;
5185 SuccsHandled[SuccMBBNo] = true;
5186
5187 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005188 PHINode *PN;
5189
5190 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5191 // nodes and Machine PHI nodes, but the incoming operands have not been
5192 // emitted yet.
5193 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005194 (PN = dyn_cast<PHINode>(I)); ++I) {
5195 // Ignore dead phi's.
5196 if (PN->use_empty()) continue;
5197
5198 unsigned Reg;
5199 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005200
Chris Lattner8c494ab2006-10-27 23:50:33 +00005201 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5202 unsigned &RegOut = ConstantsOut[C];
5203 if (RegOut == 0) {
5204 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005205 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005206 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005207 Reg = RegOut;
5208 } else {
5209 Reg = FuncInfo.ValueMap[PHIOp];
5210 if (Reg == 0) {
5211 assert(isa<AllocaInst>(PHIOp) &&
5212 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5213 "Didn't codegen value into a register!??");
5214 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005215 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005216 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005217 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005218
5219 // Remember that this register needs to added to the machine PHI node as
5220 // the input for this MBB.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005221 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00005222 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00005223 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00005224 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5225 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005226 }
5227 ConstantsOut.clear();
5228
5229 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005230 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005231
Nate Begemanf15485a2006-03-27 01:32:24 +00005232 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005233 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005234 SwitchCases.clear();
5235 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005236 JTCases.clear();
5237 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005238 BitTestCases.clear();
5239 BitTestCases = SDL.BitTestCases;
5240
Chris Lattnera651cf62005-01-17 19:43:36 +00005241 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005242 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005243
5244 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5245 // with correct tailcall attribute so that the target can rely on the tailcall
5246 // attribute indicating whether the call is really eligible for tail call
5247 // optimization.
5248 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00005249}
5250
Chris Lattneread0d882008-06-17 06:09:18 +00005251void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5252 SmallPtrSet<SDNode*, 128> VisitedNodes;
5253 SmallVector<SDNode*, 128> Worklist;
5254
5255 Worklist.push_back(DAG.getRoot().Val);
5256
5257 APInt Mask;
5258 APInt KnownZero;
5259 APInt KnownOne;
5260
5261 while (!Worklist.empty()) {
5262 SDNode *N = Worklist.back();
5263 Worklist.pop_back();
5264
5265 // If we've already seen this node, ignore it.
5266 if (!VisitedNodes.insert(N))
5267 continue;
5268
5269 // Otherwise, add all chain operands to the worklist.
5270 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5271 if (N->getOperand(i).getValueType() == MVT::Other)
5272 Worklist.push_back(N->getOperand(i).Val);
5273
5274 // If this is a CopyToReg with a vreg dest, process it.
5275 if (N->getOpcode() != ISD::CopyToReg)
5276 continue;
5277
5278 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5279 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5280 continue;
5281
5282 // Ignore non-scalar or non-integer values.
5283 SDOperand Src = N->getOperand(2);
5284 MVT SrcVT = Src.getValueType();
5285 if (!SrcVT.isInteger() || SrcVT.isVector())
5286 continue;
5287
5288 unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5289 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5290 DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5291
5292 // Only install this information if it tells us something.
5293 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5294 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5295 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5296 if (DestReg >= FLI.LiveOutRegInfo.size())
5297 FLI.LiveOutRegInfo.resize(DestReg+1);
5298 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5299 LOI.NumSignBits = NumSignBits;
5300 LOI.KnownOne = NumSignBits;
5301 LOI.KnownZero = NumSignBits;
5302 }
5303 }
5304}
5305
Nate Begemanf15485a2006-03-27 01:32:24 +00005306void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00005307 DOUT << "Lowered selection DAG:\n";
5308 DEBUG(DAG.dump());
5309
Chris Lattneraf21d552005-10-10 16:47:10 +00005310 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005311 if (TimePassesIsEnabled) {
5312 NamedRegionTimer T("DAG Combining 1");
5313 DAG.Combine(false, *AA);
5314 } else {
5315 DAG.Combine(false, *AA);
5316 }
Nate Begeman2300f552005-09-07 00:15:36 +00005317
Dan Gohman417e11b2007-10-08 15:12:17 +00005318 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005319 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005320
Chris Lattner1c08c712005-01-07 07:47:53 +00005321 // Second step, hack on the DAG until it only uses operations and types that
5322 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00005323#if 0 // Enable this some day.
5324 DAG.LegalizeTypes();
5325 // Someday even later, enable a dag combine pass here.
5326#endif
Evan Chengebffb662008-07-01 17:59:20 +00005327 if (TimePassesIsEnabled) {
5328 NamedRegionTimer T("DAG Legalization");
5329 DAG.Legalize();
5330 } else {
5331 DAG.Legalize();
5332 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005333
Bill Wendling832171c2006-12-07 20:04:42 +00005334 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005335 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005336
Chris Lattneraf21d552005-10-10 16:47:10 +00005337 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005338 if (TimePassesIsEnabled) {
5339 NamedRegionTimer T("DAG Combining 2");
5340 DAG.Combine(true, *AA);
5341 } else {
5342 DAG.Combine(true, *AA);
5343 }
Nate Begeman2300f552005-09-07 00:15:36 +00005344
Dan Gohman417e11b2007-10-08 15:12:17 +00005345 DOUT << "Optimized legalized selection DAG:\n";
5346 DEBUG(DAG.dump());
5347
Evan Chenga9c20912006-01-21 02:32:06 +00005348 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattneread0d882008-06-17 06:09:18 +00005349
5350 if (EnableValueProp) // FIXME: Only do this if !fast.
5351 ComputeLiveOutVRegInfo(DAG);
Evan Cheng552c4a82006-04-28 02:09:19 +00005352
Chris Lattnera33ef482005-03-30 01:10:47 +00005353 // Third, instruction select all of the operations to machine code, adding the
5354 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005355 if (TimePassesIsEnabled) {
5356 NamedRegionTimer T("Instruction Selection");
5357 InstructionSelect(DAG);
5358 } else {
5359 InstructionSelect(DAG);
5360 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005361
5362 // Emit machine code to BB. This can change 'BB' to the last block being
5363 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005364 if (TimePassesIsEnabled) {
5365 NamedRegionTimer T("Instruction Scheduling");
5366 ScheduleAndEmitDAG(DAG);
5367 } else {
5368 ScheduleAndEmitDAG(DAG);
5369 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005370
5371 // Perform target specific isel post processing.
Evan Chengebffb662008-07-01 17:59:20 +00005372 if (TimePassesIsEnabled) {
5373 NamedRegionTimer T("Instruction Selection Post Processing");
5374 InstructionSelectPostProcessing(DAG);
5375 } else {
5376 InstructionSelectPostProcessing(DAG);
5377 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005378
Bill Wendling832171c2006-12-07 20:04:42 +00005379 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005380 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005381}
Chris Lattner1c08c712005-01-07 07:47:53 +00005382
Nate Begemanf15485a2006-03-27 01:32:24 +00005383void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5384 FunctionLoweringInfo &FuncInfo) {
5385 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5386 {
Chris Lattneread0d882008-06-17 06:09:18 +00005387 SelectionDAG DAG(TLI, MF, FuncInfo,
5388 getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005389 CurDAG = &DAG;
5390
5391 // First step, lower LLVM code to some DAG. This DAG may use operations and
5392 // types that are not supported by the target.
5393 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5394
5395 // Second step, emit the lowered DAG as machine code.
5396 CodeGenAndEmitDAG(DAG);
5397 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005398
5399 DOUT << "Total amount of phi nodes to update: "
5400 << PHINodesToUpdate.size() << "\n";
5401 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5402 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5403 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005404
Chris Lattnera33ef482005-03-30 01:10:47 +00005405 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005406 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005407 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005408 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5409 MachineInstr *PHI = PHINodesToUpdate[i].first;
5410 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5411 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005412 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5413 false));
5414 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005415 }
5416 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005417 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005418
5419 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5420 // Lower header first, if it wasn't already lowered
5421 if (!BitTestCases[i].Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005422 SelectionDAG HSDAG(TLI, MF, FuncInfo,
5423 getAnalysisToUpdate<MachineModuleInfo>());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005424 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005425 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005426 // Set the current basic block to the mbb we wish to insert the code into
5427 BB = BitTestCases[i].Parent;
5428 HSDL.setCurrentBasicBlock(BB);
5429 // Emit the code
5430 HSDL.visitBitTestHeader(BitTestCases[i]);
5431 HSDAG.setRoot(HSDL.getRoot());
5432 CodeGenAndEmitDAG(HSDAG);
5433 }
5434
5435 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
Chris Lattneread0d882008-06-17 06:09:18 +00005436 SelectionDAG BSDAG(TLI, MF, FuncInfo,
5437 getAnalysisToUpdate<MachineModuleInfo>());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005438 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005439 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005440 // Set the current basic block to the mbb we wish to insert the code into
5441 BB = BitTestCases[i].Cases[j].ThisBB;
5442 BSDL.setCurrentBasicBlock(BB);
5443 // Emit the code
5444 if (j+1 != ej)
5445 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5446 BitTestCases[i].Reg,
5447 BitTestCases[i].Cases[j]);
5448 else
5449 BSDL.visitBitTestCase(BitTestCases[i].Default,
5450 BitTestCases[i].Reg,
5451 BitTestCases[i].Cases[j]);
5452
5453
5454 BSDAG.setRoot(BSDL.getRoot());
5455 CodeGenAndEmitDAG(BSDAG);
5456 }
5457
5458 // Update PHI Nodes
5459 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5460 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5461 MachineBasicBlock *PHIBB = PHI->getParent();
5462 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5463 "This is not a machine PHI node that we are updating!");
5464 // This is "default" BB. We have two jumps to it. From "header" BB and
5465 // from last "case" BB.
5466 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005467 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5468 false));
5469 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5470 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5471 false));
5472 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5473 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005474 }
5475 // One of "cases" BB.
5476 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5477 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5478 if (cBB->succ_end() !=
5479 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005480 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5481 false));
5482 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005483 }
5484 }
5485 }
5486 }
5487
Nate Begeman9453eea2006-04-23 06:26:20 +00005488 // If the JumpTable record is filled in, then we need to emit a jump table.
5489 // Updating the PHI nodes is tricky in this case, since we need to determine
5490 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005491 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5492 // Lower header first, if it wasn't already lowered
5493 if (!JTCases[i].first.Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005494 SelectionDAG HSDAG(TLI, MF, FuncInfo,
5495 getAnalysisToUpdate<MachineModuleInfo>());
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005496 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005497 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005498 // Set the current basic block to the mbb we wish to insert the code into
5499 BB = JTCases[i].first.HeaderBB;
5500 HSDL.setCurrentBasicBlock(BB);
5501 // Emit the code
5502 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5503 HSDAG.setRoot(HSDL.getRoot());
5504 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005505 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005506
Chris Lattneread0d882008-06-17 06:09:18 +00005507 SelectionDAG JSDAG(TLI, MF, FuncInfo,
5508 getAnalysisToUpdate<MachineModuleInfo>());
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005509 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005510 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005511 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005512 BB = JTCases[i].second.MBB;
5513 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005514 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005515 JSDL.visitJumpTable(JTCases[i].second);
5516 JSDAG.setRoot(JSDL.getRoot());
5517 CodeGenAndEmitDAG(JSDAG);
5518
Nate Begeman37efe672006-04-22 18:53:45 +00005519 // Update PHI Nodes
5520 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5521 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5522 MachineBasicBlock *PHIBB = PHI->getParent();
5523 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5524 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005525 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005526 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005527 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5528 false));
5529 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005530 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005531 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005532 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005533 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5534 false));
5535 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005536 }
5537 }
Nate Begeman37efe672006-04-22 18:53:45 +00005538 }
5539
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005540 // If the switch block involved a branch to one of the actual successors, we
5541 // need to update PHI nodes in that block.
5542 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5543 MachineInstr *PHI = PHINodesToUpdate[i].first;
5544 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5545 "This is not a machine PHI node that we are updating!");
5546 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005547 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5548 false));
5549 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005550 }
5551 }
5552
Nate Begemanf15485a2006-03-27 01:32:24 +00005553 // If we generated any switch lowering information, build and codegen any
5554 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005555 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Chris Lattneread0d882008-06-17 06:09:18 +00005556 SelectionDAG SDAG(TLI, MF, FuncInfo,
5557 getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005558 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005559 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005560
Nate Begemanf15485a2006-03-27 01:32:24 +00005561 // Set the current basic block to the mbb we wish to insert the code into
5562 BB = SwitchCases[i].ThisBB;
5563 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005564
Nate Begemanf15485a2006-03-27 01:32:24 +00005565 // Emit the code
5566 SDL.visitSwitchCase(SwitchCases[i]);
5567 SDAG.setRoot(SDL.getRoot());
5568 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005569
5570 // Handle any PHI nodes in successors of this chunk, as if we were coming
5571 // from the original BB before switch expansion. Note that PHI nodes can
5572 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5573 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005574 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005575 for (MachineBasicBlock::iterator Phi = BB->begin();
5576 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5577 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5578 for (unsigned pn = 0; ; ++pn) {
5579 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5580 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005581 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5582 second, false));
5583 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005584 break;
5585 }
5586 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005587 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005588
5589 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005590 if (BB == SwitchCases[i].FalseBB)
5591 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005592
5593 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005594 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005595 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005596 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005597 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005598 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005599}
Evan Chenga9c20912006-01-21 02:32:06 +00005600
Jim Laskey13ec7022006-08-01 14:21:23 +00005601
Evan Chenga9c20912006-01-21 02:32:06 +00005602//===----------------------------------------------------------------------===//
5603/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5604/// target node in the graph.
5605void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5606 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005607
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005608 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005609
5610 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005611 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005612 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005613 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005614
Evan Cheng4576f6d2008-07-01 18:05:03 +00005615 ScheduleDAG *SL = Ctor(this, &DAG, BB, FastISel);
Chris Lattnera3818e62006-01-21 19:12:11 +00005616 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005617
5618 if (ViewSUnitDAGs) SL->viewGraph();
5619
Evan Chengcccf1232006-02-04 06:49:00 +00005620 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005621}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005622
Chris Lattner03fc53c2006-03-06 00:22:00 +00005623
Jim Laskey9ff542f2006-08-01 18:29:48 +00005624HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5625 return new HazardRecognizer();
5626}
5627
Chris Lattner75548062006-10-11 03:58:02 +00005628//===----------------------------------------------------------------------===//
5629// Helper functions used by the generated instruction selector.
5630//===----------------------------------------------------------------------===//
5631// Calls to these methods are generated by tblgen.
5632
5633/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5634/// the dag combiner simplified the 255, we still want to match. RHS is the
5635/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5636/// specified in the .td file (e.g. 255).
5637bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005638 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005639 const APInt &ActualMask = RHS->getAPIntValue();
5640 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005641
5642 // If the actual mask exactly matches, success!
5643 if (ActualMask == DesiredMask)
5644 return true;
5645
5646 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005647 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005648 return false;
5649
5650 // Otherwise, the DAG Combiner may have proven that the value coming in is
5651 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005652 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005653 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005654 return true;
5655
5656 // TODO: check to see if missing bits are just not demanded.
5657
5658 // Otherwise, this pattern doesn't match.
5659 return false;
5660}
5661
5662/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5663/// the dag combiner simplified the 255, we still want to match. RHS is the
5664/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5665/// specified in the .td file (e.g. 255).
5666bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005667 int64_t DesiredMaskS) const {
5668 const APInt &ActualMask = RHS->getAPIntValue();
5669 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005670
5671 // If the actual mask exactly matches, success!
5672 if (ActualMask == DesiredMask)
5673 return true;
5674
5675 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005676 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005677 return false;
5678
5679 // Otherwise, the DAG Combiner may have proven that the value coming in is
5680 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005681 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005682
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005683 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005684 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005685
5686 // If all the missing bits in the or are already known to be set, match!
5687 if ((NeededMask & KnownOne) == NeededMask)
5688 return true;
5689
5690 // TODO: check to see if missing bits are just not demanded.
5691
5692 // Otherwise, this pattern doesn't match.
5693 return false;
5694}
5695
Jim Laskey9ff542f2006-08-01 18:29:48 +00005696
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005697/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5698/// by tblgen. Others should not call it.
5699void SelectionDAGISel::
5700SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5701 std::vector<SDOperand> InOps;
5702 std::swap(InOps, Ops);
5703
5704 Ops.push_back(InOps[0]); // input chain.
5705 Ops.push_back(InOps[1]); // input asm string.
5706
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005707 unsigned i = 2, e = InOps.size();
5708 if (InOps[e-1].getValueType() == MVT::Flag)
5709 --e; // Don't process a flag operand if it is here.
5710
5711 while (i != e) {
5712 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5713 if ((Flags & 7) != 4 /*MEM*/) {
5714 // Just skip over this operand, copying the operands verbatim.
5715 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5716 i += (Flags >> 3) + 1;
5717 } else {
5718 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5719 // Otherwise, this is a memory operand. Ask the target to select it.
5720 std::vector<SDOperand> SelOps;
5721 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005722 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005723 exit(1);
5724 }
5725
5726 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005727 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005728 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005729 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005730 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5731 i += 2;
5732 }
5733 }
5734
5735 // Add the flag input back if present.
5736 if (e != InOps.size())
5737 Ops.push_back(InOps.back());
5738}
Devang Patel794fd752007-05-01 21:15:47 +00005739
Devang Patel19974732007-05-03 01:11:54 +00005740char SelectionDAGISel::ID = 0;