blob: 15e362984939cb7128cb9c8eb339a7824db98925 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000080 ISHeuristic("pre-RA-sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Chris Lattner5bab7852008-01-25 17:24:52 +000082 cl::desc("Instruction schedulers available (before register"
83 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000084
Jim Laskey9ff542f2006-08-01 18:29:48 +000085 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000086 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000088} // namespace
89
Evan Cheng5c807602008-02-26 02:33:44 +000090namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000091
Chris Lattnerf899fce2008-04-27 23:48:12 +000092/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93/// MVT::ValueTypes that represent all the individual underlying
94/// non-aggregate types that comprise it.
95static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
101 EI != EB; ++EI)
102 ComputeValueVTs(TLI, *EI, ValueVTs);
103 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000104 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
110 return;
111 }
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
114}
Dan Gohman23ce5022008-04-25 18:27:55 +0000115
Chris Lattnerf899fce2008-04-27 23:48:12 +0000116namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000117 /// RegsForValue - This struct represents the registers (physical or virtual)
118 /// that a particular set of values is assigned, and the type information about
119 /// the value. The most common situation is to represent one value at a time,
120 /// but struct or array values are handled element-wise as multiple values.
121 /// The splitting of aggregates is performed recursively, so that we never
122 /// have aggregate-typed registers. The values at this point do not necessarily
123 /// have legal types, so each value may require one or more registers of some
124 /// legal type.
125 ///
Chris Lattner95255282006-06-28 23:17:24 +0000126 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000128 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000129 const TargetLowering *TLI;
130
Dan Gohman0fe00902008-04-28 18:10:39 +0000131 /// ValueVTs - The value types of the values, which may not be legal, and
132 /// may need be promoted or synthesized from one or more registers.
133 ///
134 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000135
Dan Gohman0fe00902008-04-28 18:10:39 +0000136 /// RegVTs - The value types of the registers. This is the same size as
137 /// ValueVTs and it records, for each value, what the type of the assigned
138 /// register or registers are. (Individual values are never synthesized
139 /// from more than one type of register.)
140 ///
141 /// With virtual registers, the contents of RegVTs is redundant with TLI's
142 /// getRegisterType member function, however when with physical registers
143 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000144 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000145 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000146
Dan Gohman0fe00902008-04-28 18:10:39 +0000147 /// Regs - This list holds the registers assigned to the values.
148 /// Each legal or promoted value requires one register, and each
149 /// expanded value requires multiple registers.
150 ///
151 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000154
Dan Gohman23ce5022008-04-25 18:27:55 +0000155 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000156 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000157 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000158 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000159 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000160 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000161 const SmallVector<MVT::ValueType, 4> &regvts,
162 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000163 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000164 RegsForValue(const TargetLowering &tli,
165 unsigned Reg, const Type *Ty) : TLI(&tli) {
166 ComputeValueVTs(tli, Ty, ValueVTs);
167
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000168 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000169 MVT::ValueType ValueVT = ValueVTs[Value];
170 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
171 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
172 for (unsigned i = 0; i != NumRegs; ++i)
173 Regs.push_back(Reg + i);
174 RegVTs.push_back(RegisterVT);
175 Reg += NumRegs;
176 }
Chris Lattner864635a2006-02-22 22:37:12 +0000177 }
178
Chris Lattner41f62592008-04-29 04:29:54 +0000179 /// append - Add the specified values to this one.
180 void append(const RegsForValue &RHS) {
181 TLI = RHS.TLI;
182 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
183 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
184 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
185 }
186
187
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000189 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000190 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000192 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000193 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000194
195 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
196 /// specified value into the registers specified by this object. This uses
197 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000200 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000201
202 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
203 /// operand list. This adds the code marker and includes the number of
204 /// values added into it.
205 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000206 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000207 };
208}
Evan Cheng4ef10862006-01-23 07:01:07 +0000209
Chris Lattner1c08c712005-01-07 07:47:53 +0000210namespace llvm {
211 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000212 /// createDefaultScheduler - This creates an instruction scheduler appropriate
213 /// for the target.
214 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
215 SelectionDAG *DAG,
216 MachineBasicBlock *BB) {
217 TargetLowering &TLI = IS->getTargetLowering();
218
219 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
220 return createTDListDAGScheduler(IS, DAG, BB);
221 } else {
222 assert(TLI.getSchedulingPreference() ==
223 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
224 return createBURRListDAGScheduler(IS, DAG, BB);
225 }
226 }
227
228
229 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000230 /// FunctionLoweringInfo - This contains information that is global to a
231 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000232 class FunctionLoweringInfo {
233 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000234 TargetLowering &TLI;
235 Function &Fn;
236 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000237 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000238
239 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
240
241 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
242 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
243
244 /// ValueMap - Since we emit code for the function a basic block at a time,
245 /// we must remember which virtual registers hold the values for
246 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000247 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000248
249 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
250 /// the entry block. This allows the allocas to be efficiently referenced
251 /// anywhere in the function.
252 std::map<const AllocaInst*, int> StaticAllocaMap;
253
Duncan Sandsf4070822007-06-15 19:04:19 +0000254#ifndef NDEBUG
255 SmallSet<Instruction*, 8> CatchInfoLost;
256 SmallSet<Instruction*, 8> CatchInfoFound;
257#endif
258
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000260 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000261 }
Chris Lattner571e4342006-10-27 21:36:01 +0000262
263 /// isExportedInst - Return true if the specified value is an instruction
264 /// exported from its block.
265 bool isExportedInst(const Value *V) {
266 return ValueMap.count(V);
267 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000268
Chris Lattner3c384492006-03-16 19:51:18 +0000269 unsigned CreateRegForValue(const Value *V);
270
Chris Lattner1c08c712005-01-07 07:47:53 +0000271 unsigned InitializeRegForValue(const Value *V) {
272 unsigned &R = ValueMap[V];
273 assert(R == 0 && "Already initialized this value register!");
274 return R = CreateRegForValue(V);
275 }
276 };
277}
278
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000279/// isSelector - Return true if this instruction is a call to the
280/// eh.selector intrinsic.
281static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000282 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000283 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
284 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000285 return false;
286}
287
Chris Lattner1c08c712005-01-07 07:47:53 +0000288/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000289/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000290/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000291static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
292 if (isa<PHINode>(I)) return true;
293 BasicBlock *BB = I->getParent();
294 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000296 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000297 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000298 return true;
299 return false;
300}
301
Chris Lattnerbf209482005-10-30 19:42:35 +0000302/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000303/// entry block, return true. This includes arguments used by switches, since
304/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000305static bool isOnlyUsedInEntryBlock(Argument *A) {
306 BasicBlock *Entry = A->getParent()->begin();
307 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000308 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000309 return false; // Use not in entry block.
310 return true;
311}
312
Chris Lattner1c08c712005-01-07 07:47:53 +0000313FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000314 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000315 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000316
Chris Lattnerbf209482005-10-30 19:42:35 +0000317 // Create a vreg for each argument register that is not dead and is used
318 // outside of the entry block for the function.
319 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
320 AI != E; ++AI)
321 if (!isOnlyUsedInEntryBlock(AI))
322 InitializeRegForValue(AI);
323
Chris Lattner1c08c712005-01-07 07:47:53 +0000324 // Initialize the mapping of values to registers. This is only set up for
325 // instruction values that are used outside of the block that defines
326 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000327 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
329 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000330 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000331 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000332 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000333 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000334 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000335 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000336
Reid Spencerb83eb642006-10-20 07:07:24 +0000337 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000338 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000340 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000341 }
342
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000343 for (; BB != EB; ++BB)
344 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000345 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
346 if (!isa<AllocaInst>(I) ||
347 !StaticAllocaMap.count(cast<AllocaInst>(I)))
348 InitializeRegForValue(I);
349
350 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
351 // also creates the initial PHI MachineInstrs, though none of the input
352 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000353 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000354 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
355 MBBMap[BB] = MBB;
356 MF.getBasicBlockList().push_back(MBB);
357
358 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
359 // appropriate.
360 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000361 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
362 if (PN->use_empty()) continue;
363
364 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000365 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000366 unsigned PHIReg = ValueMap[PN];
367 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000369 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000370 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000371 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000372 }
373}
374
Chris Lattner3c384492006-03-16 19:51:18 +0000375/// CreateRegForValue - Allocate the appropriate number of virtual registers of
376/// the correctly promoted or expanded types. Assign these registers
377/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000378///
379/// In the case that the given value has struct or array type, this function
380/// will assign registers for each member or element.
381///
Chris Lattner3c384492006-03-16 19:51:18 +0000382unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000383 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000384 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000385
Dan Gohman23ce5022008-04-25 18:27:55 +0000386 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000387 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000388 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000389 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000390
Chris Lattnerb606dba2008-04-28 06:44:42 +0000391 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000392 for (unsigned i = 0; i != NumRegs; ++i) {
393 unsigned R = MakeReg(RegisterVT);
394 if (!FirstReg) FirstReg = R;
395 }
396 }
397 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000398}
Chris Lattner1c08c712005-01-07 07:47:53 +0000399
400//===----------------------------------------------------------------------===//
401/// SelectionDAGLowering - This is the common target-independent lowering
402/// implementation that is parameterized by a TargetLowering object.
403/// Also, targets can overload any lowering method.
404///
405namespace llvm {
406class SelectionDAGLowering {
407 MachineBasicBlock *CurMBB;
408
Chris Lattner0da331f2007-02-04 01:31:47 +0000409 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000410
Chris Lattnerd3948112005-01-17 22:19:26 +0000411 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
412 /// them up and then emit token factor nodes when possible. This allows us to
413 /// get simple disambiguation between loads without worrying about alias
414 /// analysis.
415 std::vector<SDOperand> PendingLoads;
416
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000417 /// PendingExports - CopyToReg nodes that copy values to virtual registers
418 /// for export to other blocks need to be emitted before any terminator
419 /// instruction, but they have no other ordering requirements. We bunch them
420 /// up and the emit a single tokenfactor for them just before terminator
421 /// instructions.
422 std::vector<SDOperand> PendingExports;
423
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000424 /// Case - A struct to record the Value for a switch case, and the
425 /// case's target basic block.
426 struct Case {
427 Constant* Low;
428 Constant* High;
429 MachineBasicBlock* BB;
430
431 Case() : Low(0), High(0), BB(0) { }
432 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
433 Low(low), High(high), BB(bb) { }
434 uint64_t size() const {
435 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
436 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
437 return (rHigh - rLow + 1ULL);
438 }
439 };
440
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000441 struct CaseBits {
442 uint64_t Mask;
443 MachineBasicBlock* BB;
444 unsigned Bits;
445
446 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
447 Mask(mask), BB(bb), Bits(bits) { }
448 };
449
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000451 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000452 typedef CaseVector::iterator CaseItr;
453 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000454
455 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
456 /// of conditional branches.
457 struct CaseRec {
458 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
459 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
460
461 /// CaseBB - The MBB in which to emit the compare and branch
462 MachineBasicBlock *CaseBB;
463 /// LT, GE - If nonzero, we know the current case value must be less-than or
464 /// greater-than-or-equal-to these Constants.
465 Constant *LT;
466 Constant *GE;
467 /// Range - A pair of iterators representing the range of case values to be
468 /// processed at this point in the binary search tree.
469 CaseRange Range;
470 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000471
472 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000473
474 /// The comparison function for sorting the switch case values in the vector.
475 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000476 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000477 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000478 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
479 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
480 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
481 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000482 }
483 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000484
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000485 struct CaseBitsCmp {
486 bool operator () (const CaseBits& C1, const CaseBits& C2) {
487 return C1.Bits > C2.Bits;
488 }
489 };
490
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000491 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000492
Chris Lattner1c08c712005-01-07 07:47:53 +0000493public:
494 // TLI - This is information that describes the available target features we
495 // need for lowering. This indicates when operations are unavailable,
496 // implemented with a libcall, etc.
497 TargetLowering &TLI;
498 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000499 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000500 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000501
Nate Begemanf15485a2006-03-27 01:32:24 +0000502 /// SwitchCases - Vector of CaseBlock structures used to communicate
503 /// SwitchInst code generation information.
504 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000505 /// JTCases - Vector of JumpTable structures used to communicate
506 /// SwitchInst code generation information.
507 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000508 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000509
Chris Lattner1c08c712005-01-07 07:47:53 +0000510 /// FuncInfo - Information about the function as a whole.
511 ///
512 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000513
514 /// GCI - Garbage collection metadata for the function.
515 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000516
517 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000518 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000519 FunctionLoweringInfo &funcinfo,
520 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000521 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000522 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000523 }
524
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000525 /// getRoot - Return the current virtual root of the Selection DAG,
526 /// flushing any PendingLoad items. This must be done before emitting
527 /// a store or any other node that may need to be ordered after any
528 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000529 ///
530 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000531 if (PendingLoads.empty())
532 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000533
Chris Lattnerd3948112005-01-17 22:19:26 +0000534 if (PendingLoads.size() == 1) {
535 SDOperand Root = PendingLoads[0];
536 DAG.setRoot(Root);
537 PendingLoads.clear();
538 return Root;
539 }
540
541 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000542 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
543 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000544 PendingLoads.clear();
545 DAG.setRoot(Root);
546 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000547 }
548
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000549 /// getControlRoot - Similar to getRoot, but instead of flushing all the
550 /// PendingLoad items, flush all the PendingExports items. It is necessary
551 /// to do this before emitting a terminator instruction.
552 ///
553 SDOperand getControlRoot() {
554 SDOperand Root = DAG.getRoot();
555
556 if (PendingExports.empty())
557 return Root;
558
559 // Turn all of the CopyToReg chains into one factored node.
560 if (Root.getOpcode() != ISD::EntryToken) {
561 unsigned i = 0, e = PendingExports.size();
562 for (; i != e; ++i) {
563 assert(PendingExports[i].Val->getNumOperands() > 1);
564 if (PendingExports[i].Val->getOperand(0) == Root)
565 break; // Don't add the root if we already indirectly depend on it.
566 }
567
568 if (i == e)
569 PendingExports.push_back(Root);
570 }
571
572 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
573 &PendingExports[0],
574 PendingExports.size());
575 PendingExports.clear();
576 DAG.setRoot(Root);
577 return Root;
578 }
579
580 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000581
Chris Lattner1c08c712005-01-07 07:47:53 +0000582 void visit(Instruction &I) { visit(I.getOpcode(), I); }
583
584 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000585 // Note: this doesn't use InstVisitor, because it has to work with
586 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000587 switch (Opcode) {
588 default: assert(0 && "Unknown instruction type encountered!");
589 abort();
590 // Build the switch statement using the Instruction.def file.
591#define HANDLE_INST(NUM, OPCODE, CLASS) \
592 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
593#include "llvm/Instruction.def"
594 }
595 }
596
597 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
598
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000599 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000600 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000601 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner199862b2006-03-16 19:57:50 +0000603 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000604
Chris Lattner0da331f2007-02-04 01:31:47 +0000605 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000606 SDOperand &N = NodeMap[V];
607 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000608 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000609 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000610
Evan Cheng5c807602008-02-26 02:33:44 +0000611 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000612 std::set<unsigned> &OutputRegs,
613 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000614
Chris Lattner571e4342006-10-27 21:36:01 +0000615 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
616 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
617 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000618 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000619 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000620 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000621 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000622
Chris Lattner1c08c712005-01-07 07:47:53 +0000623 // Terminator instructions.
624 void visitRet(ReturnInst &I);
625 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000626 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000627 void visitUnreachable(UnreachableInst &I) { /* noop */ }
628
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000630 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000631 CaseRecVector& WorkList,
632 Value* SV,
633 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000634 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000635 CaseRecVector& WorkList,
636 Value* SV,
637 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000638 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000639 CaseRecVector& WorkList,
640 Value* SV,
641 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000642 bool handleBitTestsSwitchCase(CaseRec& CR,
643 CaseRecVector& WorkList,
644 Value* SV,
645 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000646 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000647 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
648 void visitBitTestCase(MachineBasicBlock* NextMBB,
649 unsigned Reg,
650 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000651 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000652 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
653 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000654
Chris Lattner1c08c712005-01-07 07:47:53 +0000655 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000656 void visitInvoke(InvokeInst &I);
657 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000658
Dan Gohman7f321562007-06-25 16:23:39 +0000659 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000660 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000661 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000662 if (I.getType()->isFPOrFPVector())
663 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000664 else
Dan Gohman7f321562007-06-25 16:23:39 +0000665 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000666 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000667 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000668 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000669 if (I.getType()->isFPOrFPVector())
670 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000671 else
Dan Gohman7f321562007-06-25 16:23:39 +0000672 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000673 }
Dan Gohman7f321562007-06-25 16:23:39 +0000674 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
675 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
676 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
677 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
678 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
679 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
680 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
681 void visitOr (User &I) { visitBinary(I, ISD::OR); }
682 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000683 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000684 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
685 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000686 void visitICmp(User &I);
687 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Chris Lattner2bbd8102006-03-29 00:11:43 +0000702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000704 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000705
Chris Lattner1c08c712005-01-07 07:47:53 +0000706 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000708
709 void visitMalloc(MallocInst &I);
710 void visitFree(FreeInst &I);
711 void visitAlloca(AllocaInst &I);
712 void visitLoad(LoadInst &I);
713 void visitStore(StoreInst &I);
714 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
715 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000716 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000717 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000718 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000719
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 void visitVAArg(VAArgInst &I);
722 void visitVAEnd(CallInst &I);
723 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724
Dan Gohmanef5d1942008-03-11 21:11:25 +0000725 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000726
Chris Lattner1c08c712005-01-07 07:47:53 +0000727 void visitUserOp1(Instruction &I) {
728 assert(0 && "UserOp1 should not exist at instruction selection time!");
729 abort();
730 }
731 void visitUserOp2(Instruction &I) {
732 assert(0 && "UserOp2 should not exist at instruction selection time!");
733 abort();
734 }
Mon P Wang63307c32008-05-05 19:05:59 +0000735
736private:
737 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
738
Chris Lattner1c08c712005-01-07 07:47:53 +0000739};
740} // end namespace llvm
741
Dan Gohman6183f782007-07-05 20:12:34 +0000742
Duncan Sandsb988bac2008-02-11 20:58:28 +0000743/// getCopyFromParts - Create a value that contains the specified legal parts
744/// combined into the value they represent. If the parts combine to a type
745/// larger then ValueVT then AssertOp can be used to specify whether the extra
746/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000747/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000748static SDOperand getCopyFromParts(SelectionDAG &DAG,
749 const SDOperand *Parts,
750 unsigned NumParts,
751 MVT::ValueType PartVT,
752 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000753 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000754 assert(NumParts > 0 && "No parts to assemble!");
755 TargetLowering &TLI = DAG.getTargetLoweringInfo();
756 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000757
Duncan Sands014e04a2008-02-12 20:46:31 +0000758 if (NumParts > 1) {
759 // Assemble the value from multiple parts.
760 if (!MVT::isVector(ValueVT)) {
761 unsigned PartBits = MVT::getSizeInBits(PartVT);
762 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000763
Duncan Sands014e04a2008-02-12 20:46:31 +0000764 // Assemble the power of 2 part.
765 unsigned RoundParts = NumParts & (NumParts - 1) ?
766 1 << Log2_32(NumParts) : NumParts;
767 unsigned RoundBits = PartBits * RoundParts;
768 MVT::ValueType RoundVT = RoundBits == ValueBits ?
769 ValueVT : MVT::getIntegerType(RoundBits);
770 SDOperand Lo, Hi;
771
772 if (RoundParts > 2) {
773 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
774 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
776 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000777 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000778 Lo = Parts[0];
779 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000780 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000781 if (TLI.isBigEndian())
782 std::swap(Lo, Hi);
783 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
784
785 if (RoundParts < NumParts) {
786 // Assemble the trailing non-power-of-2 part.
787 unsigned OddParts = NumParts - RoundParts;
788 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
789 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
790
791 // Combine the round and odd parts.
792 Lo = Val;
793 if (TLI.isBigEndian())
794 std::swap(Lo, Hi);
795 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
796 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
797 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
798 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
799 TLI.getShiftAmountTy()));
800 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
801 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
802 }
803 } else {
804 // Handle a multi-element vector.
805 MVT::ValueType IntermediateVT, RegisterVT;
806 unsigned NumIntermediates;
807 unsigned NumRegs =
808 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
809 RegisterVT);
810
811 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
812 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
813 assert(RegisterVT == Parts[0].getValueType() &&
814 "Part type doesn't match part!");
815
816 // Assemble the parts into intermediate operands.
817 SmallVector<SDOperand, 8> Ops(NumIntermediates);
818 if (NumIntermediates == NumParts) {
819 // If the register was not expanded, truncate or copy the value,
820 // as appropriate.
821 for (unsigned i = 0; i != NumParts; ++i)
822 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
823 PartVT, IntermediateVT);
824 } else if (NumParts > 0) {
825 // If the intermediate type was expanded, build the intermediate operands
826 // from the parts.
827 assert(NumParts % NumIntermediates == 0 &&
828 "Must expand into a divisible number of parts!");
829 unsigned Factor = NumParts / NumIntermediates;
830 for (unsigned i = 0; i != NumIntermediates; ++i)
831 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
832 PartVT, IntermediateVT);
833 }
834
835 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
836 // operands.
837 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
838 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
839 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000840 }
Dan Gohman6183f782007-07-05 20:12:34 +0000841 }
842
Duncan Sands014e04a2008-02-12 20:46:31 +0000843 // There is now one part, held in Val. Correct it to match ValueVT.
844 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000845
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 if (PartVT == ValueVT)
847 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000848
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 if (MVT::isVector(PartVT)) {
850 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
851 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000852 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000853
854 if (MVT::isVector(ValueVT)) {
855 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
856 MVT::getVectorNumElements(ValueVT) == 1 &&
857 "Only trivial scalar-to-vector conversions should get here!");
858 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
859 }
860
861 if (MVT::isInteger(PartVT) &&
862 MVT::isInteger(ValueVT)) {
863 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
864 // For a truncate, see if we have any information to
865 // indicate whether the truncated bits will always be
866 // zero or sign-extension.
867 if (AssertOp != ISD::DELETED_NODE)
868 Val = DAG.getNode(AssertOp, PartVT, Val,
869 DAG.getValueType(ValueVT));
870 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
871 } else {
872 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
873 }
874 }
875
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000876 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
877 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000878 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000879 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000880 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000881 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
882 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000883
884 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
885 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
886
887 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000888 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000889}
890
Duncan Sandsb988bac2008-02-11 20:58:28 +0000891/// getCopyToParts - Create a series of nodes that contain the specified value
892/// split into legal parts. If the parts contain more bits than Val, then, for
893/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000894static void getCopyToParts(SelectionDAG &DAG,
895 SDOperand Val,
896 SDOperand *Parts,
897 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000898 MVT::ValueType PartVT,
899 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000900 TargetLowering &TLI = DAG.getTargetLoweringInfo();
901 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000902 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000903 unsigned PartBits = MVT::getSizeInBits(PartVT);
904 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000905
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 if (!NumParts)
907 return;
908
909 if (!MVT::isVector(ValueVT)) {
910 if (PartVT == ValueVT) {
911 assert(NumParts == 1 && "No-op copy with multiple parts!");
912 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000913 return;
914 }
915
Duncan Sands014e04a2008-02-12 20:46:31 +0000916 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
917 // If the parts cover more bits than the value has, promote the value.
918 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
919 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000920 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000921 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
922 ValueVT = MVT::getIntegerType(NumParts * PartBits);
923 Val = DAG.getNode(ExtendKind, ValueVT, Val);
924 } else {
925 assert(0 && "Unknown mismatch!");
926 }
927 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
928 // Different types of the same size.
929 assert(NumParts == 1 && PartVT != ValueVT);
930 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
931 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
932 // If the parts cover less bits than value has, truncate the value.
933 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
934 ValueVT = MVT::getIntegerType(NumParts * PartBits);
935 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000936 } else {
937 assert(0 && "Unknown mismatch!");
938 }
939 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000940
941 // The value may have changed - recompute ValueVT.
942 ValueVT = Val.getValueType();
943 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
944 "Failed to tile the value with PartVT!");
945
946 if (NumParts == 1) {
947 assert(PartVT == ValueVT && "Type conversion failed!");
948 Parts[0] = Val;
949 return;
950 }
951
952 // Expand the value into multiple parts.
953 if (NumParts & (NumParts - 1)) {
954 // The number of parts is not a power of 2. Split off and copy the tail.
955 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
956 "Do not know what to expand to!");
957 unsigned RoundParts = 1 << Log2_32(NumParts);
958 unsigned RoundBits = RoundParts * PartBits;
959 unsigned OddParts = NumParts - RoundParts;
960 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
961 DAG.getConstant(RoundBits,
962 TLI.getShiftAmountTy()));
963 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
964 if (TLI.isBigEndian())
965 // The odd parts were reversed by getCopyToParts - unreverse them.
966 std::reverse(Parts + RoundParts, Parts + NumParts);
967 NumParts = RoundParts;
968 ValueVT = MVT::getIntegerType(NumParts * PartBits);
969 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
970 }
971
972 // The number of parts is a power of 2. Repeatedly bisect the value using
973 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000974 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
975 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
976 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000977 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
978 for (unsigned i = 0; i < NumParts; i += StepSize) {
979 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000980 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
981 SDOperand &Part0 = Parts[i];
982 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000983
Duncan Sands25eb0432008-03-12 20:30:08 +0000984 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
985 DAG.getConstant(1, PtrVT));
986 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
987 DAG.getConstant(0, PtrVT));
988
989 if (ThisBits == PartBits && ThisVT != PartVT) {
990 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
991 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
992 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000993 }
994 }
995
996 if (TLI.isBigEndian())
997 std::reverse(Parts, Parts + NumParts);
998
999 return;
1000 }
1001
1002 // Vector ValueVT.
1003 if (NumParts == 1) {
1004 if (PartVT != ValueVT) {
1005 if (MVT::isVector(PartVT)) {
1006 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1007 } else {
1008 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1009 MVT::getVectorNumElements(ValueVT) == 1 &&
1010 "Only trivial vector-to-scalar conversions should get here!");
1011 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1012 DAG.getConstant(0, PtrVT));
1013 }
1014 }
1015
Dan Gohman6183f782007-07-05 20:12:34 +00001016 Parts[0] = Val;
1017 return;
1018 }
1019
1020 // Handle a multi-element vector.
1021 MVT::ValueType IntermediateVT, RegisterVT;
1022 unsigned NumIntermediates;
1023 unsigned NumRegs =
1024 DAG.getTargetLoweringInfo()
1025 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1026 RegisterVT);
1027 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1028
1029 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1030 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1031
1032 // Split the vector into intermediate operands.
1033 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1034 for (unsigned i = 0; i != NumIntermediates; ++i)
1035 if (MVT::isVector(IntermediateVT))
1036 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1037 IntermediateVT, Val,
1038 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001039 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001040 else
1041 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1042 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001043 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001044
1045 // Split the intermediate operands into legal parts.
1046 if (NumParts == NumIntermediates) {
1047 // If the register was not expanded, promote or copy the value,
1048 // as appropriate.
1049 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001050 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001051 } else if (NumParts > 0) {
1052 // If the intermediate type was expanded, split each the value into
1053 // legal parts.
1054 assert(NumParts % NumIntermediates == 0 &&
1055 "Must expand into a divisible number of parts!");
1056 unsigned Factor = NumParts / NumIntermediates;
1057 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001058 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001059 }
1060}
1061
1062
Chris Lattner199862b2006-03-16 19:57:50 +00001063SDOperand SelectionDAGLowering::getValue(const Value *V) {
1064 SDOperand &N = NodeMap[V];
1065 if (N.Val) return N;
1066
Chris Lattner199862b2006-03-16 19:57:50 +00001067 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001068 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001069
1070 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1071 return N = DAG.getConstant(CI->getValue(), VT);
1072
1073 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001074 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001075
1076 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001077 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001078
1079 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1080 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1081
Chris Lattner6833b062008-04-28 07:16:35 +00001082 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1083 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001084
1085 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1086 visit(CE->getOpcode(), *CE);
1087 SDOperand N1 = NodeMap[V];
1088 assert(N1.Val && "visit didn't populate the ValueMap!");
1089 return N1;
1090 }
1091
Chris Lattner6833b062008-04-28 07:16:35 +00001092 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001093 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001094
Chris Lattner6833b062008-04-28 07:16:35 +00001095 // Now that we know the number and type of the elements, get that number of
1096 // elements into the Ops array based on what kind of constant it is.
1097 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001098 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1099 for (unsigned i = 0; i != NumElements; ++i)
1100 Ops.push_back(getValue(CP->getOperand(i)));
1101 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001102 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1103 "Unknown vector constant!");
1104 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1105
Chris Lattnerb606dba2008-04-28 06:44:42 +00001106 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001107 if (isa<UndefValue>(C))
1108 Op = DAG.getNode(ISD::UNDEF, EltVT);
1109 else if (MVT::isFloatingPoint(EltVT))
1110 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001111 else
Chris Lattner6833b062008-04-28 07:16:35 +00001112 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001113 Ops.assign(NumElements, Op);
1114 }
1115
1116 // Create a BUILD_VECTOR node.
1117 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001118 }
1119
Chris Lattnerb606dba2008-04-28 06:44:42 +00001120 // If this is a static alloca, generate it as the frameindex instead of
1121 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001122 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1123 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001124 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001125 if (SI != FuncInfo.StaticAllocaMap.end())
1126 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1127 }
1128
Chris Lattner251db182007-02-25 18:40:32 +00001129 unsigned InReg = FuncInfo.ValueMap[V];
1130 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001131
Chris Lattner6833b062008-04-28 07:16:35 +00001132 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001133 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001134 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001135}
1136
1137
Chris Lattner1c08c712005-01-07 07:47:53 +00001138void SelectionDAGLowering::visitRet(ReturnInst &I) {
1139 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001140 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001141 return;
1142 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001143
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001144 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001145 NewValues.push_back(getControlRoot());
1146 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001147 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001148 MVT::ValueType VT = RetOp.getValueType();
1149
Evan Cheng8e7d0562006-05-26 23:09:09 +00001150 // FIXME: C calling convention requires the return type to be promoted to
1151 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001152 if (MVT::isInteger(VT)) {
1153 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1154 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1155 VT = MinVT;
1156 }
1157
1158 unsigned NumParts = TLI.getNumRegisters(VT);
1159 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1160 SmallVector<SDOperand, 4> Parts(NumParts);
1161 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1162
1163 const Function *F = I.getParent()->getParent();
1164 if (F->paramHasAttr(0, ParamAttr::SExt))
1165 ExtendKind = ISD::SIGN_EXTEND;
1166 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1167 ExtendKind = ISD::ZERO_EXTEND;
1168
1169 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1170
1171 for (unsigned i = 0; i < NumParts; ++i) {
1172 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001173 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001174 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001175 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001176 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1177 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001178}
1179
Chris Lattner571e4342006-10-27 21:36:01 +00001180/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1181/// the current basic block, add it to ValueMap now so that we'll get a
1182/// CopyTo/FromReg.
1183void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1184 // No need to export constants.
1185 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1186
1187 // Already exported?
1188 if (FuncInfo.isExportedInst(V)) return;
1189
1190 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001191 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001192}
1193
Chris Lattner8c494ab2006-10-27 23:50:33 +00001194bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1195 const BasicBlock *FromBB) {
1196 // The operands of the setcc have to be in this block. We don't know
1197 // how to export them from some other block.
1198 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1199 // Can export from current BB.
1200 if (VI->getParent() == FromBB)
1201 return true;
1202
1203 // Is already exported, noop.
1204 return FuncInfo.isExportedInst(V);
1205 }
1206
1207 // If this is an argument, we can export it if the BB is the entry block or
1208 // if it is already exported.
1209 if (isa<Argument>(V)) {
1210 if (FromBB == &FromBB->getParent()->getEntryBlock())
1211 return true;
1212
1213 // Otherwise, can only export this if it is already exported.
1214 return FuncInfo.isExportedInst(V);
1215 }
1216
1217 // Otherwise, constants can always be exported.
1218 return true;
1219}
1220
Chris Lattner6a586c82006-10-29 21:01:20 +00001221static bool InBlock(const Value *V, const BasicBlock *BB) {
1222 if (const Instruction *I = dyn_cast<Instruction>(V))
1223 return I->getParent() == BB;
1224 return true;
1225}
1226
Chris Lattner571e4342006-10-27 21:36:01 +00001227/// FindMergedConditions - If Cond is an expression like
1228void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1229 MachineBasicBlock *TBB,
1230 MachineBasicBlock *FBB,
1231 MachineBasicBlock *CurBB,
1232 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001233 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001234 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001235
Reid Spencere4d87aa2006-12-23 06:05:41 +00001236 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1237 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001238 BOp->getParent() != CurBB->getBasicBlock() ||
1239 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1240 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001241 const BasicBlock *BB = CurBB->getBasicBlock();
1242
Reid Spencere4d87aa2006-12-23 06:05:41 +00001243 // If the leaf of the tree is a comparison, merge the condition into
1244 // the caseblock.
1245 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1246 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001247 // how to export them from some other block. If this is the first block
1248 // of the sequence, no exporting is needed.
1249 (CurBB == CurMBB ||
1250 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1251 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001252 BOp = cast<Instruction>(Cond);
1253 ISD::CondCode Condition;
1254 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1255 switch (IC->getPredicate()) {
1256 default: assert(0 && "Unknown icmp predicate opcode!");
1257 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1258 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1259 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1260 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1261 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1262 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1263 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1264 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1265 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1266 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1267 }
1268 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1269 ISD::CondCode FPC, FOC;
1270 switch (FC->getPredicate()) {
1271 default: assert(0 && "Unknown fcmp predicate opcode!");
1272 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1273 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1274 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1275 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1276 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1277 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1278 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001279 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1280 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001281 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1282 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1283 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1284 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1285 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1286 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1287 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1288 }
1289 if (FiniteOnlyFPMath())
1290 Condition = FOC;
1291 else
1292 Condition = FPC;
1293 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001294 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001295 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001296 }
1297
Chris Lattner571e4342006-10-27 21:36:01 +00001298 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001299 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001300 SwitchCases.push_back(CB);
1301 return;
1302 }
1303
1304 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001305 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001306 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001307 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001308 return;
1309 }
1310
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001311
1312 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001313 MachineFunction::iterator BBI = CurBB;
1314 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1315 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1316
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001317 if (Opc == Instruction::Or) {
1318 // Codegen X | Y as:
1319 // jmp_if_X TBB
1320 // jmp TmpBB
1321 // TmpBB:
1322 // jmp_if_Y TBB
1323 // jmp FBB
1324 //
Chris Lattner571e4342006-10-27 21:36:01 +00001325
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001326 // Emit the LHS condition.
1327 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1328
1329 // Emit the RHS condition into TmpBB.
1330 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1331 } else {
1332 assert(Opc == Instruction::And && "Unknown merge op!");
1333 // Codegen X & Y as:
1334 // jmp_if_X TmpBB
1335 // jmp FBB
1336 // TmpBB:
1337 // jmp_if_Y TBB
1338 // jmp FBB
1339 //
1340 // This requires creation of TmpBB after CurBB.
1341
1342 // Emit the LHS condition.
1343 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1344
1345 // Emit the RHS condition into TmpBB.
1346 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1347 }
Chris Lattner571e4342006-10-27 21:36:01 +00001348}
1349
Chris Lattnerdf19f272006-10-31 22:37:42 +00001350/// If the set of cases should be emitted as a series of branches, return true.
1351/// If we should emit this as a bunch of and/or'd together conditions, return
1352/// false.
1353static bool
1354ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1355 if (Cases.size() != 2) return true;
1356
Chris Lattner0ccb5002006-10-31 23:06:00 +00001357 // If this is two comparisons of the same values or'd or and'd together, they
1358 // will get folded into a single comparison, so don't emit two blocks.
1359 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1360 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1361 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1362 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1363 return false;
1364 }
1365
Chris Lattnerdf19f272006-10-31 22:37:42 +00001366 return true;
1367}
1368
Chris Lattner1c08c712005-01-07 07:47:53 +00001369void SelectionDAGLowering::visitBr(BranchInst &I) {
1370 // Update machine-CFG edges.
1371 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001372
1373 // Figure out which block is immediately after the current one.
1374 MachineBasicBlock *NextBlock = 0;
1375 MachineFunction::iterator BBI = CurMBB;
1376 if (++BBI != CurMBB->getParent()->end())
1377 NextBlock = BBI;
1378
1379 if (I.isUnconditional()) {
1380 // If this is not a fall-through branch, emit the branch.
1381 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001382 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001383 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001384
Chris Lattner57ab6592006-10-24 17:57:59 +00001385 // Update machine-CFG edges.
1386 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 return;
1388 }
1389
1390 // If this condition is one of the special cases we handle, do special stuff
1391 // now.
1392 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001393 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001394
1395 // If this is a series of conditions that are or'd or and'd together, emit
1396 // this as a sequence of branches instead of setcc's with and/or operations.
1397 // For example, instead of something like:
1398 // cmp A, B
1399 // C = seteq
1400 // cmp D, E
1401 // F = setle
1402 // or C, F
1403 // jnz foo
1404 // Emit:
1405 // cmp A, B
1406 // je foo
1407 // cmp D, E
1408 // jle foo
1409 //
1410 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1411 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001412 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001413 BOp->getOpcode() == Instruction::Or)) {
1414 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001415 // If the compares in later blocks need to use values not currently
1416 // exported from this block, export them now. This block should always
1417 // be the first entry.
1418 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1419
Chris Lattnerdf19f272006-10-31 22:37:42 +00001420 // Allow some cases to be rejected.
1421 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001422 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1423 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1424 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1425 }
1426
1427 // Emit the branch for this block.
1428 visitSwitchCase(SwitchCases[0]);
1429 SwitchCases.erase(SwitchCases.begin());
1430 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001431 }
1432
Chris Lattner0ccb5002006-10-31 23:06:00 +00001433 // Okay, we decided not to do this, remove any inserted MBB's and clear
1434 // SwitchCases.
1435 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1436 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1437
Chris Lattnerdf19f272006-10-31 22:37:42 +00001438 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001439 }
1440 }
Chris Lattner24525952006-10-24 18:07:37 +00001441
1442 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001443 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001444 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001445 // Use visitSwitchCase to actually insert the fast branch sequence for this
1446 // cond branch.
1447 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001448}
1449
Nate Begemanf15485a2006-03-27 01:32:24 +00001450/// visitSwitchCase - Emits the necessary code to represent a single node in
1451/// the binary search tree resulting from lowering a switch instruction.
1452void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001453 SDOperand Cond;
1454 SDOperand CondLHS = getValue(CB.CmpLHS);
1455
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001456 // Build the setcc now.
1457 if (CB.CmpMHS == NULL) {
1458 // Fold "(X == true)" to X and "(X == false)" to !X to
1459 // handle common cases produced by branch lowering.
1460 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1461 Cond = CondLHS;
1462 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1463 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1464 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1465 } else
1466 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1467 } else {
1468 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001469
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001470 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1471 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1472
1473 SDOperand CmpOp = getValue(CB.CmpMHS);
1474 MVT::ValueType VT = CmpOp.getValueType();
1475
1476 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1477 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1478 } else {
1479 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1480 Cond = DAG.getSetCC(MVT::i1, SUB,
1481 DAG.getConstant(High-Low, VT), ISD::SETULE);
1482 }
1483
1484 }
1485
Nate Begemanf15485a2006-03-27 01:32:24 +00001486 // Set NextBlock to be the MBB immediately after the current one, if any.
1487 // This is used to avoid emitting unnecessary branches to the next block.
1488 MachineBasicBlock *NextBlock = 0;
1489 MachineFunction::iterator BBI = CurMBB;
1490 if (++BBI != CurMBB->getParent()->end())
1491 NextBlock = BBI;
1492
1493 // If the lhs block is the next block, invert the condition so that we can
1494 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001495 if (CB.TrueBB == NextBlock) {
1496 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001497 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1498 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1499 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001500 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001501 DAG.getBasicBlock(CB.TrueBB));
1502 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001503 DAG.setRoot(BrCond);
1504 else
1505 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001506 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001507 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001508 CurMBB->addSuccessor(CB.TrueBB);
1509 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001510}
1511
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001512/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001513void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001514 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001515 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001516 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001517 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001518 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1519 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1520 Table, Index));
1521 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001522}
1523
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001524/// visitJumpTableHeader - This function emits necessary code to produce index
1525/// in the JumpTable from switch case.
1526void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1527 SelectionDAGISel::JumpTableHeader &JTH) {
1528 // Subtract the lowest switch case value from the value being switched on
1529 // and conditional branch to default mbb if the result is greater than the
1530 // difference between smallest and largest cases.
1531 SDOperand SwitchOp = getValue(JTH.SValue);
1532 MVT::ValueType VT = SwitchOp.getValueType();
1533 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1534 DAG.getConstant(JTH.First, VT));
1535
1536 // The SDNode we just created, which holds the value being switched on
1537 // minus the the smallest case value, needs to be copied to a virtual
1538 // register so it can be used as an index into the jump table in a
1539 // subsequent basic block. This value may be smaller or larger than the
1540 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001541 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001542 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1543 else
1544 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1545
1546 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001547 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001548 JT.Reg = JumpTableReg;
1549
1550 // Emit the range check for the jump table, and branch to the default
1551 // block for the switch statement if the value being switched on exceeds
1552 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001553 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001554 DAG.getConstant(JTH.Last-JTH.First,VT),
1555 ISD::SETUGT);
1556
1557 // Set NextBlock to be the MBB immediately after the current one, if any.
1558 // This is used to avoid emitting unnecessary branches to the next block.
1559 MachineBasicBlock *NextBlock = 0;
1560 MachineFunction::iterator BBI = CurMBB;
1561 if (++BBI != CurMBB->getParent()->end())
1562 NextBlock = BBI;
1563
1564 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1565 DAG.getBasicBlock(JT.Default));
1566
1567 if (JT.MBB == NextBlock)
1568 DAG.setRoot(BrCond);
1569 else
1570 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001571 DAG.getBasicBlock(JT.MBB)));
1572
1573 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001574}
1575
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001576/// visitBitTestHeader - This function emits necessary code to produce value
1577/// suitable for "bit tests"
1578void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1579 // Subtract the minimum value
1580 SDOperand SwitchOp = getValue(B.SValue);
1581 MVT::ValueType VT = SwitchOp.getValueType();
1582 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1583 DAG.getConstant(B.First, VT));
1584
1585 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001586 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001587 DAG.getConstant(B.Range, VT),
1588 ISD::SETUGT);
1589
1590 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001591 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001592 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1593 else
1594 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1595
1596 // Make desired shift
1597 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1598 DAG.getConstant(1, TLI.getPointerTy()),
1599 ShiftOp);
1600
1601 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001602 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001603 B.Reg = SwitchReg;
1604
1605 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1606 DAG.getBasicBlock(B.Default));
1607
1608 // Set NextBlock to be the MBB immediately after the current one, if any.
1609 // This is used to avoid emitting unnecessary branches to the next block.
1610 MachineBasicBlock *NextBlock = 0;
1611 MachineFunction::iterator BBI = CurMBB;
1612 if (++BBI != CurMBB->getParent()->end())
1613 NextBlock = BBI;
1614
1615 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1616 if (MBB == NextBlock)
1617 DAG.setRoot(BrRange);
1618 else
1619 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1620 DAG.getBasicBlock(MBB)));
1621
1622 CurMBB->addSuccessor(B.Default);
1623 CurMBB->addSuccessor(MBB);
1624
1625 return;
1626}
1627
1628/// visitBitTestCase - this function produces one "bit test"
1629void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1630 unsigned Reg,
1631 SelectionDAGISel::BitTestCase &B) {
1632 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001633 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001634
1635 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1636 SwitchVal,
1637 DAG.getConstant(B.Mask,
1638 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001639 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001640 DAG.getConstant(0, TLI.getPointerTy()),
1641 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001642 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001643 AndCmp, DAG.getBasicBlock(B.TargetBB));
1644
1645 // Set NextBlock to be the MBB immediately after the current one, if any.
1646 // This is used to avoid emitting unnecessary branches to the next block.
1647 MachineBasicBlock *NextBlock = 0;
1648 MachineFunction::iterator BBI = CurMBB;
1649 if (++BBI != CurMBB->getParent()->end())
1650 NextBlock = BBI;
1651
1652 if (NextMBB == NextBlock)
1653 DAG.setRoot(BrAnd);
1654 else
1655 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1656 DAG.getBasicBlock(NextMBB)));
1657
1658 CurMBB->addSuccessor(B.TargetBB);
1659 CurMBB->addSuccessor(NextMBB);
1660
1661 return;
1662}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001663
Jim Laskeyb180aa12007-02-21 22:53:45 +00001664void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1665 // Retrieve successors.
1666 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001667 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001668
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001669 if (isa<InlineAsm>(I.getCalledValue()))
1670 visitInlineAsm(&I);
1671 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001672 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001673
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001674 // If the value of the invoke is used outside of its defining block, make it
1675 // available as a virtual register.
1676 if (!I.use_empty()) {
1677 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1678 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001679 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001680 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001681
1682 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001683 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001684 DAG.getBasicBlock(Return)));
1685
1686 // Update successor info
1687 CurMBB->addSuccessor(Return);
1688 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001689}
1690
1691void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1692}
1693
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001694/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001695/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001696bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001697 CaseRecVector& WorkList,
1698 Value* SV,
1699 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001700 Case& BackCase = *(CR.Range.second-1);
1701
1702 // Size is the number of Cases represented by this range.
1703 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001704 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001705 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001706
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001707 // Get the MachineFunction which holds the current MBB. This is used when
1708 // inserting any additional MBBs necessary to represent the switch.
1709 MachineFunction *CurMF = CurMBB->getParent();
1710
1711 // Figure out which block is immediately after the current one.
1712 MachineBasicBlock *NextBlock = 0;
1713 MachineFunction::iterator BBI = CR.CaseBB;
1714
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001715 if (++BBI != CurMBB->getParent()->end())
1716 NextBlock = BBI;
1717
1718 // TODO: If any two of the cases has the same destination, and if one value
1719 // is the same as the other, but has one bit unset that the other has set,
1720 // use bit manipulation to do two compares at once. For example:
1721 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1722
1723 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001724 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001725 // The last case block won't fall through into 'NextBlock' if we emit the
1726 // branches in this order. See if rearranging a case value would help.
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001728 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001729 std::swap(*I, BackCase);
1730 break;
1731 }
1732 }
1733 }
1734
1735 // Create a CaseBlock record representing a conditional branch to
1736 // the Case's target mbb if the value being switched on SV is equal
1737 // to C.
1738 MachineBasicBlock *CurBlock = CR.CaseBB;
1739 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1740 MachineBasicBlock *FallThrough;
1741 if (I != E-1) {
1742 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1743 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1744 } else {
1745 // If the last case doesn't match, go to the default block.
1746 FallThrough = Default;
1747 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001748
1749 Value *RHS, *LHS, *MHS;
1750 ISD::CondCode CC;
1751 if (I->High == I->Low) {
1752 // This is just small small case range :) containing exactly 1 case
1753 CC = ISD::SETEQ;
1754 LHS = SV; RHS = I->High; MHS = NULL;
1755 } else {
1756 CC = ISD::SETLE;
1757 LHS = I->Low; MHS = SV; RHS = I->High;
1758 }
1759 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1760 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001761
1762 // If emitting the first comparison, just call visitSwitchCase to emit the
1763 // code into the current block. Otherwise, push the CaseBlock onto the
1764 // vector to be later processed by SDISel, and insert the node's MBB
1765 // before the next MBB.
1766 if (CurBlock == CurMBB)
1767 visitSwitchCase(CB);
1768 else
1769 SwitchCases.push_back(CB);
1770
1771 CurBlock = FallThrough;
1772 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001773
1774 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001775}
1776
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001777static inline bool areJTsAllowed(const TargetLowering &TLI) {
1778 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1779 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1780}
1781
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001782/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001783bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001784 CaseRecVector& WorkList,
1785 Value* SV,
1786 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001787 Case& FrontCase = *CR.Range.first;
1788 Case& BackCase = *(CR.Range.second-1);
1789
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001790 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1791 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1792
1793 uint64_t TSize = 0;
1794 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1795 I!=E; ++I)
1796 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001797
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001798 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001799 return false;
1800
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001801 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1802 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001803 return false;
1804
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001805 DOUT << "Lowering jump table\n"
1806 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001807 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001808
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001809 // Get the MachineFunction which holds the current MBB. This is used when
1810 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001811 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001812
1813 // Figure out which block is immediately after the current one.
1814 MachineBasicBlock *NextBlock = 0;
1815 MachineFunction::iterator BBI = CR.CaseBB;
1816
1817 if (++BBI != CurMBB->getParent()->end())
1818 NextBlock = BBI;
1819
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001820 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1821
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001822 // Create a new basic block to hold the code for loading the address
1823 // of the jump table, and jumping to it. Update successor information;
1824 // we will either branch to the default case for the switch, or the jump
1825 // table.
1826 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1827 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1828 CR.CaseBB->addSuccessor(Default);
1829 CR.CaseBB->addSuccessor(JumpTableBB);
1830
1831 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001832 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001833 // a case statement, push the case's BB onto the vector, otherwise, push
1834 // the default BB.
1835 std::vector<MachineBasicBlock*> DestBBs;
1836 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1838 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1839 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1840
1841 if ((Low <= TEI) && (TEI <= High)) {
1842 DestBBs.push_back(I->BB);
1843 if (TEI==High)
1844 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001845 } else {
1846 DestBBs.push_back(Default);
1847 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001848 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001849
1850 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001851 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001852 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1853 E = DestBBs.end(); I != E; ++I) {
1854 if (!SuccsHandled[(*I)->getNumber()]) {
1855 SuccsHandled[(*I)->getNumber()] = true;
1856 JumpTableBB->addSuccessor(*I);
1857 }
1858 }
1859
1860 // Create a jump table index for this jump table, or return an existing
1861 // one.
1862 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1863
1864 // Set the jump table information so that we can codegen it as a second
1865 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001866 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001867 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1868 (CR.CaseBB == CurMBB));
1869 if (CR.CaseBB == CurMBB)
1870 visitJumpTableHeader(JT, JTH);
1871
1872 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001873
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001874 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001875}
1876
1877/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1878/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001879bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880 CaseRecVector& WorkList,
1881 Value* SV,
1882 MachineBasicBlock* Default) {
1883 // Get the MachineFunction which holds the current MBB. This is used when
1884 // inserting any additional MBBs necessary to represent the switch.
1885 MachineFunction *CurMF = CurMBB->getParent();
1886
1887 // Figure out which block is immediately after the current one.
1888 MachineBasicBlock *NextBlock = 0;
1889 MachineFunction::iterator BBI = CR.CaseBB;
1890
1891 if (++BBI != CurMBB->getParent()->end())
1892 NextBlock = BBI;
1893
1894 Case& FrontCase = *CR.Range.first;
1895 Case& BackCase = *(CR.Range.second-1);
1896 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1897
1898 // Size is the number of Cases represented by this range.
1899 unsigned Size = CR.Range.second - CR.Range.first;
1900
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001901 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1902 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001903 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001904 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001905
1906 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1907 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001908 uint64_t TSize = 0;
1909 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1910 I!=E; ++I)
1911 TSize += I->size();
1912
1913 uint64_t LSize = FrontCase.size();
1914 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001915 DOUT << "Selecting best pivot: \n"
1916 << "First: " << First << ", Last: " << Last <<"\n"
1917 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001918 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001919 J!=E; ++I, ++J) {
1920 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1921 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001922 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001923 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1924 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001925 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001926 // Should always split in some non-trivial place
1927 DOUT <<"=>Step\n"
1928 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1929 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1930 << "Metric: " << Metric << "\n";
1931 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001932 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001933 FMetric = Metric;
1934 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001935 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001936
1937 LSize += J->size();
1938 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001939 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001940 if (areJTsAllowed(TLI)) {
1941 // If our case is dense we *really* should handle it earlier!
1942 assert((FMetric > 0) && "Should handle dense range earlier!");
1943 } else {
1944 Pivot = CR.Range.first + Size/2;
1945 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001946
1947 CaseRange LHSR(CR.Range.first, Pivot);
1948 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001949 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001950 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1951
1952 // We know that we branch to the LHS if the Value being switched on is
1953 // less than the Pivot value, C. We use this to optimize our binary
1954 // tree a bit, by recognizing that if SV is greater than or equal to the
1955 // LHS's Case Value, and that Case Value is exactly one less than the
1956 // Pivot's Value, then we can branch directly to the LHS's Target,
1957 // rather than creating a leaf node for it.
1958 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001959 LHSR.first->High == CR.GE &&
1960 cast<ConstantInt>(C)->getSExtValue() ==
1961 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1962 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001963 } else {
1964 TrueBB = new MachineBasicBlock(LLVMBB);
1965 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1966 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1967 }
1968
1969 // Similar to the optimization above, if the Value being switched on is
1970 // known to be less than the Constant CR.LT, and the current Case Value
1971 // is CR.LT - 1, then we can branch directly to the target block for
1972 // the current Case Value, rather than emitting a RHS leaf node for it.
1973 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001974 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1975 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1976 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001977 } else {
1978 FalseBB = new MachineBasicBlock(LLVMBB);
1979 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1980 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1981 }
1982
1983 // Create a CaseBlock record representing a conditional branch to
1984 // the LHS node if the value being switched on SV is less than C.
1985 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001986 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1987 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001988
1989 if (CR.CaseBB == CurMBB)
1990 visitSwitchCase(CB);
1991 else
1992 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001993
1994 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001995}
1996
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001997/// handleBitTestsSwitchCase - if current case range has few destination and
1998/// range span less, than machine word bitwidth, encode case range into series
1999/// of masks and emit bit tests with these masks.
2000bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2001 CaseRecVector& WorkList,
2002 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002003 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00002004 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002005
2006 Case& FrontCase = *CR.Range.first;
2007 Case& BackCase = *(CR.Range.second-1);
2008
2009 // Get the MachineFunction which holds the current MBB. This is used when
2010 // inserting any additional MBBs necessary to represent the switch.
2011 MachineFunction *CurMF = CurMBB->getParent();
2012
2013 unsigned numCmps = 0;
2014 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2015 I!=E; ++I) {
2016 // Single case counts one, case range - two.
2017 if (I->Low == I->High)
2018 numCmps +=1;
2019 else
2020 numCmps +=2;
2021 }
2022
2023 // Count unique destinations
2024 SmallSet<MachineBasicBlock*, 4> Dests;
2025 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2026 Dests.insert(I->BB);
2027 if (Dests.size() > 3)
2028 // Don't bother the code below, if there are too much unique destinations
2029 return false;
2030 }
2031 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2032 << "Total number of comparisons: " << numCmps << "\n";
2033
2034 // Compute span of values.
2035 Constant* minValue = FrontCase.Low;
2036 Constant* maxValue = BackCase.High;
2037 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2038 cast<ConstantInt>(minValue)->getSExtValue();
2039 DOUT << "Compare range: " << range << "\n"
2040 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2041 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2042
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002043 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002044 (!(Dests.size() == 1 && numCmps >= 3) &&
2045 !(Dests.size() == 2 && numCmps >= 5) &&
2046 !(Dests.size() >= 3 && numCmps >= 6)))
2047 return false;
2048
2049 DOUT << "Emitting bit tests\n";
2050 int64_t lowBound = 0;
2051
2052 // Optimize the case where all the case values fit in a
2053 // word without having to subtract minValue. In this case,
2054 // we can optimize away the subtraction.
2055 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002056 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002057 range = cast<ConstantInt>(maxValue)->getSExtValue();
2058 } else {
2059 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2060 }
2061
2062 CaseBitsVector CasesBits;
2063 unsigned i, count = 0;
2064
2065 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2066 MachineBasicBlock* Dest = I->BB;
2067 for (i = 0; i < count; ++i)
2068 if (Dest == CasesBits[i].BB)
2069 break;
2070
2071 if (i == count) {
2072 assert((count < 3) && "Too much destinations to test!");
2073 CasesBits.push_back(CaseBits(0, Dest, 0));
2074 count++;
2075 }
2076
2077 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2078 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2079
2080 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002081 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002082 CasesBits[i].Bits++;
2083 }
2084
2085 }
2086 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2087
2088 SelectionDAGISel::BitTestInfo BTC;
2089
2090 // Figure out which block is immediately after the current one.
2091 MachineFunction::iterator BBI = CR.CaseBB;
2092 ++BBI;
2093
2094 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2095
2096 DOUT << "Cases:\n";
2097 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2098 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2099 << ", BB: " << CasesBits[i].BB << "\n";
2100
2101 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2102 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2103 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2104 CaseBB,
2105 CasesBits[i].BB));
2106 }
2107
2108 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002109 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002110 CR.CaseBB, Default, BTC);
2111
2112 if (CR.CaseBB == CurMBB)
2113 visitBitTestHeader(BTB);
2114
2115 BitTestCases.push_back(BTB);
2116
2117 return true;
2118}
2119
2120
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002121/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002122unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2123 const SwitchInst& SI) {
2124 unsigned numCmps = 0;
2125
2126 // Start with "simple" cases
2127 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2128 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2129 Cases.push_back(Case(SI.getSuccessorValue(i),
2130 SI.getSuccessorValue(i),
2131 SMBB));
2132 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002133 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002134
2135 // Merge case into clusters
2136 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002137 // Must recompute end() each iteration because it may be
2138 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002139 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002140 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2141 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2142 MachineBasicBlock* nextBB = J->BB;
2143 MachineBasicBlock* currentBB = I->BB;
2144
2145 // If the two neighboring cases go to the same destination, merge them
2146 // into a single case.
2147 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2148 I->High = J->High;
2149 J = Cases.erase(J);
2150 } else {
2151 I = J++;
2152 }
2153 }
2154
2155 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2156 if (I->Low != I->High)
2157 // A range counts double, since it requires two compares.
2158 ++numCmps;
2159 }
2160
2161 return numCmps;
2162}
2163
2164void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002165 // Figure out which block is immediately after the current one.
2166 MachineBasicBlock *NextBlock = 0;
2167 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002168
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002169 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002170
Nate Begemanf15485a2006-03-27 01:32:24 +00002171 // If there is only the default destination, branch to it if it is not the
2172 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002173 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002174 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002175
Nate Begemanf15485a2006-03-27 01:32:24 +00002176 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002177 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002178 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002179 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002180
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002181 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002182 return;
2183 }
2184
2185 // If there are any non-default case statements, create a vector of Cases
2186 // representing each one, and sort the vector so that we can efficiently
2187 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002188 CaseVector Cases;
2189 unsigned numCmps = Clusterify(Cases, SI);
2190 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2191 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002192
Nate Begemanf15485a2006-03-27 01:32:24 +00002193 // Get the Value to be switched on and default basic blocks, which will be
2194 // inserted into CaseBlock records, representing basic blocks in the binary
2195 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002196 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002197
Nate Begemanf15485a2006-03-27 01:32:24 +00002198 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002199 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002200 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2201
2202 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002203 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002204 CaseRec CR = WorkList.back();
2205 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002206
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002207 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2208 continue;
2209
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002210 // If the range has few cases (two or less) emit a series of specific
2211 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002212 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2213 continue;
2214
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002215 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002216 // target supports indirect branches, then emit a jump table rather than
2217 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002218 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2219 continue;
2220
2221 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2222 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2223 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002224 }
2225}
2226
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002227
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002228void SelectionDAGLowering::visitSub(User &I) {
2229 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002230 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002231 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002232 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2233 const VectorType *DestTy = cast<VectorType>(I.getType());
2234 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002235 if (ElTy->isFloatingPoint()) {
2236 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002237 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002238 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2239 if (CV == CNZ) {
2240 SDOperand Op2 = getValue(I.getOperand(1));
2241 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2242 return;
2243 }
Dan Gohman7f321562007-06-25 16:23:39 +00002244 }
2245 }
2246 }
2247 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002248 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002249 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002250 SDOperand Op2 = getValue(I.getOperand(1));
2251 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2252 return;
2253 }
Dan Gohman7f321562007-06-25 16:23:39 +00002254 }
2255
2256 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002257}
2258
Dan Gohman7f321562007-06-25 16:23:39 +00002259void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002260 SDOperand Op1 = getValue(I.getOperand(0));
2261 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002262
2263 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002264}
2265
Nate Begemane21ea612005-11-18 07:42:56 +00002266void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2267 SDOperand Op1 = getValue(I.getOperand(0));
2268 SDOperand Op2 = getValue(I.getOperand(1));
2269
Dan Gohman7f321562007-06-25 16:23:39 +00002270 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2271 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002272 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2273 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2274 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002275
Chris Lattner1c08c712005-01-07 07:47:53 +00002276 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2277}
2278
Reid Spencer45fb3f32006-11-20 01:22:35 +00002279void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002280 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2281 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2282 predicate = IC->getPredicate();
2283 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2284 predicate = ICmpInst::Predicate(IC->getPredicate());
2285 SDOperand Op1 = getValue(I.getOperand(0));
2286 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002287 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002288 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002289 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2290 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2291 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2292 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2293 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2294 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2295 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2296 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2297 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2298 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2299 default:
2300 assert(!"Invalid ICmp predicate value");
2301 Opcode = ISD::SETEQ;
2302 break;
2303 }
2304 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2305}
2306
2307void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002308 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2309 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2310 predicate = FC->getPredicate();
2311 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2312 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002313 SDOperand Op1 = getValue(I.getOperand(0));
2314 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002315 ISD::CondCode Condition, FOC, FPC;
2316 switch (predicate) {
2317 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2318 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2319 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2320 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2321 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2322 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2323 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002324 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2325 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002326 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2327 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2328 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2329 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2330 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2331 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2332 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2333 default:
2334 assert(!"Invalid FCmp predicate value");
2335 FOC = FPC = ISD::SETFALSE;
2336 break;
2337 }
2338 if (FiniteOnlyFPMath())
2339 Condition = FOC;
2340 else
2341 Condition = FPC;
2342 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002343}
2344
2345void SelectionDAGLowering::visitSelect(User &I) {
2346 SDOperand Cond = getValue(I.getOperand(0));
2347 SDOperand TrueVal = getValue(I.getOperand(1));
2348 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002349 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2350 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002351}
2352
Reid Spencer3da59db2006-11-27 01:05:10 +00002353
2354void SelectionDAGLowering::visitTrunc(User &I) {
2355 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2356 SDOperand N = getValue(I.getOperand(0));
2357 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2358 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2359}
2360
2361void SelectionDAGLowering::visitZExt(User &I) {
2362 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2363 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2364 SDOperand N = getValue(I.getOperand(0));
2365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2366 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2367}
2368
2369void SelectionDAGLowering::visitSExt(User &I) {
2370 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2371 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2372 SDOperand N = getValue(I.getOperand(0));
2373 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2374 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2375}
2376
2377void SelectionDAGLowering::visitFPTrunc(User &I) {
2378 // FPTrunc is never a no-op cast, no need to check
2379 SDOperand N = getValue(I.getOperand(0));
2380 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002381 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002382}
2383
2384void SelectionDAGLowering::visitFPExt(User &I){
2385 // FPTrunc is never a no-op cast, no need to check
2386 SDOperand N = getValue(I.getOperand(0));
2387 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2388 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2389}
2390
2391void SelectionDAGLowering::visitFPToUI(User &I) {
2392 // FPToUI is never a no-op cast, no need to check
2393 SDOperand N = getValue(I.getOperand(0));
2394 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2395 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2396}
2397
2398void SelectionDAGLowering::visitFPToSI(User &I) {
2399 // FPToSI is never a no-op cast, no need to check
2400 SDOperand N = getValue(I.getOperand(0));
2401 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2402 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2403}
2404
2405void SelectionDAGLowering::visitUIToFP(User &I) {
2406 // UIToFP is never a no-op cast, no need to check
2407 SDOperand N = getValue(I.getOperand(0));
2408 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2409 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2410}
2411
2412void SelectionDAGLowering::visitSIToFP(User &I){
2413 // UIToFP is never a no-op cast, no need to check
2414 SDOperand N = getValue(I.getOperand(0));
2415 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2416 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2417}
2418
2419void SelectionDAGLowering::visitPtrToInt(User &I) {
2420 // What to do depends on the size of the integer and the size of the pointer.
2421 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002422 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002423 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002424 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002425 SDOperand Result;
2426 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2427 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2428 else
2429 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2430 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2431 setValue(&I, Result);
2432}
Chris Lattner1c08c712005-01-07 07:47:53 +00002433
Reid Spencer3da59db2006-11-27 01:05:10 +00002434void SelectionDAGLowering::visitIntToPtr(User &I) {
2435 // What to do depends on the size of the integer and the size of the pointer.
2436 // We can either truncate, zero extend, or no-op, accordingly.
2437 SDOperand N = getValue(I.getOperand(0));
2438 MVT::ValueType SrcVT = N.getValueType();
2439 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2440 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2441 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2442 else
2443 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2444 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2445}
2446
2447void SelectionDAGLowering::visitBitCast(User &I) {
2448 SDOperand N = getValue(I.getOperand(0));
2449 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002450
2451 // BitCast assures us that source and destination are the same size so this
2452 // is either a BIT_CONVERT or a no-op.
2453 if (DestVT != N.getValueType())
2454 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2455 else
2456 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002457}
2458
Chris Lattner2bbd8102006-03-29 00:11:43 +00002459void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002460 SDOperand InVec = getValue(I.getOperand(0));
2461 SDOperand InVal = getValue(I.getOperand(1));
2462 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2463 getValue(I.getOperand(2)));
2464
Dan Gohman7f321562007-06-25 16:23:39 +00002465 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2466 TLI.getValueType(I.getType()),
2467 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002468}
2469
Chris Lattner2bbd8102006-03-29 00:11:43 +00002470void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002471 SDOperand InVec = getValue(I.getOperand(0));
2472 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2473 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002474 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002475 TLI.getValueType(I.getType()), InVec, InIdx));
2476}
Chris Lattnerc7029802006-03-18 01:44:44 +00002477
Chris Lattner3e104b12006-04-08 04:15:24 +00002478void SelectionDAGLowering::visitShuffleVector(User &I) {
2479 SDOperand V1 = getValue(I.getOperand(0));
2480 SDOperand V2 = getValue(I.getOperand(1));
2481 SDOperand Mask = getValue(I.getOperand(2));
2482
Dan Gohman7f321562007-06-25 16:23:39 +00002483 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2484 TLI.getValueType(I.getType()),
2485 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002486}
2487
2488
Chris Lattner1c08c712005-01-07 07:47:53 +00002489void SelectionDAGLowering::visitGetElementPtr(User &I) {
2490 SDOperand N = getValue(I.getOperand(0));
2491 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002492
2493 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2494 OI != E; ++OI) {
2495 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002496 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002497 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002498 if (Field) {
2499 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002500 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002501 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002502 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002503 }
2504 Ty = StTy->getElementType(Field);
2505 } else {
2506 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002507
Chris Lattner7c0104b2005-11-09 04:45:33 +00002508 // If this is a constant subscript, handle it quickly.
2509 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002510 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002511 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002512 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002513 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2514 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002515 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002516 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002517
2518 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002519 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002520 SDOperand IdxN = getValue(Idx);
2521
2522 // If the index is smaller or larger than intptr_t, truncate or extend
2523 // it.
2524 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002525 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002526 } else if (IdxN.getValueType() > N.getValueType())
2527 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2528
2529 // If this is a multiply by a power of two, turn it into a shl
2530 // immediately. This is a very common case.
2531 if (isPowerOf2_64(ElementSize)) {
2532 unsigned Amt = Log2_64(ElementSize);
2533 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002534 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002535 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2536 continue;
2537 }
2538
Chris Lattner0bd48932008-01-17 07:00:52 +00002539 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002540 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2541 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002542 }
2543 }
2544 setValue(&I, N);
2545}
2546
2547void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2548 // If this is a fixed sized alloca in the entry block of the function,
2549 // allocate it statically on the stack.
2550 if (FuncInfo.StaticAllocaMap.count(&I))
2551 return; // getValue will auto-populate this.
2552
2553 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002554 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002555 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002556 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002557 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002558
2559 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002560 MVT::ValueType IntPtr = TLI.getPointerTy();
2561 if (IntPtr < AllocSize.getValueType())
2562 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2563 else if (IntPtr > AllocSize.getValueType())
2564 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002565
Chris Lattner68cd65e2005-01-22 23:04:37 +00002566 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002567 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002568
Evan Cheng45157792007-08-16 23:46:29 +00002569 // Handle alignment. If the requested alignment is less than or equal to
2570 // the stack alignment, ignore it. If the size is greater than or equal to
2571 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002572 unsigned StackAlign =
2573 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002574 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002575 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002576
2577 // Round the size of the allocation up to the stack alignment size
2578 // by add SA-1 to the size.
2579 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002580 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002581 // Mask out the low bits for alignment purposes.
2582 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002583 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002584
Chris Lattner0bd48932008-01-17 07:00:52 +00002585 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002586 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2587 MVT::Other);
2588 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002589 setValue(&I, DSA);
2590 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002591
2592 // Inform the Frame Information that we have just allocated a variable-sized
2593 // object.
2594 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2595}
2596
Chris Lattner1c08c712005-01-07 07:47:53 +00002597void SelectionDAGLowering::visitLoad(LoadInst &I) {
2598 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002599
Chris Lattnerd3948112005-01-17 22:19:26 +00002600 SDOperand Root;
2601 if (I.isVolatile())
2602 Root = getRoot();
2603 else {
2604 // Do not serialize non-volatile loads against each other.
2605 Root = DAG.getRoot();
2606 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002607
Evan Cheng466685d2006-10-09 20:57:25 +00002608 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002609 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002610}
2611
2612SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002613 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002614 bool isVolatile,
2615 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002616 SDOperand L =
2617 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2618 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002619
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002620 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002621 DAG.setRoot(L.getValue(1));
2622 else
2623 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002624
2625 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002626}
2627
2628
2629void SelectionDAGLowering::visitStore(StoreInst &I) {
2630 Value *SrcV = I.getOperand(0);
2631 SDOperand Src = getValue(SrcV);
2632 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002633 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002634 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002635}
2636
Chris Lattner0eade312006-03-24 02:22:33 +00002637/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2638/// node.
2639void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2640 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002641 bool HasChain = !I.doesNotAccessMemory();
2642 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2643
Chris Lattner0eade312006-03-24 02:22:33 +00002644 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002645 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002646 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2647 if (OnlyLoad) {
2648 // We don't need to serialize loads against other loads.
2649 Ops.push_back(DAG.getRoot());
2650 } else {
2651 Ops.push_back(getRoot());
2652 }
2653 }
Chris Lattner0eade312006-03-24 02:22:33 +00002654
2655 // Add the intrinsic ID as an integer operand.
2656 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2657
2658 // Add all operands of the call to the operand list.
2659 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2660 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002661 assert(TLI.isTypeLegal(Op.getValueType()) &&
2662 "Intrinsic uses a non-legal type?");
2663 Ops.push_back(Op);
2664 }
2665
2666 std::vector<MVT::ValueType> VTs;
2667 if (I.getType() != Type::VoidTy) {
2668 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002669 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002670 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002671 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2672
2673 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2674 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2675 }
2676
2677 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2678 VTs.push_back(VT);
2679 }
2680 if (HasChain)
2681 VTs.push_back(MVT::Other);
2682
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002683 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2684
Chris Lattner0eade312006-03-24 02:22:33 +00002685 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002686 SDOperand Result;
2687 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002688 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2689 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002690 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002691 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2692 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002693 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002694 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2695 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002696
Chris Lattnere58a7802006-04-02 03:41:14 +00002697 if (HasChain) {
2698 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2699 if (OnlyLoad)
2700 PendingLoads.push_back(Chain);
2701 else
2702 DAG.setRoot(Chain);
2703 }
Chris Lattner0eade312006-03-24 02:22:33 +00002704 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002705 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002706 MVT::ValueType VT = TLI.getValueType(PTy);
2707 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002708 }
2709 setValue(&I, Result);
2710 }
2711}
2712
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002713/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002714static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002715 V = IntrinsicInst::StripPointerCasts(V);
2716 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002717 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002718 "TypeInfo must be a global variable or NULL");
2719 return GV;
2720}
2721
Duncan Sandsf4070822007-06-15 19:04:19 +00002722/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002723/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002724static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2725 MachineBasicBlock *MBB) {
2726 // Inform the MachineModuleInfo of the personality for this landing pad.
2727 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2728 assert(CE->getOpcode() == Instruction::BitCast &&
2729 isa<Function>(CE->getOperand(0)) &&
2730 "Personality should be a function");
2731 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2732
2733 // Gather all the type infos for this landing pad and pass them along to
2734 // MachineModuleInfo.
2735 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002736 unsigned N = I.getNumOperands();
2737
2738 for (unsigned i = N - 1; i > 2; --i) {
2739 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2740 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002741 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002742 assert (FirstCatch <= N && "Invalid filter length");
2743
2744 if (FirstCatch < N) {
2745 TyInfo.reserve(N - FirstCatch);
2746 for (unsigned j = FirstCatch; j < N; ++j)
2747 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2748 MMI->addCatchTypeInfo(MBB, TyInfo);
2749 TyInfo.clear();
2750 }
2751
Duncan Sands6590b042007-08-27 15:47:50 +00002752 if (!FilterLength) {
2753 // Cleanup.
2754 MMI->addCleanup(MBB);
2755 } else {
2756 // Filter.
2757 TyInfo.reserve(FilterLength - 1);
2758 for (unsigned j = i + 1; j < FirstCatch; ++j)
2759 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2760 MMI->addFilterTypeInfo(MBB, TyInfo);
2761 TyInfo.clear();
2762 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002763
2764 N = i;
2765 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002766 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002767
2768 if (N > 3) {
2769 TyInfo.reserve(N - 3);
2770 for (unsigned j = 3; j < N; ++j)
2771 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002772 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002773 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002774}
2775
Mon P Wang63307c32008-05-05 19:05:59 +00002776
2777/// Inlined utility function to implement binary input atomic intrinsics for
2778// visitIntrinsicCall: I is a call instruction
2779// Op is the associated NodeType for I
2780const char *
2781SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2782 SDOperand Root = getRoot();
2783 SDOperand O2 = getValue(I.getOperand(2));
2784 SDOperand L = DAG.getAtomic(Op, Root,
2785 getValue(I.getOperand(1)),
2786 O2, O2.getValueType());
2787 setValue(&I, L);
2788 DAG.setRoot(L.getValue(1));
2789 return 0;
2790}
2791
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002792/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2793/// we want to emit this as a call to a named external function, return the name
2794/// otherwise lower it and return null.
2795const char *
2796SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2797 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002798 default:
2799 // By default, turn this into a target intrinsic node.
2800 visitTargetIntrinsic(I, Intrinsic);
2801 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002802 case Intrinsic::vastart: visitVAStart(I); return 0;
2803 case Intrinsic::vaend: visitVAEnd(I); return 0;
2804 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002805 case Intrinsic::returnaddress:
2806 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2807 getValue(I.getOperand(1))));
2808 return 0;
2809 case Intrinsic::frameaddress:
2810 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2811 getValue(I.getOperand(1))));
2812 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002813 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002814 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002815 break;
2816 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002817 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002818 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002819 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002820 case Intrinsic::memcpy_i64: {
2821 SDOperand Op1 = getValue(I.getOperand(1));
2822 SDOperand Op2 = getValue(I.getOperand(2));
2823 SDOperand Op3 = getValue(I.getOperand(3));
2824 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2825 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2826 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002827 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002828 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002829 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002830 case Intrinsic::memset_i64: {
2831 SDOperand Op1 = getValue(I.getOperand(1));
2832 SDOperand Op2 = getValue(I.getOperand(2));
2833 SDOperand Op3 = getValue(I.getOperand(3));
2834 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2835 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2836 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002837 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002838 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002839 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002840 case Intrinsic::memmove_i64: {
2841 SDOperand Op1 = getValue(I.getOperand(1));
2842 SDOperand Op2 = getValue(I.getOperand(2));
2843 SDOperand Op3 = getValue(I.getOperand(3));
2844 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2845
2846 // If the source and destination are known to not be aliases, we can
2847 // lower memmove as memcpy.
2848 uint64_t Size = -1ULL;
2849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2850 Size = C->getValue();
2851 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2852 AliasAnalysis::NoAlias) {
2853 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2854 I.getOperand(1), 0, I.getOperand(2), 0));
2855 return 0;
2856 }
2857
2858 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2859 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002860 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002861 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002862 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002863 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002864 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002865 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002866 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002867
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002868 Ops[0] = getRoot();
2869 Ops[1] = getValue(SPI.getLineValue());
2870 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002871
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002872 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002873 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002874 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2875
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002876 Ops[3] = DAG.getString(CompileUnit->getFileName());
2877 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002878
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002879 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002880 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002881
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002882 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002883 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002884 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002885 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002886 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002887 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2888 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002889 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002890 DAG.getConstant(LabelID, MVT::i32),
2891 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002892 }
2893
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002894 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002895 }
2896 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002897 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002898 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002899 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2900 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002901 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2902 DAG.getConstant(LabelID, MVT::i32),
2903 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002904 }
2905
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002906 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002907 }
2908 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002909 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002910 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002911 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002912 Value *SP = FSI.getSubprogram();
2913 if (SP && MMI->Verify(SP)) {
2914 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2915 // what (most?) gdb expects.
2916 DebugInfoDesc *DD = MMI->getDescFor(SP);
2917 assert(DD && "Not a debug information descriptor");
2918 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2919 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2920 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2921 CompileUnit->getFileName());
2922 // Record the source line but does create a label. It will be emitted
2923 // at asm emission time.
2924 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002925 }
2926
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002927 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002928 }
2929 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002930 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002931 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002932 Value *Variable = DI.getVariable();
2933 if (MMI && Variable && MMI->Verify(Variable))
2934 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2935 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002936 return 0;
2937 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002938
Jim Laskeyb180aa12007-02-21 22:53:45 +00002939 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002940 if (!CurMBB->isLandingPad()) {
2941 // FIXME: Mark exception register as live in. Hack for PR1508.
2942 unsigned Reg = TLI.getExceptionAddressRegister();
2943 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00002944 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002945 // Insert the EXCEPTIONADDR instruction.
2946 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2947 SDOperand Ops[1];
2948 Ops[0] = DAG.getRoot();
2949 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2950 setValue(&I, Op);
2951 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002952 return 0;
2953 }
2954
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002955 case Intrinsic::eh_selector_i32:
2956 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002957 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002958 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2959 MVT::i32 : MVT::i64);
2960
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002961 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002962 if (CurMBB->isLandingPad())
2963 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002964 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002965#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002966 FuncInfo.CatchInfoLost.insert(&I);
2967#endif
Duncan Sands90291952007-07-06 09:18:59 +00002968 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2969 unsigned Reg = TLI.getExceptionSelectorRegister();
2970 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002971 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002972
2973 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002974 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002975 SDOperand Ops[2];
2976 Ops[0] = getValue(I.getOperand(1));
2977 Ops[1] = getRoot();
2978 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2979 setValue(&I, Op);
2980 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002981 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002982 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002983 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002984
2985 return 0;
2986 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002987
2988 case Intrinsic::eh_typeid_for_i32:
2989 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002990 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002991 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2992 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002993
Jim Laskey735b6f82007-02-22 15:38:06 +00002994 if (MMI) {
2995 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002996 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002997
Jim Laskey735b6f82007-02-22 15:38:06 +00002998 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002999 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003000 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003001 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003002 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003003 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003004
3005 return 0;
3006 }
3007
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003008 case Intrinsic::eh_return: {
3009 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3010
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003011 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003012 MMI->setCallsEHReturn(true);
3013 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3014 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003015 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003016 getValue(I.getOperand(1)),
3017 getValue(I.getOperand(2))));
3018 } else {
3019 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3020 }
3021
3022 return 0;
3023 }
3024
3025 case Intrinsic::eh_unwind_init: {
3026 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3027 MMI->setCallsUnwindInit(true);
3028 }
3029
3030 return 0;
3031 }
3032
3033 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003034 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3035 SDOperand CfaArg;
3036 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3037 CfaArg = DAG.getNode(ISD::TRUNCATE,
3038 TLI.getPointerTy(), getValue(I.getOperand(1)));
3039 else
3040 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3041 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003042
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003043 SDOperand Offset = DAG.getNode(ISD::ADD,
3044 TLI.getPointerTy(),
3045 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3046 TLI.getPointerTy()),
3047 CfaArg);
3048 setValue(&I, DAG.getNode(ISD::ADD,
3049 TLI.getPointerTy(),
3050 DAG.getNode(ISD::FRAMEADDR,
3051 TLI.getPointerTy(),
3052 DAG.getConstant(0,
3053 TLI.getPointerTy())),
3054 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003055 return 0;
3056 }
3057
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003058 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003059 setValue(&I, DAG.getNode(ISD::FSQRT,
3060 getValue(I.getOperand(1)).getValueType(),
3061 getValue(I.getOperand(1))));
3062 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003063 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003064 setValue(&I, DAG.getNode(ISD::FPOWI,
3065 getValue(I.getOperand(1)).getValueType(),
3066 getValue(I.getOperand(1)),
3067 getValue(I.getOperand(2))));
3068 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003069 case Intrinsic::sin:
3070 setValue(&I, DAG.getNode(ISD::FSIN,
3071 getValue(I.getOperand(1)).getValueType(),
3072 getValue(I.getOperand(1))));
3073 return 0;
3074 case Intrinsic::cos:
3075 setValue(&I, DAG.getNode(ISD::FCOS,
3076 getValue(I.getOperand(1)).getValueType(),
3077 getValue(I.getOperand(1))));
3078 return 0;
3079 case Intrinsic::pow:
3080 setValue(&I, DAG.getNode(ISD::FPOW,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1)),
3083 getValue(I.getOperand(2))));
3084 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003085 case Intrinsic::pcmarker: {
3086 SDOperand Tmp = getValue(I.getOperand(1));
3087 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3088 return 0;
3089 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003090 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003091 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003092 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3093 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3094 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003095 setValue(&I, Tmp);
3096 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003097 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003098 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003099 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003100 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003101 assert(0 && "part_select intrinsic not implemented");
3102 abort();
3103 }
3104 case Intrinsic::part_set: {
3105 // Currently not implemented: just abort
3106 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003107 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003108 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003109 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003110 setValue(&I, DAG.getNode(ISD::BSWAP,
3111 getValue(I.getOperand(1)).getValueType(),
3112 getValue(I.getOperand(1))));
3113 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003114 case Intrinsic::cttz: {
3115 SDOperand Arg = getValue(I.getOperand(1));
3116 MVT::ValueType Ty = Arg.getValueType();
3117 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003118 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003119 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003120 }
3121 case Intrinsic::ctlz: {
3122 SDOperand Arg = getValue(I.getOperand(1));
3123 MVT::ValueType Ty = Arg.getValueType();
3124 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003125 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003126 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003127 }
3128 case Intrinsic::ctpop: {
3129 SDOperand Arg = getValue(I.getOperand(1));
3130 MVT::ValueType Ty = Arg.getValueType();
3131 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003132 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003133 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003134 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003135 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003136 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003137 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3138 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003139 setValue(&I, Tmp);
3140 DAG.setRoot(Tmp.getValue(1));
3141 return 0;
3142 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003143 case Intrinsic::stackrestore: {
3144 SDOperand Tmp = getValue(I.getOperand(1));
3145 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003146 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003147 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003148 case Intrinsic::var_annotation:
3149 // Discard annotate attributes
3150 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003151
Duncan Sands36397f52007-07-27 12:58:54 +00003152 case Intrinsic::init_trampoline: {
3153 const Function *F =
3154 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3155
3156 SDOperand Ops[6];
3157 Ops[0] = getRoot();
3158 Ops[1] = getValue(I.getOperand(1));
3159 Ops[2] = getValue(I.getOperand(2));
3160 Ops[3] = getValue(I.getOperand(3));
3161 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3162 Ops[5] = DAG.getSrcValue(F);
3163
Duncan Sandsf7331b32007-09-11 14:10:23 +00003164 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3165 DAG.getNodeValueTypes(TLI.getPointerTy(),
3166 MVT::Other), 2,
3167 Ops, 6);
3168
3169 setValue(&I, Tmp);
3170 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003171 return 0;
3172 }
Gordon Henriksence224772008-01-07 01:30:38 +00003173
3174 case Intrinsic::gcroot:
3175 if (GCI) {
3176 Value *Alloca = I.getOperand(1);
3177 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3178
3179 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3180 GCI->addStackRoot(FI->getIndex(), TypeMap);
3181 }
3182 return 0;
3183
3184 case Intrinsic::gcread:
3185 case Intrinsic::gcwrite:
3186 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3187 return 0;
3188
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003189 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003190 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003191 return 0;
3192 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003193
3194 case Intrinsic::trap: {
3195 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3196 return 0;
3197 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003198 case Intrinsic::prefetch: {
3199 SDOperand Ops[4];
3200 Ops[0] = getRoot();
3201 Ops[1] = getValue(I.getOperand(1));
3202 Ops[2] = getValue(I.getOperand(2));
3203 Ops[3] = getValue(I.getOperand(3));
3204 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3205 return 0;
3206 }
3207
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003208 case Intrinsic::memory_barrier: {
3209 SDOperand Ops[6];
3210 Ops[0] = getRoot();
3211 for (int x = 1; x < 6; ++x)
3212 Ops[x] = getValue(I.getOperand(x));
3213
3214 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3215 return 0;
3216 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003217 case Intrinsic::atomic_lcs: {
3218 SDOperand Root = getRoot();
3219 SDOperand O3 = getValue(I.getOperand(3));
3220 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3221 getValue(I.getOperand(1)),
3222 getValue(I.getOperand(2)),
3223 O3, O3.getValueType());
3224 setValue(&I, L);
3225 DAG.setRoot(L.getValue(1));
3226 return 0;
3227 }
Mon P Wang63307c32008-05-05 19:05:59 +00003228 case Intrinsic::atomic_las:
3229 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3230 case Intrinsic::atomic_lss:
3231 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3232 case Intrinsic::atomic_load_and:
3233 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3234 case Intrinsic::atomic_load_or:
3235 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3236 case Intrinsic::atomic_load_xor:
3237 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3238 case Intrinsic::atomic_load_min:
3239 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3240 case Intrinsic::atomic_load_max:
3241 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3242 case Intrinsic::atomic_load_umin:
3243 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3244 case Intrinsic::atomic_load_umax:
3245 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3246 case Intrinsic::atomic_swap:
3247 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003248 }
3249}
3250
3251
Duncan Sands6f74b482007-12-19 09:48:52 +00003252void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003253 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003254 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003255 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003256 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003257 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3258 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003259
Jim Laskey735b6f82007-02-22 15:38:06 +00003260 TargetLowering::ArgListTy Args;
3261 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003262 Args.reserve(CS.arg_size());
3263 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3264 i != e; ++i) {
3265 SDOperand ArgNode = getValue(*i);
3266 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003267
Duncan Sands6f74b482007-12-19 09:48:52 +00003268 unsigned attrInd = i - CS.arg_begin() + 1;
3269 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3270 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3271 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3272 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3273 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3274 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003275 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003276 Args.push_back(Entry);
3277 }
3278
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003279 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003280 // Insert a label before the invoke call to mark the try range. This can be
3281 // used to detect deletion of the invoke via the MachineModuleInfo.
3282 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003283 // Both PendingLoads and PendingExports must be flushed here;
3284 // this call might not return.
3285 (void)getRoot();
3286 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003287 DAG.getConstant(BeginLabel, MVT::i32),
3288 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003289 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003290
Jim Laskey735b6f82007-02-22 15:38:06 +00003291 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003292 TLI.LowerCallTo(getRoot(), CS.getType(),
3293 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003294 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003295 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003296 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003297 if (CS.getType() != Type::VoidTy)
3298 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003299 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003300
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003301 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003302 // Insert a label at the end of the invoke call to mark the try range. This
3303 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3304 EndLabel = MMI->NextLabelID();
3305 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003306 DAG.getConstant(EndLabel, MVT::i32),
3307 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003308
Duncan Sands6f74b482007-12-19 09:48:52 +00003309 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003310 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3311 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003312}
3313
3314
Chris Lattner1c08c712005-01-07 07:47:53 +00003315void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003316 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003317 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003318 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003319 if (unsigned IID = F->getIntrinsicID()) {
3320 RenameFn = visitIntrinsicCall(I, IID);
3321 if (!RenameFn)
3322 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003323 }
3324 }
3325
3326 // Check for well-known libc/libm calls. If the function is internal, it
3327 // can't be a library call.
3328 unsigned NameLen = F->getNameLen();
3329 if (!F->hasInternalLinkage() && NameLen) {
3330 const char *NameStr = F->getNameStart();
3331 if (NameStr[0] == 'c' &&
3332 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3333 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3334 if (I.getNumOperands() == 3 && // Basic sanity checks.
3335 I.getOperand(1)->getType()->isFloatingPoint() &&
3336 I.getType() == I.getOperand(1)->getType() &&
3337 I.getType() == I.getOperand(2)->getType()) {
3338 SDOperand LHS = getValue(I.getOperand(1));
3339 SDOperand RHS = getValue(I.getOperand(2));
3340 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3341 LHS, RHS));
3342 return;
3343 }
3344 } else if (NameStr[0] == 'f' &&
3345 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003346 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3347 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003348 if (I.getNumOperands() == 2 && // Basic sanity checks.
3349 I.getOperand(1)->getType()->isFloatingPoint() &&
3350 I.getType() == I.getOperand(1)->getType()) {
3351 SDOperand Tmp = getValue(I.getOperand(1));
3352 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3353 return;
3354 }
3355 } else if (NameStr[0] == 's' &&
3356 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003357 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3358 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003359 if (I.getNumOperands() == 2 && // Basic sanity checks.
3360 I.getOperand(1)->getType()->isFloatingPoint() &&
3361 I.getType() == I.getOperand(1)->getType()) {
3362 SDOperand Tmp = getValue(I.getOperand(1));
3363 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3364 return;
3365 }
3366 } else if (NameStr[0] == 'c' &&
3367 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003368 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3369 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003370 if (I.getNumOperands() == 2 && // Basic sanity checks.
3371 I.getOperand(1)->getType()->isFloatingPoint() &&
3372 I.getType() == I.getOperand(1)->getType()) {
3373 SDOperand Tmp = getValue(I.getOperand(1));
3374 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3375 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003376 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003377 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003378 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003379 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003380 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003381 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003382 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003383
Chris Lattner64e14b12005-01-08 22:48:57 +00003384 SDOperand Callee;
3385 if (!RenameFn)
3386 Callee = getValue(I.getOperand(0));
3387 else
3388 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003389
Duncan Sands6f74b482007-12-19 09:48:52 +00003390 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003391}
3392
Jim Laskey735b6f82007-02-22 15:38:06 +00003393
Dan Gohmanef5d1942008-03-11 21:11:25 +00003394void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003395 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003396 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3397 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003398 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003399 }
Chris Lattner6833b062008-04-28 07:16:35 +00003400
3401 // To add support for individual return values with aggregate types,
3402 // we'd need a way to take a getresult index and determine which
3403 // values of the Call SDNode are associated with it.
3404 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3405 "Individual return values must not be aggregates!");
3406
3407 SDOperand Call = getValue(I.getOperand(0));
3408 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003409}
3410
3411
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003412/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3413/// this value and returns the result as a ValueVT value. This uses
3414/// Chain/Flag as the input and updates them for the output Chain/Flag.
3415/// If the Flag pointer is NULL, no flag is used.
3416SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003417 SDOperand &Chain,
3418 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003419 // Assemble the legal parts into the final values.
3420 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003421 SmallVector<SDOperand, 8> Parts;
3422 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003423 // Copy the legal parts from the registers.
3424 MVT::ValueType ValueVT = ValueVTs[Value];
3425 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3426 MVT::ValueType RegisterVT = RegVTs[Value];
3427
Chris Lattner6833b062008-04-28 07:16:35 +00003428 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003429 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003430 SDOperand P;
3431 if (Flag == 0)
3432 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3433 else {
3434 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003435 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003436 }
3437 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003438 Parts[Part+i] = P;
3439 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003440
Dan Gohman23ce5022008-04-25 18:27:55 +00003441 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3442 ValueVT);
3443 Part += NumRegs;
3444 }
Chris Lattner6833b062008-04-28 07:16:35 +00003445
3446 if (ValueVTs.size() == 1)
3447 return Values[0];
3448
Dan Gohman23ce5022008-04-25 18:27:55 +00003449 return DAG.getNode(ISD::MERGE_VALUES,
3450 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3451 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003452}
3453
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003454/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3455/// specified value into the registers specified by this object. This uses
3456/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003457/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003458void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003459 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003460 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003461 unsigned NumRegs = Regs.size();
3462 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003463 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003464 MVT::ValueType ValueVT = ValueVTs[Value];
3465 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3466 MVT::ValueType RegisterVT = RegVTs[Value];
3467
3468 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3469 &Parts[Part], NumParts, RegisterVT);
3470 Part += NumParts;
3471 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003472
3473 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003474 SmallVector<SDOperand, 8> Chains(NumRegs);
3475 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003476 SDOperand Part;
3477 if (Flag == 0)
3478 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3479 else {
3480 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003481 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003482 }
3483 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003484 }
Chris Lattner6833b062008-04-28 07:16:35 +00003485
Evan Cheng33bf38a2008-04-28 22:07:13 +00003486 if (NumRegs == 1 || Flag)
3487 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3488 // flagged to it. That is the CopyToReg nodes and the user are considered
3489 // a single scheduling unit. If we create a TokenFactor and return it as
3490 // chain, then the TokenFactor is both a predecessor (operand) of the
3491 // user as well as a successor (the TF operands are flagged to the user).
3492 // c1, f1 = CopyToReg
3493 // c2, f2 = CopyToReg
3494 // c3 = TokenFactor c1, c2
3495 // ...
3496 // = op c3, ..., f2
3497 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003498 else
3499 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003500}
Chris Lattner864635a2006-02-22 22:37:12 +00003501
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003502/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3503/// operand list. This adds the code marker and includes the number of
3504/// values added into it.
3505void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003506 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003507 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3508 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003509 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3510 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003511 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003512 for (unsigned i = 0; i != NumRegs; ++i)
3513 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003514 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003515}
Chris Lattner864635a2006-02-22 22:37:12 +00003516
3517/// isAllocatableRegister - If the specified register is safe to allocate,
3518/// i.e. it isn't a stack pointer or some other special register, return the
3519/// register class for the register. Otherwise, return null.
3520static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003521isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003522 const TargetLowering &TLI,
3523 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003524 MVT::ValueType FoundVT = MVT::Other;
3525 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003526 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3527 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003528 MVT::ValueType ThisVT = MVT::Other;
3529
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003530 const TargetRegisterClass *RC = *RCI;
3531 // If none of the the value types for this register class are valid, we
3532 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003533 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3534 I != E; ++I) {
3535 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003536 // If we have already found this register in a different register class,
3537 // choose the one with the largest VT specified. For example, on
3538 // PowerPC, we favor f64 register classes over f32.
3539 if (FoundVT == MVT::Other ||
3540 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3541 ThisVT = *I;
3542 break;
3543 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003544 }
3545 }
3546
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003547 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003548
Chris Lattner864635a2006-02-22 22:37:12 +00003549 // NOTE: This isn't ideal. In particular, this might allocate the
3550 // frame pointer in functions that need it (due to them not being taken
3551 // out of allocation, because a variable sized allocation hasn't been seen
3552 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003553 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3554 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003555 if (*I == Reg) {
3556 // We found a matching register class. Keep looking at others in case
3557 // we find one with larger registers that this physreg is also in.
3558 FoundRC = RC;
3559 FoundVT = ThisVT;
3560 break;
3561 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003562 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003563 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003564}
3565
Chris Lattner4e4b5762006-02-01 18:59:47 +00003566
Chris Lattner0c583402007-04-28 20:49:53 +00003567namespace {
3568/// AsmOperandInfo - This contains information for each constraint that we are
3569/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003570struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3571 /// CallOperand - If this is the result output operand or a clobber
3572 /// this is null, otherwise it is the incoming operand to the CallInst.
3573 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003574 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003575
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003576 /// AssignedRegs - If this is a register or register class operand, this
3577 /// contains the set of register corresponding to the operand.
3578 RegsForValue AssignedRegs;
3579
Dan Gohman23ce5022008-04-25 18:27:55 +00003580 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003581 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003582 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003583
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003584 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3585 /// busy in OutputRegs/InputRegs.
3586 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3587 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003588 std::set<unsigned> &InputRegs,
3589 const TargetRegisterInfo &TRI) const {
3590 if (isOutReg) {
3591 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3592 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3593 }
3594 if (isInReg) {
3595 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3596 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3597 }
3598 }
3599
3600private:
3601 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3602 /// specified set.
3603 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3604 const TargetRegisterInfo &TRI) {
3605 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3606 Regs.insert(Reg);
3607 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3608 for (; *Aliases; ++Aliases)
3609 Regs.insert(*Aliases);
3610 }
Chris Lattner0c583402007-04-28 20:49:53 +00003611};
3612} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003613
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003614
Chris Lattner0fe71e92008-02-21 19:43:13 +00003615/// GetRegistersForValue - Assign registers (virtual or physical) for the
3616/// specified operand. We prefer to assign virtual registers, to allow the
3617/// register allocator handle the assignment process. However, if the asm uses
3618/// features that we can't model on machineinstrs, we have SDISel do the
3619/// allocation. This produces generally horrible, but correct, code.
3620///
3621/// OpInfo describes the operand.
3622/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3623/// or any explicitly clobbered registers.
3624/// Input and OutputRegs are the set of already allocated physical registers.
3625///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003626void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003627GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003628 std::set<unsigned> &OutputRegs,
3629 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003630 // Compute whether this value requires an input register, an output register,
3631 // or both.
3632 bool isOutReg = false;
3633 bool isInReg = false;
3634 switch (OpInfo.Type) {
3635 case InlineAsm::isOutput:
3636 isOutReg = true;
3637
3638 // If this is an early-clobber output, or if there is an input
3639 // constraint that matches this, we need to reserve the input register
3640 // so no other inputs allocate to it.
3641 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3642 break;
3643 case InlineAsm::isInput:
3644 isInReg = true;
3645 isOutReg = false;
3646 break;
3647 case InlineAsm::isClobber:
3648 isOutReg = true;
3649 isInReg = true;
3650 break;
3651 }
3652
3653
3654 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003655 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003656
3657 // If this is a constraint for a single physreg, or a constraint for a
3658 // register class, find it.
3659 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3660 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3661 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003662
3663 unsigned NumRegs = 1;
3664 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003665 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003666 MVT::ValueType RegVT;
3667 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3668
Chris Lattnerbf996f12007-04-30 17:29:31 +00003669
3670 // If this is a constraint for a specific physical register, like {r17},
3671 // assign it now.
3672 if (PhysReg.first) {
3673 if (OpInfo.ConstraintVT == MVT::Other)
3674 ValueVT = *PhysReg.second->vt_begin();
3675
3676 // Get the actual register value type. This is important, because the user
3677 // may have asked for (e.g.) the AX register in i32 type. We need to
3678 // remember that AX is actually i16 to get the right extension.
3679 RegVT = *PhysReg.second->vt_begin();
3680
3681 // This is a explicit reference to a physical register.
3682 Regs.push_back(PhysReg.first);
3683
3684 // If this is an expanded reference, add the rest of the regs to Regs.
3685 if (NumRegs != 1) {
3686 TargetRegisterClass::iterator I = PhysReg.second->begin();
3687 TargetRegisterClass::iterator E = PhysReg.second->end();
3688 for (; *I != PhysReg.first; ++I)
3689 assert(I != E && "Didn't find reg!");
3690
3691 // Already added the first reg.
3692 --NumRegs; ++I;
3693 for (; NumRegs; --NumRegs, ++I) {
3694 assert(I != E && "Ran out of registers to allocate!");
3695 Regs.push_back(*I);
3696 }
3697 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003698 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003699 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3700 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003701 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003702 }
3703
3704 // Otherwise, if this was a reference to an LLVM register class, create vregs
3705 // for this reference.
3706 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003707 const TargetRegisterClass *RC = PhysReg.second;
3708 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003709 // If this is an early clobber or tied register, our regalloc doesn't know
3710 // how to maintain the constraint. If it isn't, go ahead and create vreg
3711 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003712 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3713 // If there is some other early clobber and this is an input register,
3714 // then we are forced to pre-allocate the input reg so it doesn't
3715 // conflict with the earlyclobber.
3716 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003717 RegVT = *PhysReg.second->vt_begin();
3718
3719 if (OpInfo.ConstraintVT == MVT::Other)
3720 ValueVT = RegVT;
3721
3722 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003723 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003724 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003725 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003726
Dan Gohman23ce5022008-04-25 18:27:55 +00003727 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003728 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003729 }
3730
3731 // Otherwise, we can't allocate it. Let the code below figure out how to
3732 // maintain these constraints.
3733 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3734
3735 } else {
3736 // This is a reference to a register class that doesn't directly correspond
3737 // to an LLVM register class. Allocate NumRegs consecutive, available,
3738 // registers from the class.
3739 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3740 OpInfo.ConstraintVT);
3741 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003742
Dan Gohman6f0d0242008-02-10 18:45:23 +00003743 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003744 unsigned NumAllocated = 0;
3745 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3746 unsigned Reg = RegClassRegs[i];
3747 // See if this register is available.
3748 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3749 (isInReg && InputRegs.count(Reg))) { // Already used.
3750 // Make sure we find consecutive registers.
3751 NumAllocated = 0;
3752 continue;
3753 }
3754
3755 // Check to see if this register is allocatable (i.e. don't give out the
3756 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003757 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003758 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003759 if (!RC) { // Couldn't allocate this register.
3760 // Reset NumAllocated to make sure we return consecutive registers.
3761 NumAllocated = 0;
3762 continue;
3763 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003764 }
3765
3766 // Okay, this register is good, we can use it.
3767 ++NumAllocated;
3768
3769 // If we allocated enough consecutive registers, succeed.
3770 if (NumAllocated == NumRegs) {
3771 unsigned RegStart = (i-NumAllocated)+1;
3772 unsigned RegEnd = i+1;
3773 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003774 for (unsigned i = RegStart; i != RegEnd; ++i)
3775 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003776
Dan Gohman23ce5022008-04-25 18:27:55 +00003777 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003778 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003779 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003780 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003781 }
3782 }
3783
3784 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003785}
3786
3787
Chris Lattnerce7518c2006-01-26 22:24:51 +00003788/// visitInlineAsm - Handle a call to an InlineAsm object.
3789///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003790void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3791 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003792
Chris Lattner0c583402007-04-28 20:49:53 +00003793 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003794 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003795
3796 SDOperand Chain = getRoot();
3797 SDOperand Flag;
3798
Chris Lattner4e4b5762006-02-01 18:59:47 +00003799 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003800
Chris Lattner0c583402007-04-28 20:49:53 +00003801 // Do a prepass over the constraints, canonicalizing them, and building up the
3802 // ConstraintOperands list.
3803 std::vector<InlineAsm::ConstraintInfo>
3804 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003805
3806 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3807 // constraint. If so, we can't let the register allocator allocate any input
3808 // registers, because it will not know to avoid the earlyclobbered output reg.
3809 bool SawEarlyClobber = false;
3810
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003811 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003812 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003813 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003814 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3815 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003816
Chris Lattner0c583402007-04-28 20:49:53 +00003817 MVT::ValueType OpVT = MVT::Other;
3818
3819 // Compute the value type for each operand.
3820 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003821 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003822 // Indirect outputs just consume an argument.
3823 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003824 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003825 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003826 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003827 // The return value of the call is this value. As such, there is no
3828 // corresponding argument.
3829 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3830 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3831 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3832 } else {
3833 assert(ResNo == 0 && "Asm only has one result!");
3834 OpVT = TLI.getValueType(CS.getType());
3835 }
3836 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003837 break;
3838 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003839 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003840 break;
3841 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003842 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003843 break;
3844 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003845
Chris Lattner0c583402007-04-28 20:49:53 +00003846 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003847 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003848 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003849 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3850 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003851 else {
3852 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3853 const Type *OpTy = OpInfo.CallOperandVal->getType();
3854 // If this is an indirect operand, the operand is a pointer to the
3855 // accessed type.
3856 if (OpInfo.isIndirect)
3857 OpTy = cast<PointerType>(OpTy)->getElementType();
3858
3859 // If OpTy is not a first-class value, it may be a struct/union that we
3860 // can tile with integers.
3861 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3862 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3863 switch (BitSize) {
3864 default: break;
3865 case 1:
3866 case 8:
3867 case 16:
3868 case 32:
3869 case 64:
3870 OpTy = IntegerType::get(BitSize);
3871 break;
3872 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003873 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003874
3875 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003876 }
3877 }
3878
3879 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003880
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003881 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003882 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003883
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003884 // Keep track of whether we see an earlyclobber.
3885 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003886
Chris Lattner0fe71e92008-02-21 19:43:13 +00003887 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003888 if (!SawEarlyClobber &&
3889 OpInfo.Type == InlineAsm::isClobber &&
3890 OpInfo.ConstraintType == TargetLowering::C_Register) {
3891 // Note that we want to ignore things that we don't trick here, like
3892 // dirflag, fpsr, flags, etc.
3893 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3894 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3895 OpInfo.ConstraintVT);
3896 if (PhysReg.first || PhysReg.second) {
3897 // This is a register we know of.
3898 SawEarlyClobber = true;
3899 }
3900 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003901
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003902 // If this is a memory input, and if the operand is not indirect, do what we
3903 // need to to provide an address for the memory input.
3904 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3905 !OpInfo.isIndirect) {
3906 assert(OpInfo.Type == InlineAsm::isInput &&
3907 "Can only indirectify direct input operands!");
3908
3909 // Memory operands really want the address of the value. If we don't have
3910 // an indirect input, put it in the constpool if we can, otherwise spill
3911 // it to a stack slot.
3912
3913 // If the operand is a float, integer, or vector constant, spill to a
3914 // constant pool entry to get its address.
3915 Value *OpVal = OpInfo.CallOperandVal;
3916 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3917 isa<ConstantVector>(OpVal)) {
3918 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3919 TLI.getPointerTy());
3920 } else {
3921 // Otherwise, create a stack slot and emit a store to it before the
3922 // asm.
3923 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003924 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003925 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3926 MachineFunction &MF = DAG.getMachineFunction();
3927 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3928 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3929 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3930 OpInfo.CallOperand = StackSlot;
3931 }
3932
3933 // There is no longer a Value* corresponding to this operand.
3934 OpInfo.CallOperandVal = 0;
3935 // It is now an indirect operand.
3936 OpInfo.isIndirect = true;
3937 }
3938
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003939 // If this constraint is for a specific register, allocate it before
3940 // anything else.
3941 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3942 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003943 }
Chris Lattner0c583402007-04-28 20:49:53 +00003944 ConstraintInfos.clear();
3945
3946
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003947 // Second pass - Loop over all of the operands, assigning virtual or physregs
3948 // to registerclass operands.
3949 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003950 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003951
3952 // C_Register operands have already been allocated, Other/Memory don't need
3953 // to be.
3954 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3955 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3956 }
3957
Chris Lattner0c583402007-04-28 20:49:53 +00003958 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3959 std::vector<SDOperand> AsmNodeOperands;
3960 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3961 AsmNodeOperands.push_back(
3962 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3963
Chris Lattner2cc2f662006-02-01 01:28:23 +00003964
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003965 // Loop over all of the inputs, copying the operand values into the
3966 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003967 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00003968
Chris Lattner0c583402007-04-28 20:49:53 +00003969 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3970 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3971
3972 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003973 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003974
Chris Lattner0c583402007-04-28 20:49:53 +00003975 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003976 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003977 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3978 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003979 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003980 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003981
Chris Lattner22873462006-02-27 23:45:39 +00003982 // Add information to the INLINEASM node to know about this output.
3983 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003984 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3985 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003986 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003987 break;
3988 }
3989
Chris Lattner2a600be2007-04-28 21:01:43 +00003990 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003991
Chris Lattner864635a2006-02-22 22:37:12 +00003992 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003993 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003994 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003995 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003996 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003997 exit(1);
3998 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003999
Chris Lattner41f62592008-04-29 04:29:54 +00004000 // If this is an indirect operand, store through the pointer after the
4001 // asm.
4002 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004003 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004004 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004005 } else {
4006 // This is the result value of the call.
4007 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4008 // Concatenate this output onto the outputs list.
4009 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004010 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004011
4012 // Add information to the INLINEASM node to know that this register is
4013 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004014 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4015 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004016 break;
4017 }
4018 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004019 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004020
Chris Lattner0c583402007-04-28 20:49:53 +00004021 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004022 // If this is required to match an output register we have already set,
4023 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004024 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004025
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004026 // Scan until we find the definition we already emitted of this operand.
4027 // When we find it, create a RegsForValue operand.
4028 unsigned CurOp = 2; // The first operand.
4029 for (; OperandNo; --OperandNo) {
4030 // Advance to the next operand.
4031 unsigned NumOps =
4032 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004033 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4034 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004035 "Skipped past definitions?");
4036 CurOp += (NumOps>>3)+1;
4037 }
4038
4039 unsigned NumOps =
4040 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004041 if ((NumOps & 7) == 2 /*REGDEF*/) {
4042 // Add NumOps>>3 registers to MatchedRegs.
4043 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004044 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004045 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4046 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004047 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4048 unsigned Reg =
4049 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4050 MatchedRegs.Regs.push_back(Reg);
4051 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004052
Chris Lattner527fae12007-02-01 01:21:12 +00004053 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004054 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004055 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4056 break;
4057 } else {
4058 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004059 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4060 // Add information to the INLINEASM node to know about this input.
4061 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4062 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4063 TLI.getPointerTy()));
4064 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4065 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004066 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004067 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004068
Chris Lattner2a600be2007-04-28 21:01:43 +00004069 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004070 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004071 "Don't know how to handle indirect other inputs yet!");
4072
Chris Lattner48884cd2007-08-25 00:47:38 +00004073 std::vector<SDOperand> Ops;
4074 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4075 Ops, DAG);
4076 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004077 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004078 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004079 exit(1);
4080 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004081
4082 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004083 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004084 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4085 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004086 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004087 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004088 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004089 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004090 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4091 "Memory operands expect pointer values");
4092
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004093 // Add information to the INLINEASM node to know about this input.
4094 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004095 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4096 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004097 AsmNodeOperands.push_back(InOperandVal);
4098 break;
4099 }
4100
Chris Lattner2a600be2007-04-28 21:01:43 +00004101 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4102 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4103 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004104 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004105 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004106
4107 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004108 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4109 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004110
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004111 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004112
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004113 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4114 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004115 break;
4116 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004117 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004118 // Add the clobbered value to the operand list, so that the register
4119 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004120 if (!OpInfo.AssignedRegs.Regs.empty())
4121 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4122 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004123 break;
4124 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004125 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004126 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004127
4128 // Finish up input operands.
4129 AsmNodeOperands[0] = Chain;
4130 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4131
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004132 Chain = DAG.getNode(ISD::INLINEASM,
4133 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004134 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004135 Flag = Chain.getValue(1);
4136
Chris Lattner6656dd12006-01-31 02:03:41 +00004137 // If this asm returns a register value, copy the result from that register
4138 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004139 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004140 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004141
4142 // If any of the results of the inline asm is a vector, it may have the
4143 // wrong width/num elts. This can happen for register classes that can
4144 // contain multiple different value types. The preg or vreg allocated may
4145 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004146 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004147 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4148 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4149 if (MVT::isVector(Val.Val->getValueType(i)))
4150 Val = DAG.getNode(ISD::BIT_CONVERT,
4151 TLI.getValueType(ResSTy->getElementType(i)), Val);
4152 }
4153 } else {
4154 if (MVT::isVector(Val.getValueType()))
4155 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4156 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004157 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004158
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004159 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004160 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004161
Chris Lattner6656dd12006-01-31 02:03:41 +00004162 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4163
4164 // Process indirect outputs, first output all of the flagged copies out of
4165 // physregs.
4166 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004167 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004168 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004169 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004170 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004171 }
4172
4173 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004174 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004175 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004176 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004177 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004178 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004179 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004180 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4181 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004182 DAG.setRoot(Chain);
4183}
4184
4185
Chris Lattner1c08c712005-01-07 07:47:53 +00004186void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4187 SDOperand Src = getValue(I.getOperand(0));
4188
4189 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004190
4191 if (IntPtr < Src.getValueType())
4192 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4193 else if (IntPtr > Src.getValueType())
4194 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004195
4196 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004197 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004198 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004199 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004200
Reid Spencer47857812006-12-31 05:55:36 +00004201 TargetLowering::ArgListTy Args;
4202 TargetLowering::ArgListEntry Entry;
4203 Entry.Node = Src;
4204 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004205 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004206
4207 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004208 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4209 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004210 setValue(&I, Result.first); // Pointers always fit in registers
4211 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004212}
4213
4214void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004215 TargetLowering::ArgListTy Args;
4216 TargetLowering::ArgListEntry Entry;
4217 Entry.Node = getValue(I.getOperand(0));
4218 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004219 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004220 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004221 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004222 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4223 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004224 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4225 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004226}
4227
Evan Chengff9b3732008-01-30 18:18:23 +00004228// EmitInstrWithCustomInserter - This method should be implemented by targets
4229// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004230// instructions are special in various ways, which require special support to
4231// insert. The specified MachineInstr is created but not inserted into any
4232// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004233MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004234 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004235 cerr << "If a target marks an instruction with "
4236 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004237 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004238 abort();
4239 return 0;
4240}
4241
Chris Lattner39ae3622005-01-09 00:00:49 +00004242void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004243 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4244 getValue(I.getOperand(1)),
4245 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004246}
4247
4248void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004249 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4250 getValue(I.getOperand(0)),
4251 DAG.getSrcValue(I.getOperand(0)));
4252 setValue(&I, V);
4253 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004254}
4255
4256void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004257 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4258 getValue(I.getOperand(1)),
4259 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004260}
4261
4262void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004263 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4264 getValue(I.getOperand(1)),
4265 getValue(I.getOperand(2)),
4266 DAG.getSrcValue(I.getOperand(1)),
4267 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004268}
4269
Chris Lattnerfdfded52006-04-12 16:20:43 +00004270/// TargetLowering::LowerArguments - This is the default LowerArguments
4271/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004272/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4273/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004274std::vector<SDOperand>
4275TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4276 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4277 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004278 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004279 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4280 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4281
4282 // Add one result value for each formal argument.
4283 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004284 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004285 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4286 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004287 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004288 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004289 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004290 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004291
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004292 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004293 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004294 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004295 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004296 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004297 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004298 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004299 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004300 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004301 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004302 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004303 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004304 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004305 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004306 // For ByVal, alignment should be passed from FE. BE will guess if
4307 // this info is not there but there are cases it cannot get right.
4308 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004309 FrameAlign = F.getParamAlignment(j);
4310 Flags.setByValAlign(FrameAlign);
4311 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004312 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004313 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004314 Flags.setNest();
4315 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004316
4317 MVT::ValueType RegisterVT = getRegisterType(VT);
4318 unsigned NumRegs = getNumRegisters(VT);
4319 for (unsigned i = 0; i != NumRegs; ++i) {
4320 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004321 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004322 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004323 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004324 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004325 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004326 MyFlags.setOrigAlign(1);
4327 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004328 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004329 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004330
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004331 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004332
4333 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004334 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004335 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004336 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004337
4338 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4339 // allows exposing the loads that may be part of the argument access to the
4340 // first DAGCombiner pass.
4341 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4342
4343 // The number of results should match up, except that the lowered one may have
4344 // an extra flag result.
4345 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4346 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4347 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4348 && "Lowering produced unexpected number of results!");
4349 Result = TmpRes.Val;
4350
Dan Gohman27a70be2007-07-02 16:18:06 +00004351 unsigned NumArgRegs = Result->getNumValues() - 1;
4352 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004353
4354 // Set up the return result vector.
4355 Ops.clear();
4356 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004357 unsigned Idx = 1;
4358 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4359 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004360 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004361 MVT::ValueType PartVT = getRegisterType(VT);
4362
4363 unsigned NumParts = getNumRegisters(VT);
4364 SmallVector<SDOperand, 4> Parts(NumParts);
4365 for (unsigned j = 0; j != NumParts; ++j)
4366 Parts[j] = SDOperand(Result, i++);
4367
4368 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4369 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4370 AssertOp = ISD::AssertSext;
4371 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4372 AssertOp = ISD::AssertZext;
4373
4374 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004375 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004376 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004377 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004378 return Ops;
4379}
4380
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004381
4382/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4383/// implementation, which just inserts an ISD::CALL node, which is later custom
4384/// lowered by the target to something concrete. FIXME: When all targets are
4385/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4386std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004387TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4388 bool RetSExt, bool RetZExt, bool isVarArg,
4389 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004390 SDOperand Callee,
4391 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004392 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004393 Ops.push_back(Chain); // Op#0 - Chain
4394 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4395 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4396 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4397 Ops.push_back(Callee);
4398
4399 // Handle all of the outgoing arguments.
4400 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004401 MVT::ValueType VT = getValueType(Args[i].Ty);
4402 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004403 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004404 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004405 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004406
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004407 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004408 Flags.setZExt();
4409 if (Args[i].isSExt)
4410 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004411 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004412 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004413 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004414 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004415 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004416 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004417 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004418 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004419 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004420 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004421 // For ByVal, alignment should come from FE. BE will guess if this
4422 // info is not there but there are cases it cannot get right.
4423 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004424 FrameAlign = Args[i].Alignment;
4425 Flags.setByValAlign(FrameAlign);
4426 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004427 }
Duncan Sands36397f52007-07-27 12:58:54 +00004428 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004429 Flags.setNest();
4430 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004431
Duncan Sandsb988bac2008-02-11 20:58:28 +00004432 MVT::ValueType PartVT = getRegisterType(VT);
4433 unsigned NumParts = getNumRegisters(VT);
4434 SmallVector<SDOperand, 4> Parts(NumParts);
4435 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4436
4437 if (Args[i].isSExt)
4438 ExtendKind = ISD::SIGN_EXTEND;
4439 else if (Args[i].isZExt)
4440 ExtendKind = ISD::ZERO_EXTEND;
4441
4442 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4443
4444 for (unsigned i = 0; i != NumParts; ++i) {
4445 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004446 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004447 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004448 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004449 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004450 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004451
4452 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004453 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004454 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004455 }
4456
Dan Gohmanef5d1942008-03-11 21:11:25 +00004457 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004458 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004459 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4460 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004461 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004462
Dan Gohman23ce5022008-04-25 18:27:55 +00004463 // Then we translate that to a list of legal types.
4464 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4465 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004466 MVT::ValueType RegisterVT = getRegisterType(VT);
4467 unsigned NumRegs = getNumRegisters(VT);
4468 for (unsigned i = 0; i != NumRegs; ++i)
4469 LoweredRetTys.push_back(RegisterVT);
4470 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004471
Dan Gohmanef5d1942008-03-11 21:11:25 +00004472 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004473
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004474 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004475 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004476 DAG.getVTList(&LoweredRetTys[0],
4477 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004478 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004479 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004480
4481 // Gather up the call result into a single value.
4482 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004483 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4484
4485 if (RetSExt)
4486 AssertOp = ISD::AssertSext;
4487 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004488 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004489
Dan Gohmanef5d1942008-03-11 21:11:25 +00004490 SmallVector<SDOperand, 4> ReturnValues;
4491 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004492 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4493 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004494 MVT::ValueType RegisterVT = getRegisterType(VT);
4495 unsigned NumRegs = getNumRegisters(VT);
4496 unsigned RegNoEnd = NumRegs + RegNo;
4497 SmallVector<SDOperand, 4> Results;
4498 for (; RegNo != RegNoEnd; ++RegNo)
4499 Results.push_back(Res.getValue(RegNo));
4500 SDOperand ReturnValue =
4501 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4502 AssertOp);
4503 ReturnValues.push_back(ReturnValue);
4504 }
4505 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4506 DAG.getNode(ISD::MERGE_VALUES,
4507 DAG.getVTList(&RetTys[0], RetTys.size()),
4508 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004509 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004510
4511 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004512}
4513
Chris Lattner50381b62005-05-14 05:50:48 +00004514SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004515 assert(0 && "LowerOperation not implemented for this target!");
4516 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004517 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004518}
4519
Nate Begeman0aed7842006-01-28 03:14:31 +00004520SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4521 SelectionDAG &DAG) {
4522 assert(0 && "CustomPromoteOperation not implemented for this target!");
4523 abort();
4524 return SDOperand();
4525}
4526
Chris Lattner7041ee32005-01-11 05:56:49 +00004527//===----------------------------------------------------------------------===//
4528// SelectionDAGISel code
4529//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004530
4531unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004532 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004533}
4534
Chris Lattner495a0b52005-08-17 06:37:43 +00004535void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004536 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004537 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004538 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004539}
Chris Lattner1c08c712005-01-07 07:47:53 +00004540
Chris Lattner1c08c712005-01-07 07:47:53 +00004541bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004542 // Get alias analysis for load/store combining.
4543 AA = &getAnalysis<AliasAnalysis>();
4544
Chris Lattner1c08c712005-01-07 07:47:53 +00004545 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004546 if (MF.getFunction()->hasCollector())
4547 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4548 else
4549 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004550 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004551 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004552
4553 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4554
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004555 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4556 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4557 // Mark landing pad.
4558 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004559
4560 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004561 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004562
Evan Chengad2070c2007-02-10 02:43:39 +00004563 // Add function live-ins to entry block live-in set.
4564 BasicBlock *EntryBB = &Fn.getEntryBlock();
4565 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004566 if (!RegInfo->livein_empty())
4567 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4568 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004569 BB->addLiveIn(I->first);
4570
Duncan Sandsf4070822007-06-15 19:04:19 +00004571#ifndef NDEBUG
4572 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4573 "Not all catch info was assigned to a landing pad!");
4574#endif
4575
Chris Lattner1c08c712005-01-07 07:47:53 +00004576 return true;
4577}
4578
Chris Lattner6833b062008-04-28 07:16:35 +00004579void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004580 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004581 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004582 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004583 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004584 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004585
Dan Gohman23ce5022008-04-25 18:27:55 +00004586 RegsForValue RFV(TLI, Reg, V->getType());
4587 SDOperand Chain = DAG.getEntryNode();
4588 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4589 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004590}
4591
Chris Lattner068a81e2005-01-17 17:15:02 +00004592void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004593LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004594 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004595 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004596 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004597 SDOperand OldRoot = SDL.DAG.getRoot();
4598 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004599
Chris Lattnerbf209482005-10-30 19:42:35 +00004600 unsigned a = 0;
4601 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4602 AI != E; ++AI, ++a)
4603 if (!AI->use_empty()) {
4604 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004605
Chris Lattnerbf209482005-10-30 19:42:35 +00004606 // If this argument is live outside of the entry block, insert a copy from
4607 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004608 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4609 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004610 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004611 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004612 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004613
Chris Lattnerbf209482005-10-30 19:42:35 +00004614 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004615 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004616 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004617}
4618
Duncan Sandsf4070822007-06-15 19:04:19 +00004619static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4620 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004621 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004622 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004623 // Apply the catch info to DestBB.
4624 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4625#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004626 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4627 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004628#endif
4629 }
4630}
4631
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004632/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4633/// whether object offset >= 0.
4634static bool
4635IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4636 if (!isa<FrameIndexSDNode>(Op)) return false;
4637
4638 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4639 int FrameIdx = FrameIdxNode->getIndex();
4640 return MFI->isFixedObjectIndex(FrameIdx) &&
4641 MFI->getObjectOffset(FrameIdx) >= 0;
4642}
4643
4644/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4645/// possibly be overwritten when lowering the outgoing arguments in a tail
4646/// call. Currently the implementation of this call is very conservative and
4647/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4648/// virtual registers would be overwritten by direct lowering.
4649static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4650 MachineFrameInfo * MFI) {
4651 RegisterSDNode * OpReg = NULL;
4652 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4653 (Op.getOpcode()== ISD::CopyFromReg &&
4654 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4655 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4656 (Op.getOpcode() == ISD::LOAD &&
4657 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4658 (Op.getOpcode() == ISD::MERGE_VALUES &&
4659 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4660 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4661 getOperand(1))))
4662 return true;
4663 return false;
4664}
4665
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004666/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004667/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004668static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4669 TargetLowering& TLI) {
4670 SDNode * Ret = NULL;
4671 SDOperand Terminator = DAG.getRoot();
4672
4673 // Find RET node.
4674 if (Terminator.getOpcode() == ISD::RET) {
4675 Ret = Terminator.Val;
4676 }
4677
4678 // Fix tail call attribute of CALL nodes.
4679 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4680 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4681 if (BI->getOpcode() == ISD::CALL) {
4682 SDOperand OpRet(Ret, 0);
4683 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4684 bool isMarkedTailCall =
4685 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4686 // If CALL node has tail call attribute set to true and the call is not
4687 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004688 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004689 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004690 if (!isMarkedTailCall) continue;
4691 if (Ret==NULL ||
4692 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4693 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004694 SmallVector<SDOperand, 32> Ops;
4695 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004696 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4697 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004698 if (idx!=3)
4699 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004700 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004701 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4702 }
4703 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004704 } else {
4705 // Look for tail call clobbered arguments. Emit a series of
4706 // copyto/copyfrom virtual register nodes to protect them.
4707 SmallVector<SDOperand, 32> Ops;
4708 SDOperand Chain = OpCall.getOperand(0), InFlag;
4709 unsigned idx=0;
4710 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4711 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4712 SDOperand Arg = *I;
4713 if (idx > 4 && (idx % 2)) {
4714 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4715 getArgFlags().isByVal();
4716 MachineFunction &MF = DAG.getMachineFunction();
4717 MachineFrameInfo *MFI = MF.getFrameInfo();
4718 if (!isByVal &&
4719 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4720 MVT::ValueType VT = Arg.getValueType();
4721 unsigned VReg = MF.getRegInfo().
4722 createVirtualRegister(TLI.getRegClassFor(VT));
4723 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4724 InFlag = Chain.getValue(1);
4725 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4726 Chain = Arg.getValue(1);
4727 InFlag = Arg.getValue(2);
4728 }
4729 }
4730 Ops.push_back(Arg);
4731 }
4732 // Link in chain of CopyTo/CopyFromReg.
4733 Ops[0] = Chain;
4734 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004735 }
4736 }
4737 }
4738}
4739
Chris Lattner1c08c712005-01-07 07:47:53 +00004740void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4741 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004742 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004743 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004744
Chris Lattnerbf209482005-10-30 19:42:35 +00004745 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004746 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004747 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004748
4749 BB = FuncInfo.MBBMap[LLVMBB];
4750 SDL.setCurrentBasicBlock(BB);
4751
Duncan Sandsf4070822007-06-15 19:04:19 +00004752 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004753
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004754 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004755 // Add a label to mark the beginning of the landing pad. Deletion of the
4756 // landing pad can thus be detected via the MachineModuleInfo.
4757 unsigned LabelID = MMI->addLandingPad(BB);
4758 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004759 DAG.getConstant(LabelID, MVT::i32),
4760 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004761
Evan Chenge47c3332007-06-27 18:45:32 +00004762 // Mark exception register as live in.
4763 unsigned Reg = TLI.getExceptionAddressRegister();
4764 if (Reg) BB->addLiveIn(Reg);
4765
4766 // Mark exception selector register as live in.
4767 Reg = TLI.getExceptionSelectorRegister();
4768 if (Reg) BB->addLiveIn(Reg);
4769
Duncan Sandsf4070822007-06-15 19:04:19 +00004770 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4771 // function and list of typeids logically belong to the invoke (or, if you
4772 // like, the basic block containing the invoke), and need to be associated
4773 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004774 // information is provided by an intrinsic (eh.selector) that can be moved
4775 // to unexpected places by the optimizers: if the unwind edge is critical,
4776 // then breaking it can result in the intrinsics being in the successor of
4777 // the landing pad, not the landing pad itself. This results in exceptions
4778 // not being caught because no typeids are associated with the invoke.
4779 // This may not be the only way things can go wrong, but it is the only way
4780 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004781 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4782
4783 if (Br && Br->isUnconditional()) { // Critical edge?
4784 BasicBlock::iterator I, E;
4785 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004786 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004787 break;
4788
4789 if (I == E)
4790 // No catch info found - try to extract some from the successor.
4791 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004792 }
4793 }
4794
Chris Lattner1c08c712005-01-07 07:47:53 +00004795 // Lower all of the non-terminator instructions.
4796 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4797 I != E; ++I)
4798 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004799
Chris Lattner1c08c712005-01-07 07:47:53 +00004800 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004801 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004802 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004803 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004804 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004805 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004806 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004807 }
4808
4809 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4810 // ensure constants are generated when needed. Remember the virtual registers
4811 // that need to be added to the Machine PHI nodes as input. We cannot just
4812 // directly add them, because expansion might result in multiple MBB's for one
4813 // BB. As such, the start of the BB might correspond to a different MBB than
4814 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004815 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004816 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004817
4818 // Emit constants only once even if used by multiple PHI nodes.
4819 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004820
Chris Lattner8c494ab2006-10-27 23:50:33 +00004821 // Vector bool would be better, but vector<bool> is really slow.
4822 std::vector<unsigned char> SuccsHandled;
4823 if (TI->getNumSuccessors())
4824 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4825
Dan Gohman532dc2e2007-07-09 20:59:04 +00004826 // Check successor nodes' PHI nodes that expect a constant to be available
4827 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004828 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4829 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004830 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004831 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004832
Chris Lattner8c494ab2006-10-27 23:50:33 +00004833 // If this terminator has multiple identical successors (common for
4834 // switches), only handle each succ once.
4835 unsigned SuccMBBNo = SuccMBB->getNumber();
4836 if (SuccsHandled[SuccMBBNo]) continue;
4837 SuccsHandled[SuccMBBNo] = true;
4838
4839 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004840 PHINode *PN;
4841
4842 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4843 // nodes and Machine PHI nodes, but the incoming operands have not been
4844 // emitted yet.
4845 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004846 (PN = dyn_cast<PHINode>(I)); ++I) {
4847 // Ignore dead phi's.
4848 if (PN->use_empty()) continue;
4849
4850 unsigned Reg;
4851 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004852
Chris Lattner8c494ab2006-10-27 23:50:33 +00004853 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4854 unsigned &RegOut = ConstantsOut[C];
4855 if (RegOut == 0) {
4856 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004857 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004858 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004859 Reg = RegOut;
4860 } else {
4861 Reg = FuncInfo.ValueMap[PHIOp];
4862 if (Reg == 0) {
4863 assert(isa<AllocaInst>(PHIOp) &&
4864 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4865 "Didn't codegen value into a register!??");
4866 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004867 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004868 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004869 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004870
4871 // Remember that this register needs to added to the machine PHI node as
4872 // the input for this MBB.
4873 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004874 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004875 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004876 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4877 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004878 }
4879 ConstantsOut.clear();
4880
4881 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004882 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004883
Nate Begemanf15485a2006-03-27 01:32:24 +00004884 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004885 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004886 SwitchCases.clear();
4887 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004888 JTCases.clear();
4889 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004890 BitTestCases.clear();
4891 BitTestCases = SDL.BitTestCases;
4892
Chris Lattnera651cf62005-01-17 19:43:36 +00004893 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004894 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004895
4896 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4897 // with correct tailcall attribute so that the target can rely on the tailcall
4898 // attribute indicating whether the call is really eligible for tail call
4899 // optimization.
4900 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004901}
4902
Nate Begemanf15485a2006-03-27 01:32:24 +00004903void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004904 DOUT << "Lowered selection DAG:\n";
4905 DEBUG(DAG.dump());
4906
Chris Lattneraf21d552005-10-10 16:47:10 +00004907 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004908 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004909
Dan Gohman417e11b2007-10-08 15:12:17 +00004910 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004911 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004912
Chris Lattner1c08c712005-01-07 07:47:53 +00004913 // Second step, hack on the DAG until it only uses operations and types that
4914 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004915#if 0 // Enable this some day.
4916 DAG.LegalizeTypes();
4917 // Someday even later, enable a dag combine pass here.
4918#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004919 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004920
Bill Wendling832171c2006-12-07 20:04:42 +00004921 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004922 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004923
Chris Lattneraf21d552005-10-10 16:47:10 +00004924 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004925 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004926
Dan Gohman417e11b2007-10-08 15:12:17 +00004927 DOUT << "Optimized legalized selection DAG:\n";
4928 DEBUG(DAG.dump());
4929
Evan Chenga9c20912006-01-21 02:32:06 +00004930 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004931
Chris Lattnera33ef482005-03-30 01:10:47 +00004932 // Third, instruction select all of the operations to machine code, adding the
4933 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004934 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004935
Bill Wendling832171c2006-12-07 20:04:42 +00004936 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004937 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004938}
Chris Lattner1c08c712005-01-07 07:47:53 +00004939
Nate Begemanf15485a2006-03-27 01:32:24 +00004940void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4941 FunctionLoweringInfo &FuncInfo) {
4942 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4943 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004944 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004945 CurDAG = &DAG;
4946
4947 // First step, lower LLVM code to some DAG. This DAG may use operations and
4948 // types that are not supported by the target.
4949 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4950
4951 // Second step, emit the lowered DAG as machine code.
4952 CodeGenAndEmitDAG(DAG);
4953 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004954
4955 DOUT << "Total amount of phi nodes to update: "
4956 << PHINodesToUpdate.size() << "\n";
4957 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4958 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4959 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004960
Chris Lattnera33ef482005-03-30 01:10:47 +00004961 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004962 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004963 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004964 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4965 MachineInstr *PHI = PHINodesToUpdate[i].first;
4966 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4967 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004968 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4969 false));
4970 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004971 }
4972 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004973 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004974
4975 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4976 // Lower header first, if it wasn't already lowered
4977 if (!BitTestCases[i].Emitted) {
4978 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4979 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004980 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004981 // Set the current basic block to the mbb we wish to insert the code into
4982 BB = BitTestCases[i].Parent;
4983 HSDL.setCurrentBasicBlock(BB);
4984 // Emit the code
4985 HSDL.visitBitTestHeader(BitTestCases[i]);
4986 HSDAG.setRoot(HSDL.getRoot());
4987 CodeGenAndEmitDAG(HSDAG);
4988 }
4989
4990 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4991 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4992 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004993 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004994 // Set the current basic block to the mbb we wish to insert the code into
4995 BB = BitTestCases[i].Cases[j].ThisBB;
4996 BSDL.setCurrentBasicBlock(BB);
4997 // Emit the code
4998 if (j+1 != ej)
4999 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5000 BitTestCases[i].Reg,
5001 BitTestCases[i].Cases[j]);
5002 else
5003 BSDL.visitBitTestCase(BitTestCases[i].Default,
5004 BitTestCases[i].Reg,
5005 BitTestCases[i].Cases[j]);
5006
5007
5008 BSDAG.setRoot(BSDL.getRoot());
5009 CodeGenAndEmitDAG(BSDAG);
5010 }
5011
5012 // Update PHI Nodes
5013 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5014 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5015 MachineBasicBlock *PHIBB = PHI->getParent();
5016 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5017 "This is not a machine PHI node that we are updating!");
5018 // This is "default" BB. We have two jumps to it. From "header" BB and
5019 // from last "case" BB.
5020 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005021 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5022 false));
5023 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5024 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5025 false));
5026 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5027 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005028 }
5029 // One of "cases" BB.
5030 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5031 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5032 if (cBB->succ_end() !=
5033 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005034 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5035 false));
5036 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005037 }
5038 }
5039 }
5040 }
5041
Nate Begeman9453eea2006-04-23 06:26:20 +00005042 // If the JumpTable record is filled in, then we need to emit a jump table.
5043 // Updating the PHI nodes is tricky in this case, since we need to determine
5044 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005045 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5046 // Lower header first, if it wasn't already lowered
5047 if (!JTCases[i].first.Emitted) {
5048 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5049 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005050 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005051 // Set the current basic block to the mbb we wish to insert the code into
5052 BB = JTCases[i].first.HeaderBB;
5053 HSDL.setCurrentBasicBlock(BB);
5054 // Emit the code
5055 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5056 HSDAG.setRoot(HSDL.getRoot());
5057 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005058 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005059
5060 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5061 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005062 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005063 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005064 BB = JTCases[i].second.MBB;
5065 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005066 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005067 JSDL.visitJumpTable(JTCases[i].second);
5068 JSDAG.setRoot(JSDL.getRoot());
5069 CodeGenAndEmitDAG(JSDAG);
5070
Nate Begeman37efe672006-04-22 18:53:45 +00005071 // Update PHI Nodes
5072 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5073 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5074 MachineBasicBlock *PHIBB = PHI->getParent();
5075 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5076 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005077 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005078 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005079 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5080 false));
5081 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005082 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005083 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005084 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005085 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5086 false));
5087 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005088 }
5089 }
Nate Begeman37efe672006-04-22 18:53:45 +00005090 }
5091
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005092 // If the switch block involved a branch to one of the actual successors, we
5093 // need to update PHI nodes in that block.
5094 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5095 MachineInstr *PHI = PHINodesToUpdate[i].first;
5096 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5097 "This is not a machine PHI node that we are updating!");
5098 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005099 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5100 false));
5101 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005102 }
5103 }
5104
Nate Begemanf15485a2006-03-27 01:32:24 +00005105 // If we generated any switch lowering information, build and codegen any
5106 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005107 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005108 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005109 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005110 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005111
Nate Begemanf15485a2006-03-27 01:32:24 +00005112 // Set the current basic block to the mbb we wish to insert the code into
5113 BB = SwitchCases[i].ThisBB;
5114 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005115
Nate Begemanf15485a2006-03-27 01:32:24 +00005116 // Emit the code
5117 SDL.visitSwitchCase(SwitchCases[i]);
5118 SDAG.setRoot(SDL.getRoot());
5119 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005120
5121 // Handle any PHI nodes in successors of this chunk, as if we were coming
5122 // from the original BB before switch expansion. Note that PHI nodes can
5123 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5124 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005125 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005126 for (MachineBasicBlock::iterator Phi = BB->begin();
5127 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5128 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5129 for (unsigned pn = 0; ; ++pn) {
5130 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5131 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005132 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5133 second, false));
5134 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005135 break;
5136 }
5137 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005138 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005139
5140 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005141 if (BB == SwitchCases[i].FalseBB)
5142 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005143
5144 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005145 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005146 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005147 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005148 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005149 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005150}
Evan Chenga9c20912006-01-21 02:32:06 +00005151
Jim Laskey13ec7022006-08-01 14:21:23 +00005152
Evan Chenga9c20912006-01-21 02:32:06 +00005153//===----------------------------------------------------------------------===//
5154/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5155/// target node in the graph.
5156void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5157 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005158
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005159 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005160
5161 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005162 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005163 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005164 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005165
Jim Laskey9ff542f2006-08-01 18:29:48 +00005166 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005167 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005168
5169 if (ViewSUnitDAGs) SL->viewGraph();
5170
Evan Chengcccf1232006-02-04 06:49:00 +00005171 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005172}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005173
Chris Lattner03fc53c2006-03-06 00:22:00 +00005174
Jim Laskey9ff542f2006-08-01 18:29:48 +00005175HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5176 return new HazardRecognizer();
5177}
5178
Chris Lattner75548062006-10-11 03:58:02 +00005179//===----------------------------------------------------------------------===//
5180// Helper functions used by the generated instruction selector.
5181//===----------------------------------------------------------------------===//
5182// Calls to these methods are generated by tblgen.
5183
5184/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5185/// the dag combiner simplified the 255, we still want to match. RHS is the
5186/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5187/// specified in the .td file (e.g. 255).
5188bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005189 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005190 const APInt &ActualMask = RHS->getAPIntValue();
5191 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005192
5193 // If the actual mask exactly matches, success!
5194 if (ActualMask == DesiredMask)
5195 return true;
5196
5197 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005198 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005199 return false;
5200
5201 // Otherwise, the DAG Combiner may have proven that the value coming in is
5202 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005203 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005204 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005205 return true;
5206
5207 // TODO: check to see if missing bits are just not demanded.
5208
5209 // Otherwise, this pattern doesn't match.
5210 return false;
5211}
5212
5213/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5214/// the dag combiner simplified the 255, we still want to match. RHS is the
5215/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5216/// specified in the .td file (e.g. 255).
5217bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005218 int64_t DesiredMaskS) const {
5219 const APInt &ActualMask = RHS->getAPIntValue();
5220 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005221
5222 // If the actual mask exactly matches, success!
5223 if (ActualMask == DesiredMask)
5224 return true;
5225
5226 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005227 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005228 return false;
5229
5230 // Otherwise, the DAG Combiner may have proven that the value coming in is
5231 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005232 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005233
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005234 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005235 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005236
5237 // If all the missing bits in the or are already known to be set, match!
5238 if ((NeededMask & KnownOne) == NeededMask)
5239 return true;
5240
5241 // TODO: check to see if missing bits are just not demanded.
5242
5243 // Otherwise, this pattern doesn't match.
5244 return false;
5245}
5246
Jim Laskey9ff542f2006-08-01 18:29:48 +00005247
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005248/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5249/// by tblgen. Others should not call it.
5250void SelectionDAGISel::
5251SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5252 std::vector<SDOperand> InOps;
5253 std::swap(InOps, Ops);
5254
5255 Ops.push_back(InOps[0]); // input chain.
5256 Ops.push_back(InOps[1]); // input asm string.
5257
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005258 unsigned i = 2, e = InOps.size();
5259 if (InOps[e-1].getValueType() == MVT::Flag)
5260 --e; // Don't process a flag operand if it is here.
5261
5262 while (i != e) {
5263 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5264 if ((Flags & 7) != 4 /*MEM*/) {
5265 // Just skip over this operand, copying the operands verbatim.
5266 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5267 i += (Flags >> 3) + 1;
5268 } else {
5269 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5270 // Otherwise, this is a memory operand. Ask the target to select it.
5271 std::vector<SDOperand> SelOps;
5272 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005273 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005274 exit(1);
5275 }
5276
5277 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005278 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005279 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005280 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005281 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5282 i += 2;
5283 }
5284 }
5285
5286 // Add the flag input back if present.
5287 if (e != InOps.size())
5288 Ops.push_back(InOps.back());
5289}
Devang Patel794fd752007-05-01 21:15:47 +00005290
Devang Patel19974732007-05-03 01:11:54 +00005291char SelectionDAGISel::ID = 0;