blob: 93de65239834125eea73f233d660cd86d262c4e7 [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,
156 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000157 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(1, Reg) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000158 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000159 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000160 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000163 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000164 const SmallVector<MVT::ValueType, 4> &regvts,
165 const SmallVector<MVT::ValueType, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000166 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000167 RegsForValue(const TargetLowering &tli,
168 unsigned Reg, const Type *Ty) : TLI(&tli) {
169 ComputeValueVTs(tli, Ty, ValueVTs);
170
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000171 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000172 MVT::ValueType ValueVT = ValueVTs[Value];
173 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
174 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
175 for (unsigned i = 0; i != NumRegs; ++i)
176 Regs.push_back(Reg + i);
177 RegVTs.push_back(RegisterVT);
178 Reg += NumRegs;
179 }
Chris Lattner864635a2006-02-22 22:37:12 +0000180 }
181
182 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000183 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000184 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000185 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000186 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000187 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000188
189 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
190 /// specified value into the registers specified by this object. This uses
191 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000192 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000193 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000194 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000195
196 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
197 /// operand list. This adds the code marker and includes the number of
198 /// values added into it.
199 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000200 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000201 };
202}
Evan Cheng4ef10862006-01-23 07:01:07 +0000203
Chris Lattner1c08c712005-01-07 07:47:53 +0000204namespace llvm {
205 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000206 /// createDefaultScheduler - This creates an instruction scheduler appropriate
207 /// for the target.
208 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
209 SelectionDAG *DAG,
210 MachineBasicBlock *BB) {
211 TargetLowering &TLI = IS->getTargetLowering();
212
213 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
214 return createTDListDAGScheduler(IS, DAG, BB);
215 } else {
216 assert(TLI.getSchedulingPreference() ==
217 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
218 return createBURRListDAGScheduler(IS, DAG, BB);
219 }
220 }
221
222
223 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000224 /// FunctionLoweringInfo - This contains information that is global to a
225 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000226 class FunctionLoweringInfo {
227 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 TargetLowering &TLI;
229 Function &Fn;
230 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000231 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000232
233 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
234
235 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
236 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
237
238 /// ValueMap - Since we emit code for the function a basic block at a time,
239 /// we must remember which virtual registers hold the values for
240 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000241 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000242
243 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
244 /// the entry block. This allows the allocas to be efficiently referenced
245 /// anywhere in the function.
246 std::map<const AllocaInst*, int> StaticAllocaMap;
247
Duncan Sandsf4070822007-06-15 19:04:19 +0000248#ifndef NDEBUG
249 SmallSet<Instruction*, 8> CatchInfoLost;
250 SmallSet<Instruction*, 8> CatchInfoFound;
251#endif
252
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000254 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000255 }
Chris Lattner571e4342006-10-27 21:36:01 +0000256
257 /// isExportedInst - Return true if the specified value is an instruction
258 /// exported from its block.
259 bool isExportedInst(const Value *V) {
260 return ValueMap.count(V);
261 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000262
Chris Lattner3c384492006-03-16 19:51:18 +0000263 unsigned CreateRegForValue(const Value *V);
264
Chris Lattner1c08c712005-01-07 07:47:53 +0000265 unsigned InitializeRegForValue(const Value *V) {
266 unsigned &R = ValueMap[V];
267 assert(R == 0 && "Already initialized this value register!");
268 return R = CreateRegForValue(V);
269 }
270 };
271}
272
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000273/// isSelector - Return true if this instruction is a call to the
274/// eh.selector intrinsic.
275static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000277 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
278 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000279 return false;
280}
281
Chris Lattner1c08c712005-01-07 07:47:53 +0000282/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000283/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000284/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000285static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
286 if (isa<PHINode>(I)) return true;
287 BasicBlock *BB = I->getParent();
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000289 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000290 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000291 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000292 return true;
293 return false;
294}
295
Chris Lattnerbf209482005-10-30 19:42:35 +0000296/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000297/// entry block, return true. This includes arguments used by switches, since
298/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000299static bool isOnlyUsedInEntryBlock(Argument *A) {
300 BasicBlock *Entry = A->getParent()->begin();
301 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000302 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000303 return false; // Use not in entry block.
304 return true;
305}
306
Chris Lattner1c08c712005-01-07 07:47:53 +0000307FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000308 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000309 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000310
Chris Lattnerbf209482005-10-30 19:42:35 +0000311 // Create a vreg for each argument register that is not dead and is used
312 // outside of the entry block for the function.
313 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
314 AI != E; ++AI)
315 if (!isOnlyUsedInEntryBlock(AI))
316 InitializeRegForValue(AI);
317
Chris Lattner1c08c712005-01-07 07:47:53 +0000318 // Initialize the mapping of values to registers. This is only set up for
319 // instruction values that are used outside of the block that defines
320 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000321 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
323 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000324 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000326 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000327 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000328 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000329 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000330
Reid Spencerb83eb642006-10-20 07:07:24 +0000331 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000332 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000333 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000334 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000335 }
336
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000337 for (; BB != EB; ++BB)
338 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
340 if (!isa<AllocaInst>(I) ||
341 !StaticAllocaMap.count(cast<AllocaInst>(I)))
342 InitializeRegForValue(I);
343
344 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
345 // also creates the initial PHI MachineInstrs, though none of the input
346 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000347 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000348 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
349 MBBMap[BB] = MBB;
350 MF.getBasicBlockList().push_back(MBB);
351
352 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
353 // appropriate.
354 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000355 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
356 if (PN->use_empty()) continue;
357
358 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000359 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000360 unsigned PHIReg = ValueMap[PN];
361 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000362 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000363 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000364 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000365 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000366 }
367}
368
Chris Lattner3c384492006-03-16 19:51:18 +0000369/// CreateRegForValue - Allocate the appropriate number of virtual registers of
370/// the correctly promoted or expanded types. Assign these registers
371/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000372///
373/// In the case that the given value has struct or array type, this function
374/// will assign registers for each member or element.
375///
Chris Lattner3c384492006-03-16 19:51:18 +0000376unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000377 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000378 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000379
Dan Gohman23ce5022008-04-25 18:27:55 +0000380 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000381 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000382 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000383 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000384
Chris Lattnerb606dba2008-04-28 06:44:42 +0000385 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000386 for (unsigned i = 0; i != NumRegs; ++i) {
387 unsigned R = MakeReg(RegisterVT);
388 if (!FirstReg) FirstReg = R;
389 }
390 }
391 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000392}
Chris Lattner1c08c712005-01-07 07:47:53 +0000393
394//===----------------------------------------------------------------------===//
395/// SelectionDAGLowering - This is the common target-independent lowering
396/// implementation that is parameterized by a TargetLowering object.
397/// Also, targets can overload any lowering method.
398///
399namespace llvm {
400class SelectionDAGLowering {
401 MachineBasicBlock *CurMBB;
402
Chris Lattner0da331f2007-02-04 01:31:47 +0000403 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000404
Chris Lattnerd3948112005-01-17 22:19:26 +0000405 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
406 /// them up and then emit token factor nodes when possible. This allows us to
407 /// get simple disambiguation between loads without worrying about alias
408 /// analysis.
409 std::vector<SDOperand> PendingLoads;
410
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000411 /// PendingExports - CopyToReg nodes that copy values to virtual registers
412 /// for export to other blocks need to be emitted before any terminator
413 /// instruction, but they have no other ordering requirements. We bunch them
414 /// up and the emit a single tokenfactor for them just before terminator
415 /// instructions.
416 std::vector<SDOperand> PendingExports;
417
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000418 /// Case - A struct to record the Value for a switch case, and the
419 /// case's target basic block.
420 struct Case {
421 Constant* Low;
422 Constant* High;
423 MachineBasicBlock* BB;
424
425 Case() : Low(0), High(0), BB(0) { }
426 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
427 Low(low), High(high), BB(bb) { }
428 uint64_t size() const {
429 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
430 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
431 return (rHigh - rLow + 1ULL);
432 }
433 };
434
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000435 struct CaseBits {
436 uint64_t Mask;
437 MachineBasicBlock* BB;
438 unsigned Bits;
439
440 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
441 Mask(mask), BB(bb), Bits(bits) { }
442 };
443
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000444 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000445 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000446 typedef CaseVector::iterator CaseItr;
447 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000448
449 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
450 /// of conditional branches.
451 struct CaseRec {
452 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
453 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
454
455 /// CaseBB - The MBB in which to emit the compare and branch
456 MachineBasicBlock *CaseBB;
457 /// LT, GE - If nonzero, we know the current case value must be less-than or
458 /// greater-than-or-equal-to these Constants.
459 Constant *LT;
460 Constant *GE;
461 /// Range - A pair of iterators representing the range of case values to be
462 /// processed at this point in the binary search tree.
463 CaseRange Range;
464 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000465
466 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000467
468 /// The comparison function for sorting the switch case values in the vector.
469 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000470 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000471 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000472 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
473 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
474 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
475 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000476 }
477 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000478
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000479 struct CaseBitsCmp {
480 bool operator () (const CaseBits& C1, const CaseBits& C2) {
481 return C1.Bits > C2.Bits;
482 }
483 };
484
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000485 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000486
Chris Lattner1c08c712005-01-07 07:47:53 +0000487public:
488 // TLI - This is information that describes the available target features we
489 // need for lowering. This indicates when operations are unavailable,
490 // implemented with a libcall, etc.
491 TargetLowering &TLI;
492 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000493 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000494 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000495
Nate Begemanf15485a2006-03-27 01:32:24 +0000496 /// SwitchCases - Vector of CaseBlock structures used to communicate
497 /// SwitchInst code generation information.
498 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000499 /// JTCases - Vector of JumpTable structures used to communicate
500 /// SwitchInst code generation information.
501 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000502 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000503
Chris Lattner1c08c712005-01-07 07:47:53 +0000504 /// FuncInfo - Information about the function as a whole.
505 ///
506 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000507
508 /// GCI - Garbage collection metadata for the function.
509 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000510
511 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000512 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000513 FunctionLoweringInfo &funcinfo,
514 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000515 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000516 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000517 }
518
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000519 /// getRoot - Return the current virtual root of the Selection DAG,
520 /// flushing any PendingLoad items. This must be done before emitting
521 /// a store or any other node that may need to be ordered after any
522 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000523 ///
524 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000525 if (PendingLoads.empty())
526 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000527
Chris Lattnerd3948112005-01-17 22:19:26 +0000528 if (PendingLoads.size() == 1) {
529 SDOperand Root = PendingLoads[0];
530 DAG.setRoot(Root);
531 PendingLoads.clear();
532 return Root;
533 }
534
535 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000536 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
537 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000538 PendingLoads.clear();
539 DAG.setRoot(Root);
540 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000541 }
542
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000543 /// getControlRoot - Similar to getRoot, but instead of flushing all the
544 /// PendingLoad items, flush all the PendingExports items. It is necessary
545 /// to do this before emitting a terminator instruction.
546 ///
547 SDOperand getControlRoot() {
548 SDOperand Root = DAG.getRoot();
549
550 if (PendingExports.empty())
551 return Root;
552
553 // Turn all of the CopyToReg chains into one factored node.
554 if (Root.getOpcode() != ISD::EntryToken) {
555 unsigned i = 0, e = PendingExports.size();
556 for (; i != e; ++i) {
557 assert(PendingExports[i].Val->getNumOperands() > 1);
558 if (PendingExports[i].Val->getOperand(0) == Root)
559 break; // Don't add the root if we already indirectly depend on it.
560 }
561
562 if (i == e)
563 PendingExports.push_back(Root);
564 }
565
566 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
567 &PendingExports[0],
568 PendingExports.size());
569 PendingExports.clear();
570 DAG.setRoot(Root);
571 return Root;
572 }
573
574 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000575
Chris Lattner1c08c712005-01-07 07:47:53 +0000576 void visit(Instruction &I) { visit(I.getOpcode(), I); }
577
578 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000579 // Note: this doesn't use InstVisitor, because it has to work with
580 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000581 switch (Opcode) {
582 default: assert(0 && "Unknown instruction type encountered!");
583 abort();
584 // Build the switch statement using the Instruction.def file.
585#define HANDLE_INST(NUM, OPCODE, CLASS) \
586 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
587#include "llvm/Instruction.def"
588 }
589 }
590
591 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
592
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000593 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000594 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000595 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000596
Chris Lattner199862b2006-03-16 19:57:50 +0000597 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000598
Chris Lattner0da331f2007-02-04 01:31:47 +0000599 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000600 SDOperand &N = NodeMap[V];
601 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000602 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000603 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000604
Evan Cheng5c807602008-02-26 02:33:44 +0000605 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000606 std::set<unsigned> &OutputRegs,
607 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000608
Chris Lattner571e4342006-10-27 21:36:01 +0000609 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
610 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
611 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000612 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000613 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000614 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000615 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000616
Chris Lattner1c08c712005-01-07 07:47:53 +0000617 // Terminator instructions.
618 void visitRet(ReturnInst &I);
619 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000620 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 void visitUnreachable(UnreachableInst &I) { /* noop */ }
622
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000623 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000624 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000625 CaseRecVector& WorkList,
626 Value* SV,
627 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000632 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000636 bool handleBitTestsSwitchCase(CaseRec& CR,
637 CaseRecVector& WorkList,
638 Value* SV,
639 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000640 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000641 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
642 void visitBitTestCase(MachineBasicBlock* NextMBB,
643 unsigned Reg,
644 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000645 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000646 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
647 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000648
Chris Lattner1c08c712005-01-07 07:47:53 +0000649 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000650 void visitInvoke(InvokeInst &I);
651 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000652
Dan Gohman7f321562007-06-25 16:23:39 +0000653 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000654 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000655 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000656 if (I.getType()->isFPOrFPVector())
657 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000658 else
Dan Gohman7f321562007-06-25 16:23:39 +0000659 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000660 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000661 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000662 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000663 if (I.getType()->isFPOrFPVector())
664 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000665 else
Dan Gohman7f321562007-06-25 16:23:39 +0000666 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000667 }
Dan Gohman7f321562007-06-25 16:23:39 +0000668 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
669 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
670 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
671 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
672 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
673 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
674 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
675 void visitOr (User &I) { visitBinary(I, ISD::OR); }
676 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000677 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000678 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
679 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000680 void visitICmp(User &I);
681 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000682 // Visit the conversion instructions
683 void visitTrunc(User &I);
684 void visitZExt(User &I);
685 void visitSExt(User &I);
686 void visitFPTrunc(User &I);
687 void visitFPExt(User &I);
688 void visitFPToUI(User &I);
689 void visitFPToSI(User &I);
690 void visitUIToFP(User &I);
691 void visitSIToFP(User &I);
692 void visitPtrToInt(User &I);
693 void visitIntToPtr(User &I);
694 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000695
Chris Lattner2bbd8102006-03-29 00:11:43 +0000696 void visitExtractElement(User &I);
697 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000698 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000699
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000702
703 void visitMalloc(MallocInst &I);
704 void visitFree(FreeInst &I);
705 void visitAlloca(AllocaInst &I);
706 void visitLoad(LoadInst &I);
707 void visitStore(StoreInst &I);
708 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
709 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000710 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000711 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000712 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000713
Chris Lattner1c08c712005-01-07 07:47:53 +0000714 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000715 void visitVAArg(VAArgInst &I);
716 void visitVAEnd(CallInst &I);
717 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000718
Dan Gohmanef5d1942008-03-11 21:11:25 +0000719 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000720
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 void visitUserOp1(Instruction &I) {
722 assert(0 && "UserOp1 should not exist at instruction selection time!");
723 abort();
724 }
725 void visitUserOp2(Instruction &I) {
726 assert(0 && "UserOp2 should not exist at instruction selection time!");
727 abort();
728 }
729};
730} // end namespace llvm
731
Dan Gohman6183f782007-07-05 20:12:34 +0000732
Duncan Sandsb988bac2008-02-11 20:58:28 +0000733/// getCopyFromParts - Create a value that contains the specified legal parts
734/// combined into the value they represent. If the parts combine to a type
735/// larger then ValueVT then AssertOp can be used to specify whether the extra
736/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000737/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000738static SDOperand getCopyFromParts(SelectionDAG &DAG,
739 const SDOperand *Parts,
740 unsigned NumParts,
741 MVT::ValueType PartVT,
742 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000743 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000744 assert(NumParts > 0 && "No parts to assemble!");
745 TargetLowering &TLI = DAG.getTargetLoweringInfo();
746 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000747
Duncan Sands014e04a2008-02-12 20:46:31 +0000748 if (NumParts > 1) {
749 // Assemble the value from multiple parts.
750 if (!MVT::isVector(ValueVT)) {
751 unsigned PartBits = MVT::getSizeInBits(PartVT);
752 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000753
Duncan Sands014e04a2008-02-12 20:46:31 +0000754 // Assemble the power of 2 part.
755 unsigned RoundParts = NumParts & (NumParts - 1) ?
756 1 << Log2_32(NumParts) : NumParts;
757 unsigned RoundBits = PartBits * RoundParts;
758 MVT::ValueType RoundVT = RoundBits == ValueBits ?
759 ValueVT : MVT::getIntegerType(RoundBits);
760 SDOperand Lo, Hi;
761
762 if (RoundParts > 2) {
763 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
764 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
765 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
766 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000767 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000768 Lo = Parts[0];
769 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000770 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000771 if (TLI.isBigEndian())
772 std::swap(Lo, Hi);
773 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
774
775 if (RoundParts < NumParts) {
776 // Assemble the trailing non-power-of-2 part.
777 unsigned OddParts = NumParts - RoundParts;
778 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
779 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
780
781 // Combine the round and odd parts.
782 Lo = Val;
783 if (TLI.isBigEndian())
784 std::swap(Lo, Hi);
785 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
786 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
787 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
788 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
789 TLI.getShiftAmountTy()));
790 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
791 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
792 }
793 } else {
794 // Handle a multi-element vector.
795 MVT::ValueType IntermediateVT, RegisterVT;
796 unsigned NumIntermediates;
797 unsigned NumRegs =
798 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
799 RegisterVT);
800
801 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
802 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
803 assert(RegisterVT == Parts[0].getValueType() &&
804 "Part type doesn't match part!");
805
806 // Assemble the parts into intermediate operands.
807 SmallVector<SDOperand, 8> Ops(NumIntermediates);
808 if (NumIntermediates == NumParts) {
809 // If the register was not expanded, truncate or copy the value,
810 // as appropriate.
811 for (unsigned i = 0; i != NumParts; ++i)
812 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
813 PartVT, IntermediateVT);
814 } else if (NumParts > 0) {
815 // If the intermediate type was expanded, build the intermediate operands
816 // from the parts.
817 assert(NumParts % NumIntermediates == 0 &&
818 "Must expand into a divisible number of parts!");
819 unsigned Factor = NumParts / NumIntermediates;
820 for (unsigned i = 0; i != NumIntermediates; ++i)
821 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
822 PartVT, IntermediateVT);
823 }
824
825 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
826 // operands.
827 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
828 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
829 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000830 }
Dan Gohman6183f782007-07-05 20:12:34 +0000831 }
832
Duncan Sands014e04a2008-02-12 20:46:31 +0000833 // There is now one part, held in Val. Correct it to match ValueVT.
834 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000835
Duncan Sands014e04a2008-02-12 20:46:31 +0000836 if (PartVT == ValueVT)
837 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000838
Duncan Sands014e04a2008-02-12 20:46:31 +0000839 if (MVT::isVector(PartVT)) {
840 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
841 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000842 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000843
844 if (MVT::isVector(ValueVT)) {
845 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
846 MVT::getVectorNumElements(ValueVT) == 1 &&
847 "Only trivial scalar-to-vector conversions should get here!");
848 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
849 }
850
851 if (MVT::isInteger(PartVT) &&
852 MVT::isInteger(ValueVT)) {
853 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
854 // For a truncate, see if we have any information to
855 // indicate whether the truncated bits will always be
856 // zero or sign-extension.
857 if (AssertOp != ISD::DELETED_NODE)
858 Val = DAG.getNode(AssertOp, PartVT, Val,
859 DAG.getValueType(ValueVT));
860 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
861 } else {
862 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
863 }
864 }
865
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000866 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
867 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000868 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000869 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000870 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000871 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
872 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000873
874 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
875 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
876
877 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000878 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000879}
880
Duncan Sandsb988bac2008-02-11 20:58:28 +0000881/// getCopyToParts - Create a series of nodes that contain the specified value
882/// split into legal parts. If the parts contain more bits than Val, then, for
883/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000884static void getCopyToParts(SelectionDAG &DAG,
885 SDOperand Val,
886 SDOperand *Parts,
887 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000888 MVT::ValueType PartVT,
889 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000890 TargetLowering &TLI = DAG.getTargetLoweringInfo();
891 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000892 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000893 unsigned PartBits = MVT::getSizeInBits(PartVT);
894 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000895
Duncan Sands014e04a2008-02-12 20:46:31 +0000896 if (!NumParts)
897 return;
898
899 if (!MVT::isVector(ValueVT)) {
900 if (PartVT == ValueVT) {
901 assert(NumParts == 1 && "No-op copy with multiple parts!");
902 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000903 return;
904 }
905
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
907 // If the parts cover more bits than the value has, promote the value.
908 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
909 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000910 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000911 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
912 ValueVT = MVT::getIntegerType(NumParts * PartBits);
913 Val = DAG.getNode(ExtendKind, ValueVT, Val);
914 } else {
915 assert(0 && "Unknown mismatch!");
916 }
917 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
918 // Different types of the same size.
919 assert(NumParts == 1 && PartVT != ValueVT);
920 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
921 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
922 // If the parts cover less bits than value has, truncate the value.
923 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
924 ValueVT = MVT::getIntegerType(NumParts * PartBits);
925 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000926 } else {
927 assert(0 && "Unknown mismatch!");
928 }
929 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000930
931 // The value may have changed - recompute ValueVT.
932 ValueVT = Val.getValueType();
933 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
934 "Failed to tile the value with PartVT!");
935
936 if (NumParts == 1) {
937 assert(PartVT == ValueVT && "Type conversion failed!");
938 Parts[0] = Val;
939 return;
940 }
941
942 // Expand the value into multiple parts.
943 if (NumParts & (NumParts - 1)) {
944 // The number of parts is not a power of 2. Split off and copy the tail.
945 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
946 "Do not know what to expand to!");
947 unsigned RoundParts = 1 << Log2_32(NumParts);
948 unsigned RoundBits = RoundParts * PartBits;
949 unsigned OddParts = NumParts - RoundParts;
950 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
951 DAG.getConstant(RoundBits,
952 TLI.getShiftAmountTy()));
953 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
954 if (TLI.isBigEndian())
955 // The odd parts were reversed by getCopyToParts - unreverse them.
956 std::reverse(Parts + RoundParts, Parts + NumParts);
957 NumParts = RoundParts;
958 ValueVT = MVT::getIntegerType(NumParts * PartBits);
959 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
960 }
961
962 // The number of parts is a power of 2. Repeatedly bisect the value using
963 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000964 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
965 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
966 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000967 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
968 for (unsigned i = 0; i < NumParts; i += StepSize) {
969 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000970 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
971 SDOperand &Part0 = Parts[i];
972 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000973
Duncan Sands25eb0432008-03-12 20:30:08 +0000974 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
975 DAG.getConstant(1, PtrVT));
976 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
977 DAG.getConstant(0, PtrVT));
978
979 if (ThisBits == PartBits && ThisVT != PartVT) {
980 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
981 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
982 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000983 }
984 }
985
986 if (TLI.isBigEndian())
987 std::reverse(Parts, Parts + NumParts);
988
989 return;
990 }
991
992 // Vector ValueVT.
993 if (NumParts == 1) {
994 if (PartVT != ValueVT) {
995 if (MVT::isVector(PartVT)) {
996 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
997 } else {
998 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
999 MVT::getVectorNumElements(ValueVT) == 1 &&
1000 "Only trivial vector-to-scalar conversions should get here!");
1001 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1002 DAG.getConstant(0, PtrVT));
1003 }
1004 }
1005
Dan Gohman6183f782007-07-05 20:12:34 +00001006 Parts[0] = Val;
1007 return;
1008 }
1009
1010 // Handle a multi-element vector.
1011 MVT::ValueType IntermediateVT, RegisterVT;
1012 unsigned NumIntermediates;
1013 unsigned NumRegs =
1014 DAG.getTargetLoweringInfo()
1015 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1016 RegisterVT);
1017 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1018
1019 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1020 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1021
1022 // Split the vector into intermediate operands.
1023 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1024 for (unsigned i = 0; i != NumIntermediates; ++i)
1025 if (MVT::isVector(IntermediateVT))
1026 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1027 IntermediateVT, Val,
1028 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001029 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001030 else
1031 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1032 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001033 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001034
1035 // Split the intermediate operands into legal parts.
1036 if (NumParts == NumIntermediates) {
1037 // If the register was not expanded, promote or copy the value,
1038 // as appropriate.
1039 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001040 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001041 } else if (NumParts > 0) {
1042 // If the intermediate type was expanded, split each the value into
1043 // legal parts.
1044 assert(NumParts % NumIntermediates == 0 &&
1045 "Must expand into a divisible number of parts!");
1046 unsigned Factor = NumParts / NumIntermediates;
1047 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001048 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001049 }
1050}
1051
1052
Chris Lattner199862b2006-03-16 19:57:50 +00001053SDOperand SelectionDAGLowering::getValue(const Value *V) {
1054 SDOperand &N = NodeMap[V];
1055 if (N.Val) return N;
1056
Chris Lattner199862b2006-03-16 19:57:50 +00001057 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattner6833b062008-04-28 07:16:35 +00001058 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001059
1060 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1061 return N = DAG.getConstant(CI->getValue(), VT);
1062
1063 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001064 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001065
1066 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001067 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001068
1069 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1070 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1071
Chris Lattner6833b062008-04-28 07:16:35 +00001072 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1073 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001074
1075 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1076 visit(CE->getOpcode(), *CE);
1077 SDOperand N1 = NodeMap[V];
1078 assert(N1.Val && "visit didn't populate the ValueMap!");
1079 return N1;
1080 }
1081
Chris Lattner6833b062008-04-28 07:16:35 +00001082 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001083 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001084
Chris Lattner6833b062008-04-28 07:16:35 +00001085 // Now that we know the number and type of the elements, get that number of
1086 // elements into the Ops array based on what kind of constant it is.
1087 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001088 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1089 for (unsigned i = 0; i != NumElements; ++i)
1090 Ops.push_back(getValue(CP->getOperand(i)));
1091 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001092 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1093 "Unknown vector constant!");
1094 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1095
Chris Lattnerb606dba2008-04-28 06:44:42 +00001096 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001097 if (isa<UndefValue>(C))
1098 Op = DAG.getNode(ISD::UNDEF, EltVT);
1099 else if (MVT::isFloatingPoint(EltVT))
1100 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001101 else
Chris Lattner6833b062008-04-28 07:16:35 +00001102 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001103 Ops.assign(NumElements, Op);
1104 }
1105
1106 // Create a BUILD_VECTOR node.
1107 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001108 }
1109
Chris Lattnerb606dba2008-04-28 06:44:42 +00001110 // If this is a static alloca, generate it as the frameindex instead of
1111 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001112 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1113 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001114 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001115 if (SI != FuncInfo.StaticAllocaMap.end())
1116 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1117 }
1118
Chris Lattner251db182007-02-25 18:40:32 +00001119 unsigned InReg = FuncInfo.ValueMap[V];
1120 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001121
Chris Lattner6833b062008-04-28 07:16:35 +00001122 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001123 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001124 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001125}
1126
1127
Chris Lattner1c08c712005-01-07 07:47:53 +00001128void SelectionDAGLowering::visitRet(ReturnInst &I) {
1129 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001130 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001131 return;
1132 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001133
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001134 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001135 NewValues.push_back(getControlRoot());
1136 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001137 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001138 MVT::ValueType VT = RetOp.getValueType();
1139
Evan Cheng8e7d0562006-05-26 23:09:09 +00001140 // FIXME: C calling convention requires the return type to be promoted to
1141 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001142 if (MVT::isInteger(VT)) {
1143 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1144 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1145 VT = MinVT;
1146 }
1147
1148 unsigned NumParts = TLI.getNumRegisters(VT);
1149 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1150 SmallVector<SDOperand, 4> Parts(NumParts);
1151 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1152
1153 const Function *F = I.getParent()->getParent();
1154 if (F->paramHasAttr(0, ParamAttr::SExt))
1155 ExtendKind = ISD::SIGN_EXTEND;
1156 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1157 ExtendKind = ISD::ZERO_EXTEND;
1158
1159 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1160
1161 for (unsigned i = 0; i < NumParts; ++i) {
1162 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001163 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001164 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001165 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001166 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1167 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001168}
1169
Chris Lattner571e4342006-10-27 21:36:01 +00001170/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1171/// the current basic block, add it to ValueMap now so that we'll get a
1172/// CopyTo/FromReg.
1173void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1174 // No need to export constants.
1175 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1176
1177 // Already exported?
1178 if (FuncInfo.isExportedInst(V)) return;
1179
1180 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001181 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001182}
1183
Chris Lattner8c494ab2006-10-27 23:50:33 +00001184bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1185 const BasicBlock *FromBB) {
1186 // The operands of the setcc have to be in this block. We don't know
1187 // how to export them from some other block.
1188 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1189 // Can export from current BB.
1190 if (VI->getParent() == FromBB)
1191 return true;
1192
1193 // Is already exported, noop.
1194 return FuncInfo.isExportedInst(V);
1195 }
1196
1197 // If this is an argument, we can export it if the BB is the entry block or
1198 // if it is already exported.
1199 if (isa<Argument>(V)) {
1200 if (FromBB == &FromBB->getParent()->getEntryBlock())
1201 return true;
1202
1203 // Otherwise, can only export this if it is already exported.
1204 return FuncInfo.isExportedInst(V);
1205 }
1206
1207 // Otherwise, constants can always be exported.
1208 return true;
1209}
1210
Chris Lattner6a586c82006-10-29 21:01:20 +00001211static bool InBlock(const Value *V, const BasicBlock *BB) {
1212 if (const Instruction *I = dyn_cast<Instruction>(V))
1213 return I->getParent() == BB;
1214 return true;
1215}
1216
Chris Lattner571e4342006-10-27 21:36:01 +00001217/// FindMergedConditions - If Cond is an expression like
1218void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1219 MachineBasicBlock *TBB,
1220 MachineBasicBlock *FBB,
1221 MachineBasicBlock *CurBB,
1222 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001223 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001224 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001225
Reid Spencere4d87aa2006-12-23 06:05:41 +00001226 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1227 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001228 BOp->getParent() != CurBB->getBasicBlock() ||
1229 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1230 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001231 const BasicBlock *BB = CurBB->getBasicBlock();
1232
Reid Spencere4d87aa2006-12-23 06:05:41 +00001233 // If the leaf of the tree is a comparison, merge the condition into
1234 // the caseblock.
1235 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1236 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001237 // how to export them from some other block. If this is the first block
1238 // of the sequence, no exporting is needed.
1239 (CurBB == CurMBB ||
1240 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1241 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001242 BOp = cast<Instruction>(Cond);
1243 ISD::CondCode Condition;
1244 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1245 switch (IC->getPredicate()) {
1246 default: assert(0 && "Unknown icmp predicate opcode!");
1247 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1248 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1249 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1250 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1251 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1252 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1253 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1254 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1255 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1256 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1257 }
1258 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1259 ISD::CondCode FPC, FOC;
1260 switch (FC->getPredicate()) {
1261 default: assert(0 && "Unknown fcmp predicate opcode!");
1262 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1263 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1264 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1265 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1266 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1267 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1268 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1269 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1270 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1271 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1272 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1273 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1274 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1275 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1276 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1277 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1278 }
1279 if (FiniteOnlyFPMath())
1280 Condition = FOC;
1281 else
1282 Condition = FPC;
1283 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001284 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001285 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001286 }
1287
Chris Lattner571e4342006-10-27 21:36:01 +00001288 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001289 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001290 SwitchCases.push_back(CB);
1291 return;
1292 }
1293
1294 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001295 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001296 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001297 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001298 return;
1299 }
1300
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001301
1302 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001303 MachineFunction::iterator BBI = CurBB;
1304 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1305 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1306
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001307 if (Opc == Instruction::Or) {
1308 // Codegen X | Y as:
1309 // jmp_if_X TBB
1310 // jmp TmpBB
1311 // TmpBB:
1312 // jmp_if_Y TBB
1313 // jmp FBB
1314 //
Chris Lattner571e4342006-10-27 21:36:01 +00001315
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001316 // Emit the LHS condition.
1317 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1318
1319 // Emit the RHS condition into TmpBB.
1320 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1321 } else {
1322 assert(Opc == Instruction::And && "Unknown merge op!");
1323 // Codegen X & Y as:
1324 // jmp_if_X TmpBB
1325 // jmp FBB
1326 // TmpBB:
1327 // jmp_if_Y TBB
1328 // jmp FBB
1329 //
1330 // This requires creation of TmpBB after CurBB.
1331
1332 // Emit the LHS condition.
1333 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1334
1335 // Emit the RHS condition into TmpBB.
1336 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1337 }
Chris Lattner571e4342006-10-27 21:36:01 +00001338}
1339
Chris Lattnerdf19f272006-10-31 22:37:42 +00001340/// If the set of cases should be emitted as a series of branches, return true.
1341/// If we should emit this as a bunch of and/or'd together conditions, return
1342/// false.
1343static bool
1344ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1345 if (Cases.size() != 2) return true;
1346
Chris Lattner0ccb5002006-10-31 23:06:00 +00001347 // If this is two comparisons of the same values or'd or and'd together, they
1348 // will get folded into a single comparison, so don't emit two blocks.
1349 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1350 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1351 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1352 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1353 return false;
1354 }
1355
Chris Lattnerdf19f272006-10-31 22:37:42 +00001356 return true;
1357}
1358
Chris Lattner1c08c712005-01-07 07:47:53 +00001359void SelectionDAGLowering::visitBr(BranchInst &I) {
1360 // Update machine-CFG edges.
1361 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001362
1363 // Figure out which block is immediately after the current one.
1364 MachineBasicBlock *NextBlock = 0;
1365 MachineFunction::iterator BBI = CurMBB;
1366 if (++BBI != CurMBB->getParent()->end())
1367 NextBlock = BBI;
1368
1369 if (I.isUnconditional()) {
1370 // If this is not a fall-through branch, emit the branch.
1371 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001372 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001373 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001374
Chris Lattner57ab6592006-10-24 17:57:59 +00001375 // Update machine-CFG edges.
1376 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001377 return;
1378 }
1379
1380 // If this condition is one of the special cases we handle, do special stuff
1381 // now.
1382 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001383 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001384
1385 // If this is a series of conditions that are or'd or and'd together, emit
1386 // this as a sequence of branches instead of setcc's with and/or operations.
1387 // For example, instead of something like:
1388 // cmp A, B
1389 // C = seteq
1390 // cmp D, E
1391 // F = setle
1392 // or C, F
1393 // jnz foo
1394 // Emit:
1395 // cmp A, B
1396 // je foo
1397 // cmp D, E
1398 // jle foo
1399 //
1400 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1401 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001402 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001403 BOp->getOpcode() == Instruction::Or)) {
1404 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001405 // If the compares in later blocks need to use values not currently
1406 // exported from this block, export them now. This block should always
1407 // be the first entry.
1408 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1409
Chris Lattnerdf19f272006-10-31 22:37:42 +00001410 // Allow some cases to be rejected.
1411 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001412 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1413 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1414 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1415 }
1416
1417 // Emit the branch for this block.
1418 visitSwitchCase(SwitchCases[0]);
1419 SwitchCases.erase(SwitchCases.begin());
1420 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001421 }
1422
Chris Lattner0ccb5002006-10-31 23:06:00 +00001423 // Okay, we decided not to do this, remove any inserted MBB's and clear
1424 // SwitchCases.
1425 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1426 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1427
Chris Lattnerdf19f272006-10-31 22:37:42 +00001428 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001429 }
1430 }
Chris Lattner24525952006-10-24 18:07:37 +00001431
1432 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001433 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001434 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001435 // Use visitSwitchCase to actually insert the fast branch sequence for this
1436 // cond branch.
1437 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001438}
1439
Nate Begemanf15485a2006-03-27 01:32:24 +00001440/// visitSwitchCase - Emits the necessary code to represent a single node in
1441/// the binary search tree resulting from lowering a switch instruction.
1442void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001443 SDOperand Cond;
1444 SDOperand CondLHS = getValue(CB.CmpLHS);
1445
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001446 // Build the setcc now.
1447 if (CB.CmpMHS == NULL) {
1448 // Fold "(X == true)" to X and "(X == false)" to !X to
1449 // handle common cases produced by branch lowering.
1450 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1451 Cond = CondLHS;
1452 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1453 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1454 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1455 } else
1456 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1457 } else {
1458 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001459
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001460 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1461 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1462
1463 SDOperand CmpOp = getValue(CB.CmpMHS);
1464 MVT::ValueType VT = CmpOp.getValueType();
1465
1466 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1467 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1468 } else {
1469 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1470 Cond = DAG.getSetCC(MVT::i1, SUB,
1471 DAG.getConstant(High-Low, VT), ISD::SETULE);
1472 }
1473
1474 }
1475
Nate Begemanf15485a2006-03-27 01:32:24 +00001476 // Set NextBlock to be the MBB immediately after the current one, if any.
1477 // This is used to avoid emitting unnecessary branches to the next block.
1478 MachineBasicBlock *NextBlock = 0;
1479 MachineFunction::iterator BBI = CurMBB;
1480 if (++BBI != CurMBB->getParent()->end())
1481 NextBlock = BBI;
1482
1483 // If the lhs block is the next block, invert the condition so that we can
1484 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001485 if (CB.TrueBB == NextBlock) {
1486 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001487 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1488 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1489 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001490 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001491 DAG.getBasicBlock(CB.TrueBB));
1492 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001493 DAG.setRoot(BrCond);
1494 else
1495 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001496 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001497 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001498 CurMBB->addSuccessor(CB.TrueBB);
1499 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001500}
1501
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001502/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001503void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001504 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001505 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001506 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001507 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001508 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1509 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1510 Table, Index));
1511 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001512}
1513
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001514/// visitJumpTableHeader - This function emits necessary code to produce index
1515/// in the JumpTable from switch case.
1516void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1517 SelectionDAGISel::JumpTableHeader &JTH) {
1518 // Subtract the lowest switch case value from the value being switched on
1519 // and conditional branch to default mbb if the result is greater than the
1520 // difference between smallest and largest cases.
1521 SDOperand SwitchOp = getValue(JTH.SValue);
1522 MVT::ValueType VT = SwitchOp.getValueType();
1523 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1524 DAG.getConstant(JTH.First, VT));
1525
1526 // The SDNode we just created, which holds the value being switched on
1527 // minus the the smallest case value, needs to be copied to a virtual
1528 // register so it can be used as an index into the jump table in a
1529 // subsequent basic block. This value may be smaller or larger than the
1530 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001531 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001532 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1533 else
1534 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1535
1536 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001537 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001538 JT.Reg = JumpTableReg;
1539
1540 // Emit the range check for the jump table, and branch to the default
1541 // block for the switch statement if the value being switched on exceeds
1542 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001543 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001544 DAG.getConstant(JTH.Last-JTH.First,VT),
1545 ISD::SETUGT);
1546
1547 // Set NextBlock to be the MBB immediately after the current one, if any.
1548 // This is used to avoid emitting unnecessary branches to the next block.
1549 MachineBasicBlock *NextBlock = 0;
1550 MachineFunction::iterator BBI = CurMBB;
1551 if (++BBI != CurMBB->getParent()->end())
1552 NextBlock = BBI;
1553
1554 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1555 DAG.getBasicBlock(JT.Default));
1556
1557 if (JT.MBB == NextBlock)
1558 DAG.setRoot(BrCond);
1559 else
1560 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001561 DAG.getBasicBlock(JT.MBB)));
1562
1563 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001564}
1565
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001566/// visitBitTestHeader - This function emits necessary code to produce value
1567/// suitable for "bit tests"
1568void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1569 // Subtract the minimum value
1570 SDOperand SwitchOp = getValue(B.SValue);
1571 MVT::ValueType VT = SwitchOp.getValueType();
1572 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1573 DAG.getConstant(B.First, VT));
1574
1575 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001576 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001577 DAG.getConstant(B.Range, VT),
1578 ISD::SETUGT);
1579
1580 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001581 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001582 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1583 else
1584 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1585
1586 // Make desired shift
1587 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1588 DAG.getConstant(1, TLI.getPointerTy()),
1589 ShiftOp);
1590
1591 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001592 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001593 B.Reg = SwitchReg;
1594
1595 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1596 DAG.getBasicBlock(B.Default));
1597
1598 // Set NextBlock to be the MBB immediately after the current one, if any.
1599 // This is used to avoid emitting unnecessary branches to the next block.
1600 MachineBasicBlock *NextBlock = 0;
1601 MachineFunction::iterator BBI = CurMBB;
1602 if (++BBI != CurMBB->getParent()->end())
1603 NextBlock = BBI;
1604
1605 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1606 if (MBB == NextBlock)
1607 DAG.setRoot(BrRange);
1608 else
1609 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1610 DAG.getBasicBlock(MBB)));
1611
1612 CurMBB->addSuccessor(B.Default);
1613 CurMBB->addSuccessor(MBB);
1614
1615 return;
1616}
1617
1618/// visitBitTestCase - this function produces one "bit test"
1619void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1620 unsigned Reg,
1621 SelectionDAGISel::BitTestCase &B) {
1622 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001623 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001624
1625 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1626 SwitchVal,
1627 DAG.getConstant(B.Mask,
1628 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001629 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001630 DAG.getConstant(0, TLI.getPointerTy()),
1631 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001632 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001633 AndCmp, DAG.getBasicBlock(B.TargetBB));
1634
1635 // Set NextBlock to be the MBB immediately after the current one, if any.
1636 // This is used to avoid emitting unnecessary branches to the next block.
1637 MachineBasicBlock *NextBlock = 0;
1638 MachineFunction::iterator BBI = CurMBB;
1639 if (++BBI != CurMBB->getParent()->end())
1640 NextBlock = BBI;
1641
1642 if (NextMBB == NextBlock)
1643 DAG.setRoot(BrAnd);
1644 else
1645 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1646 DAG.getBasicBlock(NextMBB)));
1647
1648 CurMBB->addSuccessor(B.TargetBB);
1649 CurMBB->addSuccessor(NextMBB);
1650
1651 return;
1652}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001653
Jim Laskeyb180aa12007-02-21 22:53:45 +00001654void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1655 // Retrieve successors.
1656 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001657 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001658
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001659 if (isa<InlineAsm>(I.getCalledValue()))
1660 visitInlineAsm(&I);
1661 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001662 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001663
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001664 // If the value of the invoke is used outside of its defining block, make it
1665 // available as a virtual register.
1666 if (!I.use_empty()) {
1667 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1668 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001669 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001670 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001671
1672 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001673 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001674 DAG.getBasicBlock(Return)));
1675
1676 // Update successor info
1677 CurMBB->addSuccessor(Return);
1678 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001679}
1680
1681void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1682}
1683
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001684/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001685/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001686bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001687 CaseRecVector& WorkList,
1688 Value* SV,
1689 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001690 Case& BackCase = *(CR.Range.second-1);
1691
1692 // Size is the number of Cases represented by this range.
1693 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001694 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001695 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001696
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001697 // Get the MachineFunction which holds the current MBB. This is used when
1698 // inserting any additional MBBs necessary to represent the switch.
1699 MachineFunction *CurMF = CurMBB->getParent();
1700
1701 // Figure out which block is immediately after the current one.
1702 MachineBasicBlock *NextBlock = 0;
1703 MachineFunction::iterator BBI = CR.CaseBB;
1704
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001705 if (++BBI != CurMBB->getParent()->end())
1706 NextBlock = BBI;
1707
1708 // TODO: If any two of the cases has the same destination, and if one value
1709 // is the same as the other, but has one bit unset that the other has set,
1710 // use bit manipulation to do two compares at once. For example:
1711 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1712
1713 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001714 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001715 // The last case block won't fall through into 'NextBlock' if we emit the
1716 // branches in this order. See if rearranging a case value would help.
1717 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001718 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001719 std::swap(*I, BackCase);
1720 break;
1721 }
1722 }
1723 }
1724
1725 // Create a CaseBlock record representing a conditional branch to
1726 // the Case's target mbb if the value being switched on SV is equal
1727 // to C.
1728 MachineBasicBlock *CurBlock = CR.CaseBB;
1729 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1730 MachineBasicBlock *FallThrough;
1731 if (I != E-1) {
1732 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1733 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1734 } else {
1735 // If the last case doesn't match, go to the default block.
1736 FallThrough = Default;
1737 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001738
1739 Value *RHS, *LHS, *MHS;
1740 ISD::CondCode CC;
1741 if (I->High == I->Low) {
1742 // This is just small small case range :) containing exactly 1 case
1743 CC = ISD::SETEQ;
1744 LHS = SV; RHS = I->High; MHS = NULL;
1745 } else {
1746 CC = ISD::SETLE;
1747 LHS = I->Low; MHS = SV; RHS = I->High;
1748 }
1749 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1750 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001751
1752 // If emitting the first comparison, just call visitSwitchCase to emit the
1753 // code into the current block. Otherwise, push the CaseBlock onto the
1754 // vector to be later processed by SDISel, and insert the node's MBB
1755 // before the next MBB.
1756 if (CurBlock == CurMBB)
1757 visitSwitchCase(CB);
1758 else
1759 SwitchCases.push_back(CB);
1760
1761 CurBlock = FallThrough;
1762 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001763
1764 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001765}
1766
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001767static inline bool areJTsAllowed(const TargetLowering &TLI) {
1768 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1769 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1770}
1771
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001772/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001773bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001774 CaseRecVector& WorkList,
1775 Value* SV,
1776 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001777 Case& FrontCase = *CR.Range.first;
1778 Case& BackCase = *(CR.Range.second-1);
1779
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001780 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1781 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1782
1783 uint64_t TSize = 0;
1784 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1785 I!=E; ++I)
1786 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001787
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001788 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001789 return false;
1790
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001791 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1792 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001793 return false;
1794
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001795 DOUT << "Lowering jump table\n"
1796 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001797 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001798
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001799 // Get the MachineFunction which holds the current MBB. This is used when
1800 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001801 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001802
1803 // Figure out which block is immediately after the current one.
1804 MachineBasicBlock *NextBlock = 0;
1805 MachineFunction::iterator BBI = CR.CaseBB;
1806
1807 if (++BBI != CurMBB->getParent()->end())
1808 NextBlock = BBI;
1809
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001810 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1811
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001812 // Create a new basic block to hold the code for loading the address
1813 // of the jump table, and jumping to it. Update successor information;
1814 // we will either branch to the default case for the switch, or the jump
1815 // table.
1816 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1817 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1818 CR.CaseBB->addSuccessor(Default);
1819 CR.CaseBB->addSuccessor(JumpTableBB);
1820
1821 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001822 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001823 // a case statement, push the case's BB onto the vector, otherwise, push
1824 // the default BB.
1825 std::vector<MachineBasicBlock*> DestBBs;
1826 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001827 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1828 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1829 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1830
1831 if ((Low <= TEI) && (TEI <= High)) {
1832 DestBBs.push_back(I->BB);
1833 if (TEI==High)
1834 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001835 } else {
1836 DestBBs.push_back(Default);
1837 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001838 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001839
1840 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001841 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001842 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1843 E = DestBBs.end(); I != E; ++I) {
1844 if (!SuccsHandled[(*I)->getNumber()]) {
1845 SuccsHandled[(*I)->getNumber()] = true;
1846 JumpTableBB->addSuccessor(*I);
1847 }
1848 }
1849
1850 // Create a jump table index for this jump table, or return an existing
1851 // one.
1852 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1853
1854 // Set the jump table information so that we can codegen it as a second
1855 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001856 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001857 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1858 (CR.CaseBB == CurMBB));
1859 if (CR.CaseBB == CurMBB)
1860 visitJumpTableHeader(JT, JTH);
1861
1862 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001863
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001864 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001865}
1866
1867/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1868/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001869bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001870 CaseRecVector& WorkList,
1871 Value* SV,
1872 MachineBasicBlock* Default) {
1873 // Get the MachineFunction which holds the current MBB. This is used when
1874 // inserting any additional MBBs necessary to represent the switch.
1875 MachineFunction *CurMF = CurMBB->getParent();
1876
1877 // Figure out which block is immediately after the current one.
1878 MachineBasicBlock *NextBlock = 0;
1879 MachineFunction::iterator BBI = CR.CaseBB;
1880
1881 if (++BBI != CurMBB->getParent()->end())
1882 NextBlock = BBI;
1883
1884 Case& FrontCase = *CR.Range.first;
1885 Case& BackCase = *(CR.Range.second-1);
1886 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1887
1888 // Size is the number of Cases represented by this range.
1889 unsigned Size = CR.Range.second - CR.Range.first;
1890
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001891 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1892 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001893 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001894 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001895
1896 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1897 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001898 uint64_t TSize = 0;
1899 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1900 I!=E; ++I)
1901 TSize += I->size();
1902
1903 uint64_t LSize = FrontCase.size();
1904 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001905 DOUT << "Selecting best pivot: \n"
1906 << "First: " << First << ", Last: " << Last <<"\n"
1907 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001908 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001909 J!=E; ++I, ++J) {
1910 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1911 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001912 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001913 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1914 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001915 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001916 // Should always split in some non-trivial place
1917 DOUT <<"=>Step\n"
1918 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1919 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1920 << "Metric: " << Metric << "\n";
1921 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001922 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001923 FMetric = Metric;
1924 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001925 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001926
1927 LSize += J->size();
1928 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001929 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001930 if (areJTsAllowed(TLI)) {
1931 // If our case is dense we *really* should handle it earlier!
1932 assert((FMetric > 0) && "Should handle dense range earlier!");
1933 } else {
1934 Pivot = CR.Range.first + Size/2;
1935 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936
1937 CaseRange LHSR(CR.Range.first, Pivot);
1938 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001939 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001940 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1941
1942 // We know that we branch to the LHS if the Value being switched on is
1943 // less than the Pivot value, C. We use this to optimize our binary
1944 // tree a bit, by recognizing that if SV is greater than or equal to the
1945 // LHS's Case Value, and that Case Value is exactly one less than the
1946 // Pivot's Value, then we can branch directly to the LHS's Target,
1947 // rather than creating a leaf node for it.
1948 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001949 LHSR.first->High == CR.GE &&
1950 cast<ConstantInt>(C)->getSExtValue() ==
1951 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1952 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001953 } else {
1954 TrueBB = new MachineBasicBlock(LLVMBB);
1955 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1956 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1957 }
1958
1959 // Similar to the optimization above, if the Value being switched on is
1960 // known to be less than the Constant CR.LT, and the current Case Value
1961 // is CR.LT - 1, then we can branch directly to the target block for
1962 // the current Case Value, rather than emitting a RHS leaf node for it.
1963 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001964 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1965 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1966 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001967 } else {
1968 FalseBB = new MachineBasicBlock(LLVMBB);
1969 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1970 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1971 }
1972
1973 // Create a CaseBlock record representing a conditional branch to
1974 // the LHS node if the value being switched on SV is less than C.
1975 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001976 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1977 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001978
1979 if (CR.CaseBB == CurMBB)
1980 visitSwitchCase(CB);
1981 else
1982 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001983
1984 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001985}
1986
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001987/// handleBitTestsSwitchCase - if current case range has few destination and
1988/// range span less, than machine word bitwidth, encode case range into series
1989/// of masks and emit bit tests with these masks.
1990bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1991 CaseRecVector& WorkList,
1992 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001993 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001994 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001995
1996 Case& FrontCase = *CR.Range.first;
1997 Case& BackCase = *(CR.Range.second-1);
1998
1999 // Get the MachineFunction which holds the current MBB. This is used when
2000 // inserting any additional MBBs necessary to represent the switch.
2001 MachineFunction *CurMF = CurMBB->getParent();
2002
2003 unsigned numCmps = 0;
2004 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2005 I!=E; ++I) {
2006 // Single case counts one, case range - two.
2007 if (I->Low == I->High)
2008 numCmps +=1;
2009 else
2010 numCmps +=2;
2011 }
2012
2013 // Count unique destinations
2014 SmallSet<MachineBasicBlock*, 4> Dests;
2015 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2016 Dests.insert(I->BB);
2017 if (Dests.size() > 3)
2018 // Don't bother the code below, if there are too much unique destinations
2019 return false;
2020 }
2021 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2022 << "Total number of comparisons: " << numCmps << "\n";
2023
2024 // Compute span of values.
2025 Constant* minValue = FrontCase.Low;
2026 Constant* maxValue = BackCase.High;
2027 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2028 cast<ConstantInt>(minValue)->getSExtValue();
2029 DOUT << "Compare range: " << range << "\n"
2030 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2031 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2032
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002033 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002034 (!(Dests.size() == 1 && numCmps >= 3) &&
2035 !(Dests.size() == 2 && numCmps >= 5) &&
2036 !(Dests.size() >= 3 && numCmps >= 6)))
2037 return false;
2038
2039 DOUT << "Emitting bit tests\n";
2040 int64_t lowBound = 0;
2041
2042 // Optimize the case where all the case values fit in a
2043 // word without having to subtract minValue. In this case,
2044 // we can optimize away the subtraction.
2045 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002046 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002047 range = cast<ConstantInt>(maxValue)->getSExtValue();
2048 } else {
2049 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2050 }
2051
2052 CaseBitsVector CasesBits;
2053 unsigned i, count = 0;
2054
2055 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2056 MachineBasicBlock* Dest = I->BB;
2057 for (i = 0; i < count; ++i)
2058 if (Dest == CasesBits[i].BB)
2059 break;
2060
2061 if (i == count) {
2062 assert((count < 3) && "Too much destinations to test!");
2063 CasesBits.push_back(CaseBits(0, Dest, 0));
2064 count++;
2065 }
2066
2067 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2068 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2069
2070 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002071 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002072 CasesBits[i].Bits++;
2073 }
2074
2075 }
2076 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2077
2078 SelectionDAGISel::BitTestInfo BTC;
2079
2080 // Figure out which block is immediately after the current one.
2081 MachineFunction::iterator BBI = CR.CaseBB;
2082 ++BBI;
2083
2084 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2085
2086 DOUT << "Cases:\n";
2087 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2088 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2089 << ", BB: " << CasesBits[i].BB << "\n";
2090
2091 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2092 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2093 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2094 CaseBB,
2095 CasesBits[i].BB));
2096 }
2097
2098 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002099 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002100 CR.CaseBB, Default, BTC);
2101
2102 if (CR.CaseBB == CurMBB)
2103 visitBitTestHeader(BTB);
2104
2105 BitTestCases.push_back(BTB);
2106
2107 return true;
2108}
2109
2110
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002111/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002112unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2113 const SwitchInst& SI) {
2114 unsigned numCmps = 0;
2115
2116 // Start with "simple" cases
2117 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2118 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2119 Cases.push_back(Case(SI.getSuccessorValue(i),
2120 SI.getSuccessorValue(i),
2121 SMBB));
2122 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002123 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002124
2125 // Merge case into clusters
2126 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002127 // Must recompute end() each iteration because it may be
2128 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002129 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002130 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2131 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2132 MachineBasicBlock* nextBB = J->BB;
2133 MachineBasicBlock* currentBB = I->BB;
2134
2135 // If the two neighboring cases go to the same destination, merge them
2136 // into a single case.
2137 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2138 I->High = J->High;
2139 J = Cases.erase(J);
2140 } else {
2141 I = J++;
2142 }
2143 }
2144
2145 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2146 if (I->Low != I->High)
2147 // A range counts double, since it requires two compares.
2148 ++numCmps;
2149 }
2150
2151 return numCmps;
2152}
2153
2154void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002155 // Figure out which block is immediately after the current one.
2156 MachineBasicBlock *NextBlock = 0;
2157 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002158
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002159 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002160
Nate Begemanf15485a2006-03-27 01:32:24 +00002161 // If there is only the default destination, branch to it if it is not the
2162 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002163 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002164 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002165
Nate Begemanf15485a2006-03-27 01:32:24 +00002166 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002167 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002168 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002169 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002170
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002171 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002172 return;
2173 }
2174
2175 // If there are any non-default case statements, create a vector of Cases
2176 // representing each one, and sort the vector so that we can efficiently
2177 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002178 CaseVector Cases;
2179 unsigned numCmps = Clusterify(Cases, SI);
2180 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2181 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002182
Nate Begemanf15485a2006-03-27 01:32:24 +00002183 // Get the Value to be switched on and default basic blocks, which will be
2184 // inserted into CaseBlock records, representing basic blocks in the binary
2185 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002186 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002187
Nate Begemanf15485a2006-03-27 01:32:24 +00002188 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002189 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002190 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2191
2192 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002193 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002194 CaseRec CR = WorkList.back();
2195 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002196
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002197 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2198 continue;
2199
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002200 // If the range has few cases (two or less) emit a series of specific
2201 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002202 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2203 continue;
2204
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002205 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002206 // target supports indirect branches, then emit a jump table rather than
2207 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002208 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2209 continue;
2210
2211 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2212 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2213 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002214 }
2215}
2216
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002217
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002218void SelectionDAGLowering::visitSub(User &I) {
2219 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002220 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002221 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002222 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2223 const VectorType *DestTy = cast<VectorType>(I.getType());
2224 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002225 if (ElTy->isFloatingPoint()) {
2226 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002227 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002228 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2229 if (CV == CNZ) {
2230 SDOperand Op2 = getValue(I.getOperand(1));
2231 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2232 return;
2233 }
Dan Gohman7f321562007-06-25 16:23:39 +00002234 }
2235 }
2236 }
2237 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002238 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002239 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002240 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 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002247}
2248
Dan Gohman7f321562007-06-25 16:23:39 +00002249void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002250 SDOperand Op1 = getValue(I.getOperand(0));
2251 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002252
2253 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002254}
2255
Nate Begemane21ea612005-11-18 07:42:56 +00002256void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2257 SDOperand Op1 = getValue(I.getOperand(0));
2258 SDOperand Op2 = getValue(I.getOperand(1));
2259
Dan Gohman7f321562007-06-25 16:23:39 +00002260 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2261 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002262 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2263 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2264 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002265
Chris Lattner1c08c712005-01-07 07:47:53 +00002266 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2267}
2268
Reid Spencer45fb3f32006-11-20 01:22:35 +00002269void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002270 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2271 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2272 predicate = IC->getPredicate();
2273 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2274 predicate = ICmpInst::Predicate(IC->getPredicate());
2275 SDOperand Op1 = getValue(I.getOperand(0));
2276 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002277 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002278 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002279 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2280 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2281 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2282 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2283 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2284 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2285 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2286 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2287 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2288 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2289 default:
2290 assert(!"Invalid ICmp predicate value");
2291 Opcode = ISD::SETEQ;
2292 break;
2293 }
2294 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2295}
2296
2297void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002298 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2299 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2300 predicate = FC->getPredicate();
2301 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2302 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002303 SDOperand Op1 = getValue(I.getOperand(0));
2304 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002305 ISD::CondCode Condition, FOC, FPC;
2306 switch (predicate) {
2307 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2308 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2309 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2310 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2311 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2312 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2313 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2314 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2315 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2316 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2317 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2318 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2319 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2320 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2321 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2322 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2323 default:
2324 assert(!"Invalid FCmp predicate value");
2325 FOC = FPC = ISD::SETFALSE;
2326 break;
2327 }
2328 if (FiniteOnlyFPMath())
2329 Condition = FOC;
2330 else
2331 Condition = FPC;
2332 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002333}
2334
2335void SelectionDAGLowering::visitSelect(User &I) {
2336 SDOperand Cond = getValue(I.getOperand(0));
2337 SDOperand TrueVal = getValue(I.getOperand(1));
2338 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002339 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2340 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002341}
2342
Reid Spencer3da59db2006-11-27 01:05:10 +00002343
2344void SelectionDAGLowering::visitTrunc(User &I) {
2345 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2346 SDOperand N = getValue(I.getOperand(0));
2347 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2348 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2349}
2350
2351void SelectionDAGLowering::visitZExt(User &I) {
2352 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2353 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2354 SDOperand N = getValue(I.getOperand(0));
2355 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2356 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2357}
2358
2359void SelectionDAGLowering::visitSExt(User &I) {
2360 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2361 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2362 SDOperand N = getValue(I.getOperand(0));
2363 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2364 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2365}
2366
2367void SelectionDAGLowering::visitFPTrunc(User &I) {
2368 // FPTrunc is never a no-op cast, no need to check
2369 SDOperand N = getValue(I.getOperand(0));
2370 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002371 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002372}
2373
2374void SelectionDAGLowering::visitFPExt(User &I){
2375 // FPTrunc is never a no-op cast, no need to check
2376 SDOperand N = getValue(I.getOperand(0));
2377 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2378 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2379}
2380
2381void SelectionDAGLowering::visitFPToUI(User &I) {
2382 // FPToUI is never a no-op cast, no need to check
2383 SDOperand N = getValue(I.getOperand(0));
2384 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2385 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2386}
2387
2388void SelectionDAGLowering::visitFPToSI(User &I) {
2389 // FPToSI is never a no-op cast, no need to check
2390 SDOperand N = getValue(I.getOperand(0));
2391 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2392 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2393}
2394
2395void SelectionDAGLowering::visitUIToFP(User &I) {
2396 // UIToFP is never a no-op cast, no need to check
2397 SDOperand N = getValue(I.getOperand(0));
2398 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2399 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2400}
2401
2402void SelectionDAGLowering::visitSIToFP(User &I){
2403 // UIToFP is never a no-op cast, no need to check
2404 SDOperand N = getValue(I.getOperand(0));
2405 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2406 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2407}
2408
2409void SelectionDAGLowering::visitPtrToInt(User &I) {
2410 // What to do depends on the size of the integer and the size of the pointer.
2411 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002412 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002413 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002414 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002415 SDOperand Result;
2416 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2417 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2418 else
2419 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2420 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2421 setValue(&I, Result);
2422}
Chris Lattner1c08c712005-01-07 07:47:53 +00002423
Reid Spencer3da59db2006-11-27 01:05:10 +00002424void SelectionDAGLowering::visitIntToPtr(User &I) {
2425 // What to do depends on the size of the integer and the size of the pointer.
2426 // We can either truncate, zero extend, or no-op, accordingly.
2427 SDOperand N = getValue(I.getOperand(0));
2428 MVT::ValueType SrcVT = N.getValueType();
2429 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2430 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2431 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2432 else
2433 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2434 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2435}
2436
2437void SelectionDAGLowering::visitBitCast(User &I) {
2438 SDOperand N = getValue(I.getOperand(0));
2439 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002440
2441 // BitCast assures us that source and destination are the same size so this
2442 // is either a BIT_CONVERT or a no-op.
2443 if (DestVT != N.getValueType())
2444 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2445 else
2446 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002447}
2448
Chris Lattner2bbd8102006-03-29 00:11:43 +00002449void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002450 SDOperand InVec = getValue(I.getOperand(0));
2451 SDOperand InVal = getValue(I.getOperand(1));
2452 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2453 getValue(I.getOperand(2)));
2454
Dan Gohman7f321562007-06-25 16:23:39 +00002455 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2456 TLI.getValueType(I.getType()),
2457 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002458}
2459
Chris Lattner2bbd8102006-03-29 00:11:43 +00002460void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002461 SDOperand InVec = getValue(I.getOperand(0));
2462 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2463 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002464 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002465 TLI.getValueType(I.getType()), InVec, InIdx));
2466}
Chris Lattnerc7029802006-03-18 01:44:44 +00002467
Chris Lattner3e104b12006-04-08 04:15:24 +00002468void SelectionDAGLowering::visitShuffleVector(User &I) {
2469 SDOperand V1 = getValue(I.getOperand(0));
2470 SDOperand V2 = getValue(I.getOperand(1));
2471 SDOperand Mask = getValue(I.getOperand(2));
2472
Dan Gohman7f321562007-06-25 16:23:39 +00002473 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2474 TLI.getValueType(I.getType()),
2475 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002476}
2477
2478
Chris Lattner1c08c712005-01-07 07:47:53 +00002479void SelectionDAGLowering::visitGetElementPtr(User &I) {
2480 SDOperand N = getValue(I.getOperand(0));
2481 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002482
2483 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2484 OI != E; ++OI) {
2485 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002486 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002487 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002488 if (Field) {
2489 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002490 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002491 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002492 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002493 }
2494 Ty = StTy->getElementType(Field);
2495 } else {
2496 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002497
Chris Lattner7c0104b2005-11-09 04:45:33 +00002498 // If this is a constant subscript, handle it quickly.
2499 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002500 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002501 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002502 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002503 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2504 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002505 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002506 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002507
2508 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002509 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002510 SDOperand IdxN = getValue(Idx);
2511
2512 // If the index is smaller or larger than intptr_t, truncate or extend
2513 // it.
2514 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002515 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002516 } else if (IdxN.getValueType() > N.getValueType())
2517 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2518
2519 // If this is a multiply by a power of two, turn it into a shl
2520 // immediately. This is a very common case.
2521 if (isPowerOf2_64(ElementSize)) {
2522 unsigned Amt = Log2_64(ElementSize);
2523 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002524 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002525 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2526 continue;
2527 }
2528
Chris Lattner0bd48932008-01-17 07:00:52 +00002529 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002530 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2531 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002532 }
2533 }
2534 setValue(&I, N);
2535}
2536
2537void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2538 // If this is a fixed sized alloca in the entry block of the function,
2539 // allocate it statically on the stack.
2540 if (FuncInfo.StaticAllocaMap.count(&I))
2541 return; // getValue will auto-populate this.
2542
2543 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002544 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002545 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002546 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002547 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002548
2549 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002550 MVT::ValueType IntPtr = TLI.getPointerTy();
2551 if (IntPtr < AllocSize.getValueType())
2552 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2553 else if (IntPtr > AllocSize.getValueType())
2554 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002555
Chris Lattner68cd65e2005-01-22 23:04:37 +00002556 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002557 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002558
Evan Cheng45157792007-08-16 23:46:29 +00002559 // Handle alignment. If the requested alignment is less than or equal to
2560 // the stack alignment, ignore it. If the size is greater than or equal to
2561 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002562 unsigned StackAlign =
2563 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002564 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002565 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002566
2567 // Round the size of the allocation up to the stack alignment size
2568 // by add SA-1 to the size.
2569 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002570 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002571 // Mask out the low bits for alignment purposes.
2572 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002573 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002574
Chris Lattner0bd48932008-01-17 07:00:52 +00002575 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002576 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2577 MVT::Other);
2578 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002579 setValue(&I, DSA);
2580 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002581
2582 // Inform the Frame Information that we have just allocated a variable-sized
2583 // object.
2584 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2585}
2586
Chris Lattner1c08c712005-01-07 07:47:53 +00002587void SelectionDAGLowering::visitLoad(LoadInst &I) {
2588 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002589
Chris Lattnerd3948112005-01-17 22:19:26 +00002590 SDOperand Root;
2591 if (I.isVolatile())
2592 Root = getRoot();
2593 else {
2594 // Do not serialize non-volatile loads against each other.
2595 Root = DAG.getRoot();
2596 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002597
Evan Cheng466685d2006-10-09 20:57:25 +00002598 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002599 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002600}
2601
2602SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002603 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002604 bool isVolatile,
2605 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002606 SDOperand L =
2607 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2608 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002609
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002610 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002611 DAG.setRoot(L.getValue(1));
2612 else
2613 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002614
2615 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002616}
2617
2618
2619void SelectionDAGLowering::visitStore(StoreInst &I) {
2620 Value *SrcV = I.getOperand(0);
2621 SDOperand Src = getValue(SrcV);
2622 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002623 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002624 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002625}
2626
Chris Lattner0eade312006-03-24 02:22:33 +00002627/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2628/// node.
2629void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2630 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002631 bool HasChain = !I.doesNotAccessMemory();
2632 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2633
Chris Lattner0eade312006-03-24 02:22:33 +00002634 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002635 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002636 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2637 if (OnlyLoad) {
2638 // We don't need to serialize loads against other loads.
2639 Ops.push_back(DAG.getRoot());
2640 } else {
2641 Ops.push_back(getRoot());
2642 }
2643 }
Chris Lattner0eade312006-03-24 02:22:33 +00002644
2645 // Add the intrinsic ID as an integer operand.
2646 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2647
2648 // Add all operands of the call to the operand list.
2649 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2650 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002651 assert(TLI.isTypeLegal(Op.getValueType()) &&
2652 "Intrinsic uses a non-legal type?");
2653 Ops.push_back(Op);
2654 }
2655
2656 std::vector<MVT::ValueType> VTs;
2657 if (I.getType() != Type::VoidTy) {
2658 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002659 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002660 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002661 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2662
2663 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2664 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2665 }
2666
2667 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2668 VTs.push_back(VT);
2669 }
2670 if (HasChain)
2671 VTs.push_back(MVT::Other);
2672
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002673 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2674
Chris Lattner0eade312006-03-24 02:22:33 +00002675 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002676 SDOperand Result;
2677 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002678 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2679 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002680 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002681 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2682 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002683 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002684 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2685 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002686
Chris Lattnere58a7802006-04-02 03:41:14 +00002687 if (HasChain) {
2688 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2689 if (OnlyLoad)
2690 PendingLoads.push_back(Chain);
2691 else
2692 DAG.setRoot(Chain);
2693 }
Chris Lattner0eade312006-03-24 02:22:33 +00002694 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002695 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002696 MVT::ValueType VT = TLI.getValueType(PTy);
2697 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002698 }
2699 setValue(&I, Result);
2700 }
2701}
2702
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002703/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002704static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002705 V = IntrinsicInst::StripPointerCasts(V);
2706 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002707 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002708 "TypeInfo must be a global variable or NULL");
2709 return GV;
2710}
2711
Duncan Sandsf4070822007-06-15 19:04:19 +00002712/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002713/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002714static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2715 MachineBasicBlock *MBB) {
2716 // Inform the MachineModuleInfo of the personality for this landing pad.
2717 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2718 assert(CE->getOpcode() == Instruction::BitCast &&
2719 isa<Function>(CE->getOperand(0)) &&
2720 "Personality should be a function");
2721 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2722
2723 // Gather all the type infos for this landing pad and pass them along to
2724 // MachineModuleInfo.
2725 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002726 unsigned N = I.getNumOperands();
2727
2728 for (unsigned i = N - 1; i > 2; --i) {
2729 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2730 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002731 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002732 assert (FirstCatch <= N && "Invalid filter length");
2733
2734 if (FirstCatch < N) {
2735 TyInfo.reserve(N - FirstCatch);
2736 for (unsigned j = FirstCatch; j < N; ++j)
2737 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2738 MMI->addCatchTypeInfo(MBB, TyInfo);
2739 TyInfo.clear();
2740 }
2741
Duncan Sands6590b042007-08-27 15:47:50 +00002742 if (!FilterLength) {
2743 // Cleanup.
2744 MMI->addCleanup(MBB);
2745 } else {
2746 // Filter.
2747 TyInfo.reserve(FilterLength - 1);
2748 for (unsigned j = i + 1; j < FirstCatch; ++j)
2749 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2750 MMI->addFilterTypeInfo(MBB, TyInfo);
2751 TyInfo.clear();
2752 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002753
2754 N = i;
2755 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002756 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002757
2758 if (N > 3) {
2759 TyInfo.reserve(N - 3);
2760 for (unsigned j = 3; j < N; ++j)
2761 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002762 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002763 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002764}
2765
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002766/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2767/// we want to emit this as a call to a named external function, return the name
2768/// otherwise lower it and return null.
2769const char *
2770SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2771 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002772 default:
2773 // By default, turn this into a target intrinsic node.
2774 visitTargetIntrinsic(I, Intrinsic);
2775 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002776 case Intrinsic::vastart: visitVAStart(I); return 0;
2777 case Intrinsic::vaend: visitVAEnd(I); return 0;
2778 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002779 case Intrinsic::returnaddress:
2780 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2781 getValue(I.getOperand(1))));
2782 return 0;
2783 case Intrinsic::frameaddress:
2784 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2785 getValue(I.getOperand(1))));
2786 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002787 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002788 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002789 break;
2790 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002791 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002792 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002793 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002794 case Intrinsic::memcpy_i64: {
2795 SDOperand Op1 = getValue(I.getOperand(1));
2796 SDOperand Op2 = getValue(I.getOperand(2));
2797 SDOperand Op3 = getValue(I.getOperand(3));
2798 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2799 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2800 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002801 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002802 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002803 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002804 case Intrinsic::memset_i64: {
2805 SDOperand Op1 = getValue(I.getOperand(1));
2806 SDOperand Op2 = getValue(I.getOperand(2));
2807 SDOperand Op3 = getValue(I.getOperand(3));
2808 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2809 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2810 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002811 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002812 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002813 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002814 case Intrinsic::memmove_i64: {
2815 SDOperand Op1 = getValue(I.getOperand(1));
2816 SDOperand Op2 = getValue(I.getOperand(2));
2817 SDOperand Op3 = getValue(I.getOperand(3));
2818 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2819
2820 // If the source and destination are known to not be aliases, we can
2821 // lower memmove as memcpy.
2822 uint64_t Size = -1ULL;
2823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2824 Size = C->getValue();
2825 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2826 AliasAnalysis::NoAlias) {
2827 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2828 I.getOperand(1), 0, I.getOperand(2), 0));
2829 return 0;
2830 }
2831
2832 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2833 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002834 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002835 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002836 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002837 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002838 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002839 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002840 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002841
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002842 Ops[0] = getRoot();
2843 Ops[1] = getValue(SPI.getLineValue());
2844 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002845
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002846 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002847 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002848 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2849
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002850 Ops[3] = DAG.getString(CompileUnit->getFileName());
2851 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002852
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002853 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002854 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002855
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002856 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002857 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002858 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002859 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002860 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002861 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2862 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002863 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002864 DAG.getConstant(LabelID, MVT::i32),
2865 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002866 }
2867
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002868 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002869 }
2870 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002871 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002872 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002873 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2874 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002875 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2876 DAG.getConstant(LabelID, MVT::i32),
2877 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002878 }
2879
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002880 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002881 }
2882 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002883 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002884 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002885 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002886 Value *SP = FSI.getSubprogram();
2887 if (SP && MMI->Verify(SP)) {
2888 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2889 // what (most?) gdb expects.
2890 DebugInfoDesc *DD = MMI->getDescFor(SP);
2891 assert(DD && "Not a debug information descriptor");
2892 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2893 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2894 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2895 CompileUnit->getFileName());
2896 // Record the source line but does create a label. It will be emitted
2897 // at asm emission time.
2898 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002899 }
2900
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002901 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002902 }
2903 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002904 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002905 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002906 Value *Variable = DI.getVariable();
2907 if (MMI && Variable && MMI->Verify(Variable))
2908 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2909 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002910 return 0;
2911 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002912
Jim Laskeyb180aa12007-02-21 22:53:45 +00002913 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002914 if (!CurMBB->isLandingPad()) {
2915 // FIXME: Mark exception register as live in. Hack for PR1508.
2916 unsigned Reg = TLI.getExceptionAddressRegister();
2917 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00002918 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002919 // Insert the EXCEPTIONADDR instruction.
2920 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2921 SDOperand Ops[1];
2922 Ops[0] = DAG.getRoot();
2923 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2924 setValue(&I, Op);
2925 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002926 return 0;
2927 }
2928
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002929 case Intrinsic::eh_selector_i32:
2930 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002931 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002932 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2933 MVT::i32 : MVT::i64);
2934
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002935 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002936 if (CurMBB->isLandingPad())
2937 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002938 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002939#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002940 FuncInfo.CatchInfoLost.insert(&I);
2941#endif
Duncan Sands90291952007-07-06 09:18:59 +00002942 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2943 unsigned Reg = TLI.getExceptionSelectorRegister();
2944 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002945 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002946
2947 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002948 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002949 SDOperand Ops[2];
2950 Ops[0] = getValue(I.getOperand(1));
2951 Ops[1] = getRoot();
2952 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2953 setValue(&I, Op);
2954 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002955 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002956 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002957 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002958
2959 return 0;
2960 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002961
2962 case Intrinsic::eh_typeid_for_i32:
2963 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002964 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002965 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2966 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002967
Jim Laskey735b6f82007-02-22 15:38:06 +00002968 if (MMI) {
2969 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002970 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002971
Jim Laskey735b6f82007-02-22 15:38:06 +00002972 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002973 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00002974 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002975 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002976 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002977 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002978
2979 return 0;
2980 }
2981
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002982 case Intrinsic::eh_return: {
2983 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2984
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002985 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002986 MMI->setCallsEHReturn(true);
2987 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2988 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002989 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002990 getValue(I.getOperand(1)),
2991 getValue(I.getOperand(2))));
2992 } else {
2993 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2994 }
2995
2996 return 0;
2997 }
2998
2999 case Intrinsic::eh_unwind_init: {
3000 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3001 MMI->setCallsUnwindInit(true);
3002 }
3003
3004 return 0;
3005 }
3006
3007 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003008 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3009 SDOperand CfaArg;
3010 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3011 CfaArg = DAG.getNode(ISD::TRUNCATE,
3012 TLI.getPointerTy(), getValue(I.getOperand(1)));
3013 else
3014 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3015 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003016
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003017 SDOperand Offset = DAG.getNode(ISD::ADD,
3018 TLI.getPointerTy(),
3019 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3020 TLI.getPointerTy()),
3021 CfaArg);
3022 setValue(&I, DAG.getNode(ISD::ADD,
3023 TLI.getPointerTy(),
3024 DAG.getNode(ISD::FRAMEADDR,
3025 TLI.getPointerTy(),
3026 DAG.getConstant(0,
3027 TLI.getPointerTy())),
3028 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003029 return 0;
3030 }
3031
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003032 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003033 setValue(&I, DAG.getNode(ISD::FSQRT,
3034 getValue(I.getOperand(1)).getValueType(),
3035 getValue(I.getOperand(1))));
3036 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003037 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003038 setValue(&I, DAG.getNode(ISD::FPOWI,
3039 getValue(I.getOperand(1)).getValueType(),
3040 getValue(I.getOperand(1)),
3041 getValue(I.getOperand(2))));
3042 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003043 case Intrinsic::sin:
3044 setValue(&I, DAG.getNode(ISD::FSIN,
3045 getValue(I.getOperand(1)).getValueType(),
3046 getValue(I.getOperand(1))));
3047 return 0;
3048 case Intrinsic::cos:
3049 setValue(&I, DAG.getNode(ISD::FCOS,
3050 getValue(I.getOperand(1)).getValueType(),
3051 getValue(I.getOperand(1))));
3052 return 0;
3053 case Intrinsic::pow:
3054 setValue(&I, DAG.getNode(ISD::FPOW,
3055 getValue(I.getOperand(1)).getValueType(),
3056 getValue(I.getOperand(1)),
3057 getValue(I.getOperand(2))));
3058 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003059 case Intrinsic::pcmarker: {
3060 SDOperand Tmp = getValue(I.getOperand(1));
3061 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3062 return 0;
3063 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003064 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003065 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003066 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3067 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3068 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003069 setValue(&I, Tmp);
3070 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003071 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003072 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003073 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003074 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003075 assert(0 && "part_select intrinsic not implemented");
3076 abort();
3077 }
3078 case Intrinsic::part_set: {
3079 // Currently not implemented: just abort
3080 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003081 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003082 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003083 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003084 setValue(&I, DAG.getNode(ISD::BSWAP,
3085 getValue(I.getOperand(1)).getValueType(),
3086 getValue(I.getOperand(1))));
3087 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003088 case Intrinsic::cttz: {
3089 SDOperand Arg = getValue(I.getOperand(1));
3090 MVT::ValueType Ty = Arg.getValueType();
3091 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003092 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003093 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003094 }
3095 case Intrinsic::ctlz: {
3096 SDOperand Arg = getValue(I.getOperand(1));
3097 MVT::ValueType Ty = Arg.getValueType();
3098 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003099 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003100 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003101 }
3102 case Intrinsic::ctpop: {
3103 SDOperand Arg = getValue(I.getOperand(1));
3104 MVT::ValueType Ty = Arg.getValueType();
3105 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003106 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003107 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003108 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003109 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003110 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003111 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3112 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003113 setValue(&I, Tmp);
3114 DAG.setRoot(Tmp.getValue(1));
3115 return 0;
3116 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003117 case Intrinsic::stackrestore: {
3118 SDOperand Tmp = getValue(I.getOperand(1));
3119 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003120 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003121 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003122 case Intrinsic::var_annotation:
3123 // Discard annotate attributes
3124 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003125
Duncan Sands36397f52007-07-27 12:58:54 +00003126 case Intrinsic::init_trampoline: {
3127 const Function *F =
3128 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3129
3130 SDOperand Ops[6];
3131 Ops[0] = getRoot();
3132 Ops[1] = getValue(I.getOperand(1));
3133 Ops[2] = getValue(I.getOperand(2));
3134 Ops[3] = getValue(I.getOperand(3));
3135 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3136 Ops[5] = DAG.getSrcValue(F);
3137
Duncan Sandsf7331b32007-09-11 14:10:23 +00003138 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3139 DAG.getNodeValueTypes(TLI.getPointerTy(),
3140 MVT::Other), 2,
3141 Ops, 6);
3142
3143 setValue(&I, Tmp);
3144 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003145 return 0;
3146 }
Gordon Henriksence224772008-01-07 01:30:38 +00003147
3148 case Intrinsic::gcroot:
3149 if (GCI) {
3150 Value *Alloca = I.getOperand(1);
3151 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3152
3153 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3154 GCI->addStackRoot(FI->getIndex(), TypeMap);
3155 }
3156 return 0;
3157
3158 case Intrinsic::gcread:
3159 case Intrinsic::gcwrite:
3160 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3161 return 0;
3162
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003163 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003164 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003165 return 0;
3166 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003167
3168 case Intrinsic::trap: {
3169 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3170 return 0;
3171 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003172 case Intrinsic::prefetch: {
3173 SDOperand Ops[4];
3174 Ops[0] = getRoot();
3175 Ops[1] = getValue(I.getOperand(1));
3176 Ops[2] = getValue(I.getOperand(2));
3177 Ops[3] = getValue(I.getOperand(3));
3178 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3179 return 0;
3180 }
3181
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003182 case Intrinsic::memory_barrier: {
3183 SDOperand Ops[6];
3184 Ops[0] = getRoot();
3185 for (int x = 1; x < 6; ++x)
3186 Ops[x] = getValue(I.getOperand(x));
3187
3188 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3189 return 0;
3190 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003191 case Intrinsic::atomic_lcs: {
3192 SDOperand Root = getRoot();
3193 SDOperand O3 = getValue(I.getOperand(3));
3194 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3195 getValue(I.getOperand(1)),
3196 getValue(I.getOperand(2)),
3197 O3, O3.getValueType());
3198 setValue(&I, L);
3199 DAG.setRoot(L.getValue(1));
3200 return 0;
3201 }
3202 case Intrinsic::atomic_las: {
3203 SDOperand Root = getRoot();
3204 SDOperand O2 = getValue(I.getOperand(2));
3205 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3206 getValue(I.getOperand(1)),
3207 O2, O2.getValueType());
3208 setValue(&I, L);
3209 DAG.setRoot(L.getValue(1));
3210 return 0;
3211 }
3212 case Intrinsic::atomic_swap: {
3213 SDOperand Root = getRoot();
3214 SDOperand O2 = getValue(I.getOperand(2));
3215 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3216 getValue(I.getOperand(1)),
3217 O2, O2.getValueType());
3218 setValue(&I, L);
3219 DAG.setRoot(L.getValue(1));
3220 return 0;
3221 }
3222
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003223 }
3224}
3225
3226
Duncan Sands6f74b482007-12-19 09:48:52 +00003227void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003228 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003229 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003230 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003231 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003232 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3233 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003234
Jim Laskey735b6f82007-02-22 15:38:06 +00003235 TargetLowering::ArgListTy Args;
3236 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003237 Args.reserve(CS.arg_size());
3238 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3239 i != e; ++i) {
3240 SDOperand ArgNode = getValue(*i);
3241 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003242
Duncan Sands6f74b482007-12-19 09:48:52 +00003243 unsigned attrInd = i - CS.arg_begin() + 1;
3244 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3245 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3246 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3247 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3248 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3249 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003250 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003251 Args.push_back(Entry);
3252 }
3253
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003254 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003255 // Insert a label before the invoke call to mark the try range. This can be
3256 // used to detect deletion of the invoke via the MachineModuleInfo.
3257 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003258 // Both PendingLoads and PendingExports must be flushed here;
3259 // this call might not return.
3260 (void)getRoot();
3261 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003262 DAG.getConstant(BeginLabel, MVT::i32),
3263 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003264 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003265
Jim Laskey735b6f82007-02-22 15:38:06 +00003266 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003267 TLI.LowerCallTo(getRoot(), CS.getType(),
3268 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003269 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003270 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003271 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003272 if (CS.getType() != Type::VoidTy)
3273 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003274 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003275
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003276 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003277 // Insert a label at the end of the invoke call to mark the try range. This
3278 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3279 EndLabel = MMI->NextLabelID();
3280 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003281 DAG.getConstant(EndLabel, MVT::i32),
3282 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003283
Duncan Sands6f74b482007-12-19 09:48:52 +00003284 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003285 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3286 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003287}
3288
3289
Chris Lattner1c08c712005-01-07 07:47:53 +00003290void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003291 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003292 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003293 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003294 if (unsigned IID = F->getIntrinsicID()) {
3295 RenameFn = visitIntrinsicCall(I, IID);
3296 if (!RenameFn)
3297 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003298 }
3299 }
3300
3301 // Check for well-known libc/libm calls. If the function is internal, it
3302 // can't be a library call.
3303 unsigned NameLen = F->getNameLen();
3304 if (!F->hasInternalLinkage() && NameLen) {
3305 const char *NameStr = F->getNameStart();
3306 if (NameStr[0] == 'c' &&
3307 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3308 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3309 if (I.getNumOperands() == 3 && // Basic sanity checks.
3310 I.getOperand(1)->getType()->isFloatingPoint() &&
3311 I.getType() == I.getOperand(1)->getType() &&
3312 I.getType() == I.getOperand(2)->getType()) {
3313 SDOperand LHS = getValue(I.getOperand(1));
3314 SDOperand RHS = getValue(I.getOperand(2));
3315 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3316 LHS, RHS));
3317 return;
3318 }
3319 } else if (NameStr[0] == 'f' &&
3320 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003321 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3322 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003323 if (I.getNumOperands() == 2 && // Basic sanity checks.
3324 I.getOperand(1)->getType()->isFloatingPoint() &&
3325 I.getType() == I.getOperand(1)->getType()) {
3326 SDOperand Tmp = getValue(I.getOperand(1));
3327 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3328 return;
3329 }
3330 } else if (NameStr[0] == 's' &&
3331 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003332 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3333 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003334 if (I.getNumOperands() == 2 && // Basic sanity checks.
3335 I.getOperand(1)->getType()->isFloatingPoint() &&
3336 I.getType() == I.getOperand(1)->getType()) {
3337 SDOperand Tmp = getValue(I.getOperand(1));
3338 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3339 return;
3340 }
3341 } else if (NameStr[0] == 'c' &&
3342 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003343 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3344 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003345 if (I.getNumOperands() == 2 && // Basic sanity checks.
3346 I.getOperand(1)->getType()->isFloatingPoint() &&
3347 I.getType() == I.getOperand(1)->getType()) {
3348 SDOperand Tmp = getValue(I.getOperand(1));
3349 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3350 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003351 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003352 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003353 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003354 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003355 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003356 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003357 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003358
Chris Lattner64e14b12005-01-08 22:48:57 +00003359 SDOperand Callee;
3360 if (!RenameFn)
3361 Callee = getValue(I.getOperand(0));
3362 else
3363 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003364
Duncan Sands6f74b482007-12-19 09:48:52 +00003365 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003366}
3367
Jim Laskey735b6f82007-02-22 15:38:06 +00003368
Dan Gohmanef5d1942008-03-11 21:11:25 +00003369void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003370 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003371 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3372 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003373 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003374 }
Chris Lattner6833b062008-04-28 07:16:35 +00003375
3376 // To add support for individual return values with aggregate types,
3377 // we'd need a way to take a getresult index and determine which
3378 // values of the Call SDNode are associated with it.
3379 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3380 "Individual return values must not be aggregates!");
3381
3382 SDOperand Call = getValue(I.getOperand(0));
3383 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003384}
3385
3386
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003387/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3388/// this value and returns the result as a ValueVT value. This uses
3389/// Chain/Flag as the input and updates them for the output Chain/Flag.
3390/// If the Flag pointer is NULL, no flag is used.
3391SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003392 SDOperand &Chain,
3393 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003394 // Assemble the legal parts into the final values.
3395 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003396 SmallVector<SDOperand, 8> Parts;
3397 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003398 // Copy the legal parts from the registers.
3399 MVT::ValueType ValueVT = ValueVTs[Value];
3400 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3401 MVT::ValueType RegisterVT = RegVTs[Value];
3402
Chris Lattner6833b062008-04-28 07:16:35 +00003403 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003404 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003405 SDOperand P;
3406 if (Flag == 0)
3407 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3408 else {
3409 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003410 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003411 }
3412 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003413 Parts[Part+i] = P;
3414 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003415
Dan Gohman23ce5022008-04-25 18:27:55 +00003416 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3417 ValueVT);
3418 Part += NumRegs;
3419 }
Chris Lattner6833b062008-04-28 07:16:35 +00003420
3421 if (ValueVTs.size() == 1)
3422 return Values[0];
3423
Dan Gohman23ce5022008-04-25 18:27:55 +00003424 return DAG.getNode(ISD::MERGE_VALUES,
3425 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3426 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003427}
3428
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003429/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3430/// specified value into the registers specified by this object. This uses
3431/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003432/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003433void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003434 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003435 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003436 unsigned NumRegs = Regs.size();
3437 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003438 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003439 MVT::ValueType ValueVT = ValueVTs[Value];
3440 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3441 MVT::ValueType RegisterVT = RegVTs[Value];
3442
3443 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3444 &Parts[Part], NumParts, RegisterVT);
3445 Part += NumParts;
3446 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003447
3448 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003449 SmallVector<SDOperand, 8> Chains(NumRegs);
3450 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003451 SDOperand Part;
3452 if (Flag == 0)
3453 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3454 else {
3455 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003456 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003457 }
3458 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003459 }
Chris Lattner6833b062008-04-28 07:16:35 +00003460
3461 if (NumRegs == 1)
3462 Chain = Chains[0];
3463 else
3464 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003465}
Chris Lattner864635a2006-02-22 22:37:12 +00003466
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003467/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3468/// operand list. This adds the code marker and includes the number of
3469/// values added into it.
3470void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003471 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003472 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3473 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003474 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3475 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003476 MVT::ValueType RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003477 for (unsigned i = 0; i != NumRegs; ++i)
3478 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003479 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003480}
Chris Lattner864635a2006-02-22 22:37:12 +00003481
3482/// isAllocatableRegister - If the specified register is safe to allocate,
3483/// i.e. it isn't a stack pointer or some other special register, return the
3484/// register class for the register. Otherwise, return null.
3485static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003486isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003487 const TargetLowering &TLI,
3488 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003489 MVT::ValueType FoundVT = MVT::Other;
3490 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003491 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3492 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003493 MVT::ValueType ThisVT = MVT::Other;
3494
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003495 const TargetRegisterClass *RC = *RCI;
3496 // If none of the the value types for this register class are valid, we
3497 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003498 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3499 I != E; ++I) {
3500 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003501 // If we have already found this register in a different register class,
3502 // choose the one with the largest VT specified. For example, on
3503 // PowerPC, we favor f64 register classes over f32.
3504 if (FoundVT == MVT::Other ||
3505 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3506 ThisVT = *I;
3507 break;
3508 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003509 }
3510 }
3511
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003512 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003513
Chris Lattner864635a2006-02-22 22:37:12 +00003514 // NOTE: This isn't ideal. In particular, this might allocate the
3515 // frame pointer in functions that need it (due to them not being taken
3516 // out of allocation, because a variable sized allocation hasn't been seen
3517 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003518 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3519 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003520 if (*I == Reg) {
3521 // We found a matching register class. Keep looking at others in case
3522 // we find one with larger registers that this physreg is also in.
3523 FoundRC = RC;
3524 FoundVT = ThisVT;
3525 break;
3526 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003527 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003528 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003529}
3530
Chris Lattner4e4b5762006-02-01 18:59:47 +00003531
Chris Lattner0c583402007-04-28 20:49:53 +00003532namespace {
3533/// AsmOperandInfo - This contains information for each constraint that we are
3534/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003535struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3536 /// CallOperand - If this is the result output operand or a clobber
3537 /// this is null, otherwise it is the incoming operand to the CallInst.
3538 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003539 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003540
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003541 /// AssignedRegs - If this is a register or register class operand, this
3542 /// contains the set of register corresponding to the operand.
3543 RegsForValue AssignedRegs;
3544
Dan Gohman23ce5022008-04-25 18:27:55 +00003545 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003546 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003547 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003548
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003549 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3550 /// busy in OutputRegs/InputRegs.
3551 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3552 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003553 std::set<unsigned> &InputRegs,
3554 const TargetRegisterInfo &TRI) const {
3555 if (isOutReg) {
3556 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3557 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3558 }
3559 if (isInReg) {
3560 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3561 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3562 }
3563 }
3564
3565private:
3566 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3567 /// specified set.
3568 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3569 const TargetRegisterInfo &TRI) {
3570 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3571 Regs.insert(Reg);
3572 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3573 for (; *Aliases; ++Aliases)
3574 Regs.insert(*Aliases);
3575 }
Chris Lattner0c583402007-04-28 20:49:53 +00003576};
3577} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003578
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003579
Chris Lattner0fe71e92008-02-21 19:43:13 +00003580/// GetRegistersForValue - Assign registers (virtual or physical) for the
3581/// specified operand. We prefer to assign virtual registers, to allow the
3582/// register allocator handle the assignment process. However, if the asm uses
3583/// features that we can't model on machineinstrs, we have SDISel do the
3584/// allocation. This produces generally horrible, but correct, code.
3585///
3586/// OpInfo describes the operand.
3587/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3588/// or any explicitly clobbered registers.
3589/// Input and OutputRegs are the set of already allocated physical registers.
3590///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003591void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003592GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003593 std::set<unsigned> &OutputRegs,
3594 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003595 // Compute whether this value requires an input register, an output register,
3596 // or both.
3597 bool isOutReg = false;
3598 bool isInReg = false;
3599 switch (OpInfo.Type) {
3600 case InlineAsm::isOutput:
3601 isOutReg = true;
3602
3603 // If this is an early-clobber output, or if there is an input
3604 // constraint that matches this, we need to reserve the input register
3605 // so no other inputs allocate to it.
3606 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3607 break;
3608 case InlineAsm::isInput:
3609 isInReg = true;
3610 isOutReg = false;
3611 break;
3612 case InlineAsm::isClobber:
3613 isOutReg = true;
3614 isInReg = true;
3615 break;
3616 }
3617
3618
3619 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003620 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003621
3622 // If this is a constraint for a single physreg, or a constraint for a
3623 // register class, find it.
3624 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3625 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3626 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003627
3628 unsigned NumRegs = 1;
3629 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003630 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003631 MVT::ValueType RegVT;
3632 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3633
Chris Lattnerbf996f12007-04-30 17:29:31 +00003634
3635 // If this is a constraint for a specific physical register, like {r17},
3636 // assign it now.
3637 if (PhysReg.first) {
3638 if (OpInfo.ConstraintVT == MVT::Other)
3639 ValueVT = *PhysReg.second->vt_begin();
3640
3641 // Get the actual register value type. This is important, because the user
3642 // may have asked for (e.g.) the AX register in i32 type. We need to
3643 // remember that AX is actually i16 to get the right extension.
3644 RegVT = *PhysReg.second->vt_begin();
3645
3646 // This is a explicit reference to a physical register.
3647 Regs.push_back(PhysReg.first);
3648
3649 // If this is an expanded reference, add the rest of the regs to Regs.
3650 if (NumRegs != 1) {
3651 TargetRegisterClass::iterator I = PhysReg.second->begin();
3652 TargetRegisterClass::iterator E = PhysReg.second->end();
3653 for (; *I != PhysReg.first; ++I)
3654 assert(I != E && "Didn't find reg!");
3655
3656 // Already added the first reg.
3657 --NumRegs; ++I;
3658 for (; NumRegs; --NumRegs, ++I) {
3659 assert(I != E && "Ran out of registers to allocate!");
3660 Regs.push_back(*I);
3661 }
3662 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003663 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003664 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3665 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003666 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003667 }
3668
3669 // Otherwise, if this was a reference to an LLVM register class, create vregs
3670 // for this reference.
3671 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003672 const TargetRegisterClass *RC = PhysReg.second;
3673 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003674 // If this is an early clobber or tied register, our regalloc doesn't know
3675 // how to maintain the constraint. If it isn't, go ahead and create vreg
3676 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003677 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3678 // If there is some other early clobber and this is an input register,
3679 // then we are forced to pre-allocate the input reg so it doesn't
3680 // conflict with the earlyclobber.
3681 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003682 RegVT = *PhysReg.second->vt_begin();
3683
3684 if (OpInfo.ConstraintVT == MVT::Other)
3685 ValueVT = RegVT;
3686
3687 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003688 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003689 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003690 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003691
Dan Gohman23ce5022008-04-25 18:27:55 +00003692 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003693 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003694 }
3695
3696 // Otherwise, we can't allocate it. Let the code below figure out how to
3697 // maintain these constraints.
3698 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3699
3700 } else {
3701 // This is a reference to a register class that doesn't directly correspond
3702 // to an LLVM register class. Allocate NumRegs consecutive, available,
3703 // registers from the class.
3704 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3705 OpInfo.ConstraintVT);
3706 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003707
Dan Gohman6f0d0242008-02-10 18:45:23 +00003708 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003709 unsigned NumAllocated = 0;
3710 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3711 unsigned Reg = RegClassRegs[i];
3712 // See if this register is available.
3713 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3714 (isInReg && InputRegs.count(Reg))) { // Already used.
3715 // Make sure we find consecutive registers.
3716 NumAllocated = 0;
3717 continue;
3718 }
3719
3720 // Check to see if this register is allocatable (i.e. don't give out the
3721 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003722 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003723 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003724 if (!RC) { // Couldn't allocate this register.
3725 // Reset NumAllocated to make sure we return consecutive registers.
3726 NumAllocated = 0;
3727 continue;
3728 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003729 }
3730
3731 // Okay, this register is good, we can use it.
3732 ++NumAllocated;
3733
3734 // If we allocated enough consecutive registers, succeed.
3735 if (NumAllocated == NumRegs) {
3736 unsigned RegStart = (i-NumAllocated)+1;
3737 unsigned RegEnd = i+1;
3738 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003739 for (unsigned i = RegStart; i != RegEnd; ++i)
3740 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003741
Dan Gohman23ce5022008-04-25 18:27:55 +00003742 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003743 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003744 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003745 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003746 }
3747 }
3748
3749 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003750 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003751}
3752
3753
Chris Lattnerce7518c2006-01-26 22:24:51 +00003754/// visitInlineAsm - Handle a call to an InlineAsm object.
3755///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003756void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3757 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003758
Chris Lattner0c583402007-04-28 20:49:53 +00003759 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003760 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003761
3762 SDOperand Chain = getRoot();
3763 SDOperand Flag;
3764
Chris Lattner4e4b5762006-02-01 18:59:47 +00003765 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003766
Chris Lattner0c583402007-04-28 20:49:53 +00003767 // Do a prepass over the constraints, canonicalizing them, and building up the
3768 // ConstraintOperands list.
3769 std::vector<InlineAsm::ConstraintInfo>
3770 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003771
3772 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3773 // constraint. If so, we can't let the register allocator allocate any input
3774 // registers, because it will not know to avoid the earlyclobbered output reg.
3775 bool SawEarlyClobber = false;
3776
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003777 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003778 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003779 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003780 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3781 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003782
Chris Lattner0c583402007-04-28 20:49:53 +00003783 MVT::ValueType OpVT = MVT::Other;
3784
3785 // Compute the value type for each operand.
3786 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003787 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003788 // Indirect outputs just consume an argument.
3789 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003790 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003791 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003792 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003793 // The return value of the call is this value. As such, there is no
3794 // corresponding argument.
3795 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3796 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3797 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3798 } else {
3799 assert(ResNo == 0 && "Asm only has one result!");
3800 OpVT = TLI.getValueType(CS.getType());
3801 }
3802 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003803 break;
3804 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003805 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003806 break;
3807 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003808 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003809 break;
3810 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003811
Chris Lattner0c583402007-04-28 20:49:53 +00003812 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003813 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003814 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003815 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3816 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003817 else {
3818 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3819 const Type *OpTy = OpInfo.CallOperandVal->getType();
3820 // If this is an indirect operand, the operand is a pointer to the
3821 // accessed type.
3822 if (OpInfo.isIndirect)
3823 OpTy = cast<PointerType>(OpTy)->getElementType();
3824
3825 // If OpTy is not a first-class value, it may be a struct/union that we
3826 // can tile with integers.
3827 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3828 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3829 switch (BitSize) {
3830 default: break;
3831 case 1:
3832 case 8:
3833 case 16:
3834 case 32:
3835 case 64:
3836 OpTy = IntegerType::get(BitSize);
3837 break;
3838 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003839 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003840
3841 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003842 }
3843 }
3844
3845 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003846
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003847 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003848 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003849
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003850 // Keep track of whether we see an earlyclobber.
3851 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003852
Chris Lattner0fe71e92008-02-21 19:43:13 +00003853 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003854 if (!SawEarlyClobber &&
3855 OpInfo.Type == InlineAsm::isClobber &&
3856 OpInfo.ConstraintType == TargetLowering::C_Register) {
3857 // Note that we want to ignore things that we don't trick here, like
3858 // dirflag, fpsr, flags, etc.
3859 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3860 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3861 OpInfo.ConstraintVT);
3862 if (PhysReg.first || PhysReg.second) {
3863 // This is a register we know of.
3864 SawEarlyClobber = true;
3865 }
3866 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003867
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003868 // If this is a memory input, and if the operand is not indirect, do what we
3869 // need to to provide an address for the memory input.
3870 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3871 !OpInfo.isIndirect) {
3872 assert(OpInfo.Type == InlineAsm::isInput &&
3873 "Can only indirectify direct input operands!");
3874
3875 // Memory operands really want the address of the value. If we don't have
3876 // an indirect input, put it in the constpool if we can, otherwise spill
3877 // it to a stack slot.
3878
3879 // If the operand is a float, integer, or vector constant, spill to a
3880 // constant pool entry to get its address.
3881 Value *OpVal = OpInfo.CallOperandVal;
3882 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3883 isa<ConstantVector>(OpVal)) {
3884 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3885 TLI.getPointerTy());
3886 } else {
3887 // Otherwise, create a stack slot and emit a store to it before the
3888 // asm.
3889 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003890 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003891 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3892 MachineFunction &MF = DAG.getMachineFunction();
3893 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3894 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3895 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3896 OpInfo.CallOperand = StackSlot;
3897 }
3898
3899 // There is no longer a Value* corresponding to this operand.
3900 OpInfo.CallOperandVal = 0;
3901 // It is now an indirect operand.
3902 OpInfo.isIndirect = true;
3903 }
3904
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003905 // If this constraint is for a specific register, allocate it before
3906 // anything else.
3907 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3908 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003909 }
Chris Lattner0c583402007-04-28 20:49:53 +00003910 ConstraintInfos.clear();
3911
3912
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003913 // Second pass - Loop over all of the operands, assigning virtual or physregs
3914 // to registerclass operands.
3915 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003916 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003917
3918 // C_Register operands have already been allocated, Other/Memory don't need
3919 // to be.
3920 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3921 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3922 }
3923
Chris Lattner0c583402007-04-28 20:49:53 +00003924 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3925 std::vector<SDOperand> AsmNodeOperands;
3926 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3927 AsmNodeOperands.push_back(
3928 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3929
Chris Lattner2cc2f662006-02-01 01:28:23 +00003930
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003931 // Loop over all of the inputs, copying the operand values into the
3932 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003933 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003934
Chris Lattner0c583402007-04-28 20:49:53 +00003935 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3936 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3937
3938 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003939 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003940
Chris Lattner0c583402007-04-28 20:49:53 +00003941 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003942 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003943 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3944 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003945 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003946 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003947
Chris Lattner22873462006-02-27 23:45:39 +00003948 // Add information to the INLINEASM node to know about this output.
3949 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003950 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3951 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003952 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003953 break;
3954 }
3955
Chris Lattner2a600be2007-04-28 21:01:43 +00003956 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003957
Chris Lattner864635a2006-02-22 22:37:12 +00003958 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003959 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003960 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003961 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003962 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003963 exit(1);
3964 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003965
Chris Lattner0c583402007-04-28 20:49:53 +00003966 if (!OpInfo.isIndirect) {
3967 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003968 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003969 "Cannot have multiple output constraints yet!");
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003970 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003971 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003972 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003973 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003974 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003975 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003976
3977 // Add information to the INLINEASM node to know that this register is
3978 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003979 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3980 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003981 break;
3982 }
3983 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003984 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003985
Chris Lattner0c583402007-04-28 20:49:53 +00003986 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003987 // If this is required to match an output register we have already set,
3988 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003989 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003990
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003991 // Scan until we find the definition we already emitted of this operand.
3992 // When we find it, create a RegsForValue operand.
3993 unsigned CurOp = 2; // The first operand.
3994 for (; OperandNo; --OperandNo) {
3995 // Advance to the next operand.
3996 unsigned NumOps =
3997 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003998 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3999 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004000 "Skipped past definitions?");
4001 CurOp += (NumOps>>3)+1;
4002 }
4003
4004 unsigned NumOps =
4005 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004006 if ((NumOps & 7) == 2 /*REGDEF*/) {
4007 // Add NumOps>>3 registers to MatchedRegs.
4008 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004009 MatchedRegs.TLI = &TLI;
4010 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
4011 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004012 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4013 unsigned Reg =
4014 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4015 MatchedRegs.Regs.push_back(Reg);
4016 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004017
Chris Lattner527fae12007-02-01 01:21:12 +00004018 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004019 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004020 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4021 break;
4022 } else {
4023 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004024 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4025 // Add information to the INLINEASM node to know about this input.
4026 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4027 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4028 TLI.getPointerTy()));
4029 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4030 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004031 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004032 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004033
Chris Lattner2a600be2007-04-28 21:01:43 +00004034 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004035 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004036 "Don't know how to handle indirect other inputs yet!");
4037
Chris Lattner48884cd2007-08-25 00:47:38 +00004038 std::vector<SDOperand> Ops;
4039 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4040 Ops, DAG);
4041 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004042 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004043 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004044 exit(1);
4045 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004046
4047 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004048 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004049 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4050 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004051 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004052 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004053 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004054 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004055 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4056 "Memory operands expect pointer values");
4057
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004058 // Add information to the INLINEASM node to know about this input.
4059 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004060 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4061 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004062 AsmNodeOperands.push_back(InOperandVal);
4063 break;
4064 }
4065
Chris Lattner2a600be2007-04-28 21:01:43 +00004066 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4067 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4068 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004069 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004070 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004071
4072 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004073 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4074 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004075
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004076 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004077
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004078 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4079 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004080 break;
4081 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004082 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004083 // Add the clobbered value to the operand list, so that the register
4084 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004085 if (!OpInfo.AssignedRegs.Regs.empty())
4086 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4087 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004088 break;
4089 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004090 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004091 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004092
4093 // Finish up input operands.
4094 AsmNodeOperands[0] = Chain;
4095 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4096
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004097 Chain = DAG.getNode(ISD::INLINEASM,
4098 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004099 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004100 Flag = Chain.getValue(1);
4101
Chris Lattner6656dd12006-01-31 02:03:41 +00004102 // If this asm returns a register value, copy the result from that register
4103 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004104 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004105 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00004106
4107 // If the result of the inline asm is a vector, it may have the wrong
4108 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004109 // bit_convert.
4110 if (MVT::isVector(Val.getValueType())) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004111 const VectorType *VTy = cast<VectorType>(CS.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004112 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00004113
Dan Gohman7f321562007-06-25 16:23:39 +00004114 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004115 }
4116
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004117 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004118 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004119
Chris Lattner6656dd12006-01-31 02:03:41 +00004120 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4121
4122 // Process indirect outputs, first output all of the flagged copies out of
4123 // physregs.
4124 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004125 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004126 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004127 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004128 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004129 }
4130
4131 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004132 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004133 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004134 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004135 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004136 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004137 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004138 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4139 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004140 DAG.setRoot(Chain);
4141}
4142
4143
Chris Lattner1c08c712005-01-07 07:47:53 +00004144void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4145 SDOperand Src = getValue(I.getOperand(0));
4146
4147 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004148
4149 if (IntPtr < Src.getValueType())
4150 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4151 else if (IntPtr > Src.getValueType())
4152 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004153
4154 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004155 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004156 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004157 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004158
Reid Spencer47857812006-12-31 05:55:36 +00004159 TargetLowering::ArgListTy Args;
4160 TargetLowering::ArgListEntry Entry;
4161 Entry.Node = Src;
4162 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004163 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004164
4165 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004166 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4167 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004168 setValue(&I, Result.first); // Pointers always fit in registers
4169 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004170}
4171
4172void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004173 TargetLowering::ArgListTy Args;
4174 TargetLowering::ArgListEntry Entry;
4175 Entry.Node = getValue(I.getOperand(0));
4176 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004177 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004178 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004179 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004180 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4181 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004182 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4183 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004184}
4185
Evan Chengff9b3732008-01-30 18:18:23 +00004186// EmitInstrWithCustomInserter - This method should be implemented by targets
4187// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004188// instructions are special in various ways, which require special support to
4189// insert. The specified MachineInstr is created but not inserted into any
4190// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004191MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004192 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004193 cerr << "If a target marks an instruction with "
4194 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004195 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004196 abort();
4197 return 0;
4198}
4199
Chris Lattner39ae3622005-01-09 00:00:49 +00004200void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004201 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4202 getValue(I.getOperand(1)),
4203 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004204}
4205
4206void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004207 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4208 getValue(I.getOperand(0)),
4209 DAG.getSrcValue(I.getOperand(0)));
4210 setValue(&I, V);
4211 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004212}
4213
4214void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004215 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4216 getValue(I.getOperand(1)),
4217 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004218}
4219
4220void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004221 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4222 getValue(I.getOperand(1)),
4223 getValue(I.getOperand(2)),
4224 DAG.getSrcValue(I.getOperand(1)),
4225 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004226}
4227
Chris Lattnerfdfded52006-04-12 16:20:43 +00004228/// TargetLowering::LowerArguments - This is the default LowerArguments
4229/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004230/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4231/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004232std::vector<SDOperand>
4233TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4234 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4235 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004236 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004237 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4238 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4239
4240 // Add one result value for each formal argument.
4241 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004242 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004243 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4244 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004245 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004246 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004247 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004248 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004249
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004250 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004251 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004252 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004253 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004254 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004255 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004256 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004257 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004258 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004259 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004260 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004261 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004262 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004263 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004264 // For ByVal, alignment should be passed from FE. BE will guess if
4265 // this info is not there but there are cases it cannot get right.
4266 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004267 FrameAlign = F.getParamAlignment(j);
4268 Flags.setByValAlign(FrameAlign);
4269 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004270 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004271 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004272 Flags.setNest();
4273 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004274
4275 MVT::ValueType RegisterVT = getRegisterType(VT);
4276 unsigned NumRegs = getNumRegisters(VT);
4277 for (unsigned i = 0; i != NumRegs; ++i) {
4278 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004279 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004280 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004281 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004282 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004283 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004284 MyFlags.setOrigAlign(1);
4285 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004286 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004287 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004288
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004289 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004290
4291 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004292 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004293 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004294 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004295
4296 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4297 // allows exposing the loads that may be part of the argument access to the
4298 // first DAGCombiner pass.
4299 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4300
4301 // The number of results should match up, except that the lowered one may have
4302 // an extra flag result.
4303 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4304 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4305 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4306 && "Lowering produced unexpected number of results!");
4307 Result = TmpRes.Val;
4308
Dan Gohman27a70be2007-07-02 16:18:06 +00004309 unsigned NumArgRegs = Result->getNumValues() - 1;
4310 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004311
4312 // Set up the return result vector.
4313 Ops.clear();
4314 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004315 unsigned Idx = 1;
4316 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4317 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004318 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004319 MVT::ValueType PartVT = getRegisterType(VT);
4320
4321 unsigned NumParts = getNumRegisters(VT);
4322 SmallVector<SDOperand, 4> Parts(NumParts);
4323 for (unsigned j = 0; j != NumParts; ++j)
4324 Parts[j] = SDOperand(Result, i++);
4325
4326 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4327 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4328 AssertOp = ISD::AssertSext;
4329 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4330 AssertOp = ISD::AssertZext;
4331
4332 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004333 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004334 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004335 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004336 return Ops;
4337}
4338
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004339
4340/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4341/// implementation, which just inserts an ISD::CALL node, which is later custom
4342/// lowered by the target to something concrete. FIXME: When all targets are
4343/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4344std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004345TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4346 bool RetSExt, bool RetZExt, bool isVarArg,
4347 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004348 SDOperand Callee,
4349 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004350 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004351 Ops.push_back(Chain); // Op#0 - Chain
4352 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4353 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4354 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4355 Ops.push_back(Callee);
4356
4357 // Handle all of the outgoing arguments.
4358 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004359 MVT::ValueType VT = getValueType(Args[i].Ty);
4360 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004361 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004362 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004363 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004364
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004365 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004366 Flags.setZExt();
4367 if (Args[i].isSExt)
4368 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004369 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004370 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004371 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004372 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004373 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004374 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004375 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004376 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004377 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004378 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004379 // For ByVal, alignment should come from FE. BE will guess if this
4380 // info is not there but there are cases it cannot get right.
4381 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004382 FrameAlign = Args[i].Alignment;
4383 Flags.setByValAlign(FrameAlign);
4384 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004385 }
Duncan Sands36397f52007-07-27 12:58:54 +00004386 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004387 Flags.setNest();
4388 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004389
Duncan Sandsb988bac2008-02-11 20:58:28 +00004390 MVT::ValueType PartVT = getRegisterType(VT);
4391 unsigned NumParts = getNumRegisters(VT);
4392 SmallVector<SDOperand, 4> Parts(NumParts);
4393 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4394
4395 if (Args[i].isSExt)
4396 ExtendKind = ISD::SIGN_EXTEND;
4397 else if (Args[i].isZExt)
4398 ExtendKind = ISD::ZERO_EXTEND;
4399
4400 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4401
4402 for (unsigned i = 0; i != NumParts; ++i) {
4403 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004404 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004405 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004406 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004407 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004408 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004409
4410 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004411 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004412 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004413 }
4414
Dan Gohmanef5d1942008-03-11 21:11:25 +00004415 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004416 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004417 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4418 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004419 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004420
Dan Gohman23ce5022008-04-25 18:27:55 +00004421 // Then we translate that to a list of legal types.
4422 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4423 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004424 MVT::ValueType RegisterVT = getRegisterType(VT);
4425 unsigned NumRegs = getNumRegisters(VT);
4426 for (unsigned i = 0; i != NumRegs; ++i)
4427 LoweredRetTys.push_back(RegisterVT);
4428 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004429
Dan Gohmanef5d1942008-03-11 21:11:25 +00004430 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004431
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004432 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004433 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004434 DAG.getVTList(&LoweredRetTys[0],
4435 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004436 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004437 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004438
4439 // Gather up the call result into a single value.
4440 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004441 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4442
4443 if (RetSExt)
4444 AssertOp = ISD::AssertSext;
4445 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004446 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004447
Dan Gohmanef5d1942008-03-11 21:11:25 +00004448 SmallVector<SDOperand, 4> ReturnValues;
4449 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004450 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4451 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004452 MVT::ValueType RegisterVT = getRegisterType(VT);
4453 unsigned NumRegs = getNumRegisters(VT);
4454 unsigned RegNoEnd = NumRegs + RegNo;
4455 SmallVector<SDOperand, 4> Results;
4456 for (; RegNo != RegNoEnd; ++RegNo)
4457 Results.push_back(Res.getValue(RegNo));
4458 SDOperand ReturnValue =
4459 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4460 AssertOp);
4461 ReturnValues.push_back(ReturnValue);
4462 }
4463 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4464 DAG.getNode(ISD::MERGE_VALUES,
4465 DAG.getVTList(&RetTys[0], RetTys.size()),
4466 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004467 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004468
4469 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004470}
4471
Chris Lattner50381b62005-05-14 05:50:48 +00004472SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004473 assert(0 && "LowerOperation not implemented for this target!");
4474 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004475 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004476}
4477
Nate Begeman0aed7842006-01-28 03:14:31 +00004478SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4479 SelectionDAG &DAG) {
4480 assert(0 && "CustomPromoteOperation not implemented for this target!");
4481 abort();
4482 return SDOperand();
4483}
4484
Chris Lattner7041ee32005-01-11 05:56:49 +00004485//===----------------------------------------------------------------------===//
4486// SelectionDAGISel code
4487//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004488
4489unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004490 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004491}
4492
Chris Lattner495a0b52005-08-17 06:37:43 +00004493void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004494 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004495 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004496 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004497}
Chris Lattner1c08c712005-01-07 07:47:53 +00004498
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004499
Chris Lattnerbad7f482006-10-28 19:22:10 +00004500
Chris Lattner1c08c712005-01-07 07:47:53 +00004501bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004502 // Get alias analysis for load/store combining.
4503 AA = &getAnalysis<AliasAnalysis>();
4504
Chris Lattner1c08c712005-01-07 07:47:53 +00004505 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004506 if (MF.getFunction()->hasCollector())
4507 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4508 else
4509 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004510 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004511 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004512
4513 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4514
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004515 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4516 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4517 // Mark landing pad.
4518 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004519
4520 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004521 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004522
Evan Chengad2070c2007-02-10 02:43:39 +00004523 // Add function live-ins to entry block live-in set.
4524 BasicBlock *EntryBB = &Fn.getEntryBlock();
4525 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004526 if (!RegInfo->livein_empty())
4527 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4528 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004529 BB->addLiveIn(I->first);
4530
Duncan Sandsf4070822007-06-15 19:04:19 +00004531#ifndef NDEBUG
4532 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4533 "Not all catch info was assigned to a landing pad!");
4534#endif
4535
Chris Lattner1c08c712005-01-07 07:47:53 +00004536 return true;
4537}
4538
Chris Lattner6833b062008-04-28 07:16:35 +00004539void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004540 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004541 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004542 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004543 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004544 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004545
Dan Gohman23ce5022008-04-25 18:27:55 +00004546 RegsForValue RFV(TLI, Reg, V->getType());
4547 SDOperand Chain = DAG.getEntryNode();
4548 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4549 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004550}
4551
Chris Lattner068a81e2005-01-17 17:15:02 +00004552void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004553LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004554 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004555 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004556 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004557 SDOperand OldRoot = SDL.DAG.getRoot();
4558 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004559
Chris Lattnerbf209482005-10-30 19:42:35 +00004560 unsigned a = 0;
4561 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4562 AI != E; ++AI, ++a)
4563 if (!AI->use_empty()) {
4564 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004565
Chris Lattnerbf209482005-10-30 19:42:35 +00004566 // If this argument is live outside of the entry block, insert a copy from
4567 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004568 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4569 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004570 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004571 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004572 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004573
Chris Lattnerbf209482005-10-30 19:42:35 +00004574 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004575 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004576 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004577}
4578
Duncan Sandsf4070822007-06-15 19:04:19 +00004579static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4580 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004581 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004582 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004583 // Apply the catch info to DestBB.
4584 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4585#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004586 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4587 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004588#endif
4589 }
4590}
4591
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004592/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004593/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004594static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4595 TargetLowering& TLI) {
4596 SDNode * Ret = NULL;
4597 SDOperand Terminator = DAG.getRoot();
4598
4599 // Find RET node.
4600 if (Terminator.getOpcode() == ISD::RET) {
4601 Ret = Terminator.Val;
4602 }
4603
4604 // Fix tail call attribute of CALL nodes.
4605 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4606 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4607 if (BI->getOpcode() == ISD::CALL) {
4608 SDOperand OpRet(Ret, 0);
4609 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4610 bool isMarkedTailCall =
4611 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4612 // If CALL node has tail call attribute set to true and the call is not
4613 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004614 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004615 // must correctly identify tail call optimizable calls.
4616 if (isMarkedTailCall &&
4617 (Ret==NULL ||
4618 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4619 SmallVector<SDOperand, 32> Ops;
4620 unsigned idx=0;
4621 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4622 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4623 if (idx!=3)
4624 Ops.push_back(*I);
4625 else
4626 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4627 }
4628 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4629 }
4630 }
4631 }
4632}
4633
Chris Lattner1c08c712005-01-07 07:47:53 +00004634void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4635 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004636 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004637 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004638
Chris Lattnerbf209482005-10-30 19:42:35 +00004639 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004640 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004641 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004642
4643 BB = FuncInfo.MBBMap[LLVMBB];
4644 SDL.setCurrentBasicBlock(BB);
4645
Duncan Sandsf4070822007-06-15 19:04:19 +00004646 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004647
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004648 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004649 // Add a label to mark the beginning of the landing pad. Deletion of the
4650 // landing pad can thus be detected via the MachineModuleInfo.
4651 unsigned LabelID = MMI->addLandingPad(BB);
4652 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004653 DAG.getConstant(LabelID, MVT::i32),
4654 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004655
Evan Chenge47c3332007-06-27 18:45:32 +00004656 // Mark exception register as live in.
4657 unsigned Reg = TLI.getExceptionAddressRegister();
4658 if (Reg) BB->addLiveIn(Reg);
4659
4660 // Mark exception selector register as live in.
4661 Reg = TLI.getExceptionSelectorRegister();
4662 if (Reg) BB->addLiveIn(Reg);
4663
Duncan Sandsf4070822007-06-15 19:04:19 +00004664 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4665 // function and list of typeids logically belong to the invoke (or, if you
4666 // like, the basic block containing the invoke), and need to be associated
4667 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004668 // information is provided by an intrinsic (eh.selector) that can be moved
4669 // to unexpected places by the optimizers: if the unwind edge is critical,
4670 // then breaking it can result in the intrinsics being in the successor of
4671 // the landing pad, not the landing pad itself. This results in exceptions
4672 // not being caught because no typeids are associated with the invoke.
4673 // This may not be the only way things can go wrong, but it is the only way
4674 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004675 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4676
4677 if (Br && Br->isUnconditional()) { // Critical edge?
4678 BasicBlock::iterator I, E;
4679 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004680 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004681 break;
4682
4683 if (I == E)
4684 // No catch info found - try to extract some from the successor.
4685 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004686 }
4687 }
4688
Chris Lattner1c08c712005-01-07 07:47:53 +00004689 // Lower all of the non-terminator instructions.
4690 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4691 I != E; ++I)
4692 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004693
Chris Lattner1c08c712005-01-07 07:47:53 +00004694 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004695 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004696 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004697 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004698 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004699 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004700 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004701 }
4702
4703 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4704 // ensure constants are generated when needed. Remember the virtual registers
4705 // that need to be added to the Machine PHI nodes as input. We cannot just
4706 // directly add them, because expansion might result in multiple MBB's for one
4707 // BB. As such, the start of the BB might correspond to a different MBB than
4708 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004709 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004710 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004711
4712 // Emit constants only once even if used by multiple PHI nodes.
4713 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004714
Chris Lattner8c494ab2006-10-27 23:50:33 +00004715 // Vector bool would be better, but vector<bool> is really slow.
4716 std::vector<unsigned char> SuccsHandled;
4717 if (TI->getNumSuccessors())
4718 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4719
Dan Gohman532dc2e2007-07-09 20:59:04 +00004720 // Check successor nodes' PHI nodes that expect a constant to be available
4721 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004722 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4723 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004724 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004725 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004726
Chris Lattner8c494ab2006-10-27 23:50:33 +00004727 // If this terminator has multiple identical successors (common for
4728 // switches), only handle each succ once.
4729 unsigned SuccMBBNo = SuccMBB->getNumber();
4730 if (SuccsHandled[SuccMBBNo]) continue;
4731 SuccsHandled[SuccMBBNo] = true;
4732
4733 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004734 PHINode *PN;
4735
4736 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4737 // nodes and Machine PHI nodes, but the incoming operands have not been
4738 // emitted yet.
4739 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004740 (PN = dyn_cast<PHINode>(I)); ++I) {
4741 // Ignore dead phi's.
4742 if (PN->use_empty()) continue;
4743
4744 unsigned Reg;
4745 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004746
Chris Lattner8c494ab2006-10-27 23:50:33 +00004747 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4748 unsigned &RegOut = ConstantsOut[C];
4749 if (RegOut == 0) {
4750 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004751 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004752 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004753 Reg = RegOut;
4754 } else {
4755 Reg = FuncInfo.ValueMap[PHIOp];
4756 if (Reg == 0) {
4757 assert(isa<AllocaInst>(PHIOp) &&
4758 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4759 "Didn't codegen value into a register!??");
4760 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004761 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004762 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004763 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004764
4765 // Remember that this register needs to added to the machine PHI node as
4766 // the input for this MBB.
4767 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004768 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004769 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004770 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4771 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004772 }
4773 ConstantsOut.clear();
4774
4775 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004776 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004777
Nate Begemanf15485a2006-03-27 01:32:24 +00004778 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004779 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004780 SwitchCases.clear();
4781 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004782 JTCases.clear();
4783 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004784 BitTestCases.clear();
4785 BitTestCases = SDL.BitTestCases;
4786
Chris Lattnera651cf62005-01-17 19:43:36 +00004787 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004788 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004789
4790 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4791 // with correct tailcall attribute so that the target can rely on the tailcall
4792 // attribute indicating whether the call is really eligible for tail call
4793 // optimization.
4794 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004795}
4796
Nate Begemanf15485a2006-03-27 01:32:24 +00004797void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004798 DOUT << "Lowered selection DAG:\n";
4799 DEBUG(DAG.dump());
4800
Chris Lattneraf21d552005-10-10 16:47:10 +00004801 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004802 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004803
Dan Gohman417e11b2007-10-08 15:12:17 +00004804 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004805 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004806
Chris Lattner1c08c712005-01-07 07:47:53 +00004807 // Second step, hack on the DAG until it only uses operations and types that
4808 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004809#if 0 // Enable this some day.
4810 DAG.LegalizeTypes();
4811 // Someday even later, enable a dag combine pass here.
4812#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004813 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004814
Bill Wendling832171c2006-12-07 20:04:42 +00004815 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004816 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004817
Chris Lattneraf21d552005-10-10 16:47:10 +00004818 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004819 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004820
Dan Gohman417e11b2007-10-08 15:12:17 +00004821 DOUT << "Optimized legalized selection DAG:\n";
4822 DEBUG(DAG.dump());
4823
Evan Chenga9c20912006-01-21 02:32:06 +00004824 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004825
Chris Lattnera33ef482005-03-30 01:10:47 +00004826 // Third, instruction select all of the operations to machine code, adding the
4827 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004828 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004829
Bill Wendling832171c2006-12-07 20:04:42 +00004830 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004831 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004832}
Chris Lattner1c08c712005-01-07 07:47:53 +00004833
Nate Begemanf15485a2006-03-27 01:32:24 +00004834void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4835 FunctionLoweringInfo &FuncInfo) {
4836 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4837 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004838 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004839 CurDAG = &DAG;
4840
4841 // First step, lower LLVM code to some DAG. This DAG may use operations and
4842 // types that are not supported by the target.
4843 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4844
4845 // Second step, emit the lowered DAG as machine code.
4846 CodeGenAndEmitDAG(DAG);
4847 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004848
4849 DOUT << "Total amount of phi nodes to update: "
4850 << PHINodesToUpdate.size() << "\n";
4851 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4852 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4853 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004854
Chris Lattnera33ef482005-03-30 01:10:47 +00004855 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004856 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004857 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004858 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4859 MachineInstr *PHI = PHINodesToUpdate[i].first;
4860 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4861 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004862 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4863 false));
4864 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004865 }
4866 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004867 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004868
4869 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4870 // Lower header first, if it wasn't already lowered
4871 if (!BitTestCases[i].Emitted) {
4872 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4873 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004874 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004875 // Set the current basic block to the mbb we wish to insert the code into
4876 BB = BitTestCases[i].Parent;
4877 HSDL.setCurrentBasicBlock(BB);
4878 // Emit the code
4879 HSDL.visitBitTestHeader(BitTestCases[i]);
4880 HSDAG.setRoot(HSDL.getRoot());
4881 CodeGenAndEmitDAG(HSDAG);
4882 }
4883
4884 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4885 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4886 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004887 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004888 // Set the current basic block to the mbb we wish to insert the code into
4889 BB = BitTestCases[i].Cases[j].ThisBB;
4890 BSDL.setCurrentBasicBlock(BB);
4891 // Emit the code
4892 if (j+1 != ej)
4893 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4894 BitTestCases[i].Reg,
4895 BitTestCases[i].Cases[j]);
4896 else
4897 BSDL.visitBitTestCase(BitTestCases[i].Default,
4898 BitTestCases[i].Reg,
4899 BitTestCases[i].Cases[j]);
4900
4901
4902 BSDAG.setRoot(BSDL.getRoot());
4903 CodeGenAndEmitDAG(BSDAG);
4904 }
4905
4906 // Update PHI Nodes
4907 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4908 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4909 MachineBasicBlock *PHIBB = PHI->getParent();
4910 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4911 "This is not a machine PHI node that we are updating!");
4912 // This is "default" BB. We have two jumps to it. From "header" BB and
4913 // from last "case" BB.
4914 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004915 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4916 false));
4917 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4918 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4919 false));
4920 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4921 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004922 }
4923 // One of "cases" BB.
4924 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4925 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4926 if (cBB->succ_end() !=
4927 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004928 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4929 false));
4930 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004931 }
4932 }
4933 }
4934 }
4935
Nate Begeman9453eea2006-04-23 06:26:20 +00004936 // If the JumpTable record is filled in, then we need to emit a jump table.
4937 // Updating the PHI nodes is tricky in this case, since we need to determine
4938 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004939 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4940 // Lower header first, if it wasn't already lowered
4941 if (!JTCases[i].first.Emitted) {
4942 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4943 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004944 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004945 // Set the current basic block to the mbb we wish to insert the code into
4946 BB = JTCases[i].first.HeaderBB;
4947 HSDL.setCurrentBasicBlock(BB);
4948 // Emit the code
4949 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4950 HSDAG.setRoot(HSDL.getRoot());
4951 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004952 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004953
4954 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4955 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004956 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00004957 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004958 BB = JTCases[i].second.MBB;
4959 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004960 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004961 JSDL.visitJumpTable(JTCases[i].second);
4962 JSDAG.setRoot(JSDL.getRoot());
4963 CodeGenAndEmitDAG(JSDAG);
4964
Nate Begeman37efe672006-04-22 18:53:45 +00004965 // Update PHI Nodes
4966 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4967 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4968 MachineBasicBlock *PHIBB = PHI->getParent();
4969 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4970 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004971 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004972 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004973 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4974 false));
4975 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00004976 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004977 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004978 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004979 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4980 false));
4981 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00004982 }
4983 }
Nate Begeman37efe672006-04-22 18:53:45 +00004984 }
4985
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004986 // If the switch block involved a branch to one of the actual successors, we
4987 // need to update PHI nodes in that block.
4988 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4989 MachineInstr *PHI = PHINodesToUpdate[i].first;
4990 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4991 "This is not a machine PHI node that we are updating!");
4992 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004993 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4994 false));
4995 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004996 }
4997 }
4998
Nate Begemanf15485a2006-03-27 01:32:24 +00004999 // If we generated any switch lowering information, build and codegen any
5000 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005001 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005002 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005003 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005004 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005005
Nate Begemanf15485a2006-03-27 01:32:24 +00005006 // Set the current basic block to the mbb we wish to insert the code into
5007 BB = SwitchCases[i].ThisBB;
5008 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005009
Nate Begemanf15485a2006-03-27 01:32:24 +00005010 // Emit the code
5011 SDL.visitSwitchCase(SwitchCases[i]);
5012 SDAG.setRoot(SDL.getRoot());
5013 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005014
5015 // Handle any PHI nodes in successors of this chunk, as if we were coming
5016 // from the original BB before switch expansion. Note that PHI nodes can
5017 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5018 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005019 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005020 for (MachineBasicBlock::iterator Phi = BB->begin();
5021 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5022 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5023 for (unsigned pn = 0; ; ++pn) {
5024 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5025 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005026 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5027 second, false));
5028 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005029 break;
5030 }
5031 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005032 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005033
5034 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005035 if (BB == SwitchCases[i].FalseBB)
5036 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005037
5038 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005039 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005040 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005041 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005042 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005043 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005044}
Evan Chenga9c20912006-01-21 02:32:06 +00005045
Jim Laskey13ec7022006-08-01 14:21:23 +00005046
Evan Chenga9c20912006-01-21 02:32:06 +00005047//===----------------------------------------------------------------------===//
5048/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5049/// target node in the graph.
5050void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5051 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005052
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005053 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005054
5055 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005056 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005057 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005058 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005059
Jim Laskey9ff542f2006-08-01 18:29:48 +00005060 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005061 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005062
5063 if (ViewSUnitDAGs) SL->viewGraph();
5064
Evan Chengcccf1232006-02-04 06:49:00 +00005065 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005066}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005067
Chris Lattner03fc53c2006-03-06 00:22:00 +00005068
Jim Laskey9ff542f2006-08-01 18:29:48 +00005069HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5070 return new HazardRecognizer();
5071}
5072
Chris Lattner75548062006-10-11 03:58:02 +00005073//===----------------------------------------------------------------------===//
5074// Helper functions used by the generated instruction selector.
5075//===----------------------------------------------------------------------===//
5076// Calls to these methods are generated by tblgen.
5077
5078/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5079/// the dag combiner simplified the 255, we still want to match. RHS is the
5080/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5081/// specified in the .td file (e.g. 255).
5082bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005083 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005084 const APInt &ActualMask = RHS->getAPIntValue();
5085 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005086
5087 // If the actual mask exactly matches, success!
5088 if (ActualMask == DesiredMask)
5089 return true;
5090
5091 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005092 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005093 return false;
5094
5095 // Otherwise, the DAG Combiner may have proven that the value coming in is
5096 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005097 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005098 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005099 return true;
5100
5101 // TODO: check to see if missing bits are just not demanded.
5102
5103 // Otherwise, this pattern doesn't match.
5104 return false;
5105}
5106
5107/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5108/// the dag combiner simplified the 255, we still want to match. RHS is the
5109/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5110/// specified in the .td file (e.g. 255).
5111bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005112 int64_t DesiredMaskS) const {
5113 const APInt &ActualMask = RHS->getAPIntValue();
5114 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005115
5116 // If the actual mask exactly matches, success!
5117 if (ActualMask == DesiredMask)
5118 return true;
5119
5120 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005121 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005122 return false;
5123
5124 // Otherwise, the DAG Combiner may have proven that the value coming in is
5125 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005126 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005127
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005128 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005129 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005130
5131 // If all the missing bits in the or are already known to be set, match!
5132 if ((NeededMask & KnownOne) == NeededMask)
5133 return true;
5134
5135 // TODO: check to see if missing bits are just not demanded.
5136
5137 // Otherwise, this pattern doesn't match.
5138 return false;
5139}
5140
Jim Laskey9ff542f2006-08-01 18:29:48 +00005141
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005142/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5143/// by tblgen. Others should not call it.
5144void SelectionDAGISel::
5145SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5146 std::vector<SDOperand> InOps;
5147 std::swap(InOps, Ops);
5148
5149 Ops.push_back(InOps[0]); // input chain.
5150 Ops.push_back(InOps[1]); // input asm string.
5151
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005152 unsigned i = 2, e = InOps.size();
5153 if (InOps[e-1].getValueType() == MVT::Flag)
5154 --e; // Don't process a flag operand if it is here.
5155
5156 while (i != e) {
5157 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5158 if ((Flags & 7) != 4 /*MEM*/) {
5159 // Just skip over this operand, copying the operands verbatim.
5160 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5161 i += (Flags >> 3) + 1;
5162 } else {
5163 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5164 // Otherwise, this is a memory operand. Ask the target to select it.
5165 std::vector<SDOperand> SelOps;
5166 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005167 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005168 exit(1);
5169 }
5170
5171 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005172 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005173 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005174 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005175 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5176 i += 2;
5177 }
5178 }
5179
5180 // Add the flag input back if present.
5181 if (e != InOps.size())
5182 Ops.push_back(InOps.back());
5183}
Devang Patel794fd752007-05-01 21:15:47 +00005184
Devang Patel19974732007-05-03 01:11:54 +00005185char SelectionDAGISel::ID = 0;