blob: 7e8b61465ad42675aebc862418510f5148318890 [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 Lattner864635a2006-02-22 22:37:12 +000092namespace {
Dan Gohman23ce5022008-04-25 18:27:55 +000093 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
94 /// MVT::ValueTypes that represent all the individual underlying
95 /// non-aggregate types that comprise it.
96 static void ComputeValueVTs(const TargetLowering &TLI,
97 const Type *Ty,
98 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
99 // Given a struct type, recursively traverse the elements.
100 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
101 for (StructType::element_iterator EI = STy->element_begin(),
102 EB = STy->element_end();
103 EI != EB; ++EI)
104 ComputeValueVTs(TLI, *EI, ValueVTs);
105 return;
106 }
107 // Given an array type, recursively traverse the elements.
108 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
109 const Type *EltTy = ATy->getElementType();
110 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
111 ComputeValueVTs(TLI, EltTy, ValueVTs);
112 return;
113 }
114 // Base case: we can get an MVT::ValueType for this LLVM IR type.
115 MVT::ValueType VT = TLI.getValueType(Ty);
116 ValueVTs.push_back(VT);
117 }
118
Chris Lattner864635a2006-02-22 22:37:12 +0000119 /// RegsForValue - This struct represents the physical registers that a
120 /// particular value is assigned and the type information about the value.
121 /// This is needed because values can be promoted into larger registers and
122 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +0000123 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000124 /// TLI - The TargetLowering object.
125 const TargetLowering *TLI;
126
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000127 /// Regs - This list holds the register (for legal and promoted values)
Chris Lattner864635a2006-02-22 22:37:12 +0000128 /// or register set (for expanded values) that the value should be assigned
129 /// to.
130 std::vector<unsigned> Regs;
131
Dan Gohman23ce5022008-04-25 18:27:55 +0000132 /// RegVTs - The value types of the registers. This is the same size
133 /// as ValueVTs; every register contributing to a given value must
134 /// have the same type. When Regs contains all virtual registers, the
135 /// contents of RegVTs is redundant with TLI's getRegisterType member
136 /// function, however when Regs contains physical registers, it is
137 /// necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000138 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000139 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000140
Dan Gohman23ce5022008-04-25 18:27:55 +0000141 /// ValueVTs - The value types of the values, which may be promoted
142 /// or synthesized from one or more registers.
143 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman23ce5022008-04-25 18:27:55 +0000145 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000146
Dan Gohman23ce5022008-04-25 18:27:55 +0000147 RegsForValue(const TargetLowering &tli,
148 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
149 : TLI(&tli), Regs(1, Reg), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
150 RegsForValue(const TargetLowering &tli,
151 const std::vector<unsigned> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000152 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 : TLI(&tli), Regs(regs), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
154 RegsForValue(const TargetLowering &tli,
155 const std::vector<unsigned> &regs,
156 const SmallVector<MVT::ValueType, 4> &regvts,
157 const SmallVector<MVT::ValueType, 4> &valuevts)
158 : TLI(&tli), Regs(regs), RegVTs(regvts), ValueVTs(valuevts) {}
159 RegsForValue(const TargetLowering &tli,
160 unsigned Reg, const Type *Ty) : TLI(&tli) {
161 ComputeValueVTs(tli, Ty, ValueVTs);
162
163 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
164 MVT::ValueType ValueVT = ValueVTs[Value];
165 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
166 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
167 for (unsigned i = 0; i != NumRegs; ++i)
168 Regs.push_back(Reg + i);
169 RegVTs.push_back(RegisterVT);
170 Reg += NumRegs;
171 }
Chris Lattner864635a2006-02-22 22:37:12 +0000172 }
173
174 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000175 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000176 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000177 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000178 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000179 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000180
181 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
182 /// specified value into the registers specified by this object. This uses
183 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000184 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000185 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000186 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000187
188 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
189 /// operand list. This adds the code marker and includes the number of
190 /// values added into it.
191 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000192 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000193 };
194}
Evan Cheng4ef10862006-01-23 07:01:07 +0000195
Chris Lattner1c08c712005-01-07 07:47:53 +0000196namespace llvm {
197 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000198 /// createDefaultScheduler - This creates an instruction scheduler appropriate
199 /// for the target.
200 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
201 SelectionDAG *DAG,
202 MachineBasicBlock *BB) {
203 TargetLowering &TLI = IS->getTargetLowering();
204
205 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
206 return createTDListDAGScheduler(IS, DAG, BB);
207 } else {
208 assert(TLI.getSchedulingPreference() ==
209 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
210 return createBURRListDAGScheduler(IS, DAG, BB);
211 }
212 }
213
214
215 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000216 /// FunctionLoweringInfo - This contains information that is global to a
217 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000218 class FunctionLoweringInfo {
219 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000220 TargetLowering &TLI;
221 Function &Fn;
222 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000223 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000224
225 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
226
227 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
228 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
229
230 /// ValueMap - Since we emit code for the function a basic block at a time,
231 /// we must remember which virtual registers hold the values for
232 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000233 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000234
235 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
236 /// the entry block. This allows the allocas to be efficiently referenced
237 /// anywhere in the function.
238 std::map<const AllocaInst*, int> StaticAllocaMap;
239
Duncan Sandsf4070822007-06-15 19:04:19 +0000240#ifndef NDEBUG
241 SmallSet<Instruction*, 8> CatchInfoLost;
242 SmallSet<Instruction*, 8> CatchInfoFound;
243#endif
244
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000246 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000247 }
Chris Lattner571e4342006-10-27 21:36:01 +0000248
249 /// isExportedInst - Return true if the specified value is an instruction
250 /// exported from its block.
251 bool isExportedInst(const Value *V) {
252 return ValueMap.count(V);
253 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000254
Chris Lattner3c384492006-03-16 19:51:18 +0000255 unsigned CreateRegForValue(const Value *V);
256
Chris Lattner1c08c712005-01-07 07:47:53 +0000257 unsigned InitializeRegForValue(const Value *V) {
258 unsigned &R = ValueMap[V];
259 assert(R == 0 && "Already initialized this value register!");
260 return R = CreateRegForValue(V);
261 }
262 };
263}
264
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000265/// isSelector - Return true if this instruction is a call to the
266/// eh.selector intrinsic.
267static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000268 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000269 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
270 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000271 return false;
272}
273
Chris Lattner1c08c712005-01-07 07:47:53 +0000274/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000275/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000276/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000277static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
278 if (isa<PHINode>(I)) return true;
279 BasicBlock *BB = I->getParent();
280 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000281 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000282 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000283 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000284 return true;
285 return false;
286}
287
Chris Lattnerbf209482005-10-30 19:42:35 +0000288/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000289/// entry block, return true. This includes arguments used by switches, since
290/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000291static bool isOnlyUsedInEntryBlock(Argument *A) {
292 BasicBlock *Entry = A->getParent()->begin();
293 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000294 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000295 return false; // Use not in entry block.
296 return true;
297}
298
Chris Lattner1c08c712005-01-07 07:47:53 +0000299FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000300 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000301 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000302
Chris Lattnerbf209482005-10-30 19:42:35 +0000303 // Create a vreg for each argument register that is not dead and is used
304 // outside of the entry block for the function.
305 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
306 AI != E; ++AI)
307 if (!isOnlyUsedInEntryBlock(AI))
308 InitializeRegForValue(AI);
309
Chris Lattner1c08c712005-01-07 07:47:53 +0000310 // Initialize the mapping of values to registers. This is only set up for
311 // instruction values that are used outside of the block that defines
312 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000313 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000314 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
315 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000316 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000317 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000318 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000319 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000320 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000321 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000322
Reid Spencerb83eb642006-10-20 07:07:24 +0000323 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000324 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000326 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000327 }
328
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000329 for (; BB != EB; ++BB)
330 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000331 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
332 if (!isa<AllocaInst>(I) ||
333 !StaticAllocaMap.count(cast<AllocaInst>(I)))
334 InitializeRegForValue(I);
335
336 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
337 // also creates the initial PHI MachineInstrs, though none of the input
338 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000339 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000340 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
341 MBBMap[BB] = MBB;
342 MF.getBasicBlockList().push_back(MBB);
343
344 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
345 // appropriate.
346 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000347 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
348 if (PN->use_empty()) continue;
349
350 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000351 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000352 unsigned PHIReg = ValueMap[PN];
353 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000354 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000355 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000356 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000357 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000358 }
359}
360
Chris Lattner3c384492006-03-16 19:51:18 +0000361/// CreateRegForValue - Allocate the appropriate number of virtual registers of
362/// the correctly promoted or expanded types. Assign these registers
363/// consecutive vreg numbers and return the first assigned number.
364unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000365 const Type *Ty = V->getType();
366 SmallVector<MVT::ValueType, 4> ValueVTs;
367 ComputeValueVTs(TLI, Ty, ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000368
Dan Gohman23ce5022008-04-25 18:27:55 +0000369 unsigned FirstReg = 0;
370 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
371 MVT::ValueType ValueVT = ValueVTs[Value];
372 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
373 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000374
Dan Gohman23ce5022008-04-25 18:27:55 +0000375 for (unsigned i = 0; i != NumRegs; ++i) {
376 unsigned R = MakeReg(RegisterVT);
377 if (!FirstReg) FirstReg = R;
378 }
379 }
380 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000381}
Chris Lattner1c08c712005-01-07 07:47:53 +0000382
383//===----------------------------------------------------------------------===//
384/// SelectionDAGLowering - This is the common target-independent lowering
385/// implementation that is parameterized by a TargetLowering object.
386/// Also, targets can overload any lowering method.
387///
388namespace llvm {
389class SelectionDAGLowering {
390 MachineBasicBlock *CurMBB;
391
Chris Lattner0da331f2007-02-04 01:31:47 +0000392 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000393
Chris Lattnerd3948112005-01-17 22:19:26 +0000394 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
395 /// them up and then emit token factor nodes when possible. This allows us to
396 /// get simple disambiguation between loads without worrying about alias
397 /// analysis.
398 std::vector<SDOperand> PendingLoads;
399
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000400 /// PendingExports - CopyToReg nodes that copy values to virtual registers
401 /// for export to other blocks need to be emitted before any terminator
402 /// instruction, but they have no other ordering requirements. We bunch them
403 /// up and the emit a single tokenfactor for them just before terminator
404 /// instructions.
405 std::vector<SDOperand> PendingExports;
406
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000407 /// Case - A struct to record the Value for a switch case, and the
408 /// case's target basic block.
409 struct Case {
410 Constant* Low;
411 Constant* High;
412 MachineBasicBlock* BB;
413
414 Case() : Low(0), High(0), BB(0) { }
415 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
416 Low(low), High(high), BB(bb) { }
417 uint64_t size() const {
418 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
419 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
420 return (rHigh - rLow + 1ULL);
421 }
422 };
423
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000424 struct CaseBits {
425 uint64_t Mask;
426 MachineBasicBlock* BB;
427 unsigned Bits;
428
429 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
430 Mask(mask), BB(bb), Bits(bits) { }
431 };
432
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000433 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000434 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000435 typedef CaseVector::iterator CaseItr;
436 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000437
438 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
439 /// of conditional branches.
440 struct CaseRec {
441 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
442 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
443
444 /// CaseBB - The MBB in which to emit the compare and branch
445 MachineBasicBlock *CaseBB;
446 /// LT, GE - If nonzero, we know the current case value must be less-than or
447 /// greater-than-or-equal-to these Constants.
448 Constant *LT;
449 Constant *GE;
450 /// Range - A pair of iterators representing the range of case values to be
451 /// processed at this point in the binary search tree.
452 CaseRange Range;
453 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000454
455 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000456
457 /// The comparison function for sorting the switch case values in the vector.
458 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000459 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000460 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000461 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
462 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
463 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
464 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000465 }
466 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000467
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000468 struct CaseBitsCmp {
469 bool operator () (const CaseBits& C1, const CaseBits& C2) {
470 return C1.Bits > C2.Bits;
471 }
472 };
473
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000474 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000475
Chris Lattner1c08c712005-01-07 07:47:53 +0000476public:
477 // TLI - This is information that describes the available target features we
478 // need for lowering. This indicates when operations are unavailable,
479 // implemented with a libcall, etc.
480 TargetLowering &TLI;
481 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000482 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000483 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000484
Nate Begemanf15485a2006-03-27 01:32:24 +0000485 /// SwitchCases - Vector of CaseBlock structures used to communicate
486 /// SwitchInst code generation information.
487 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000488 /// JTCases - Vector of JumpTable structures used to communicate
489 /// SwitchInst code generation information.
490 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000491 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000492
Chris Lattner1c08c712005-01-07 07:47:53 +0000493 /// FuncInfo - Information about the function as a whole.
494 ///
495 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000496
497 /// GCI - Garbage collection metadata for the function.
498 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000499
500 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000501 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000502 FunctionLoweringInfo &funcinfo,
503 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000504 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000505 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 }
507
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000508 /// getRoot - Return the current virtual root of the Selection DAG,
509 /// flushing any PendingLoad items. This must be done before emitting
510 /// a store or any other node that may need to be ordered after any
511 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000512 ///
513 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000514 if (PendingLoads.empty())
515 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000516
Chris Lattnerd3948112005-01-17 22:19:26 +0000517 if (PendingLoads.size() == 1) {
518 SDOperand Root = PendingLoads[0];
519 DAG.setRoot(Root);
520 PendingLoads.clear();
521 return Root;
522 }
523
524 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000525 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
526 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000527 PendingLoads.clear();
528 DAG.setRoot(Root);
529 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000530 }
531
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000532 /// getControlRoot - Similar to getRoot, but instead of flushing all the
533 /// PendingLoad items, flush all the PendingExports items. It is necessary
534 /// to do this before emitting a terminator instruction.
535 ///
536 SDOperand getControlRoot() {
537 SDOperand Root = DAG.getRoot();
538
539 if (PendingExports.empty())
540 return Root;
541
542 // Turn all of the CopyToReg chains into one factored node.
543 if (Root.getOpcode() != ISD::EntryToken) {
544 unsigned i = 0, e = PendingExports.size();
545 for (; i != e; ++i) {
546 assert(PendingExports[i].Val->getNumOperands() > 1);
547 if (PendingExports[i].Val->getOperand(0) == Root)
548 break; // Don't add the root if we already indirectly depend on it.
549 }
550
551 if (i == e)
552 PendingExports.push_back(Root);
553 }
554
555 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
556 &PendingExports[0],
557 PendingExports.size());
558 PendingExports.clear();
559 DAG.setRoot(Root);
560 return Root;
561 }
562
563 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000564
Chris Lattner1c08c712005-01-07 07:47:53 +0000565 void visit(Instruction &I) { visit(I.getOpcode(), I); }
566
567 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000568 // Note: this doesn't use InstVisitor, because it has to work with
569 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000570 switch (Opcode) {
571 default: assert(0 && "Unknown instruction type encountered!");
572 abort();
573 // Build the switch statement using the Instruction.def file.
574#define HANDLE_INST(NUM, OPCODE, CLASS) \
575 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
576#include "llvm/Instruction.def"
577 }
578 }
579
580 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
581
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000582 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000583 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000584 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000585
Chris Lattner199862b2006-03-16 19:57:50 +0000586 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000587
Chris Lattner0da331f2007-02-04 01:31:47 +0000588 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000589 SDOperand &N = NodeMap[V];
590 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000591 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000592 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000593
Evan Cheng5c807602008-02-26 02:33:44 +0000594 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000595 std::set<unsigned> &OutputRegs,
596 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000597
Chris Lattner571e4342006-10-27 21:36:01 +0000598 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
599 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
600 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000601 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000602 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000603 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000604 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000605
Chris Lattner1c08c712005-01-07 07:47:53 +0000606 // Terminator instructions.
607 void visitRet(ReturnInst &I);
608 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000609 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000610 void visitUnreachable(UnreachableInst &I) { /* noop */ }
611
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000612 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000613 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000614 CaseRecVector& WorkList,
615 Value* SV,
616 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000617 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000618 CaseRecVector& WorkList,
619 Value* SV,
620 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000621 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000622 CaseRecVector& WorkList,
623 Value* SV,
624 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000625 bool handleBitTestsSwitchCase(CaseRec& CR,
626 CaseRecVector& WorkList,
627 Value* SV,
628 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000629 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000630 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
631 void visitBitTestCase(MachineBasicBlock* NextMBB,
632 unsigned Reg,
633 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000634 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000635 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
636 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000637
Chris Lattner1c08c712005-01-07 07:47:53 +0000638 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000639 void visitInvoke(InvokeInst &I);
640 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000641
Dan Gohman7f321562007-06-25 16:23:39 +0000642 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000643 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000644 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000645 if (I.getType()->isFPOrFPVector())
646 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000647 else
Dan Gohman7f321562007-06-25 16:23:39 +0000648 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000649 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000650 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000651 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000652 if (I.getType()->isFPOrFPVector())
653 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000654 else
Dan Gohman7f321562007-06-25 16:23:39 +0000655 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000656 }
Dan Gohman7f321562007-06-25 16:23:39 +0000657 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
658 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
659 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
660 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
661 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
662 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
663 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
664 void visitOr (User &I) { visitBinary(I, ISD::OR); }
665 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000666 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000667 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
668 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000669 void visitICmp(User &I);
670 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000671 // Visit the conversion instructions
672 void visitTrunc(User &I);
673 void visitZExt(User &I);
674 void visitSExt(User &I);
675 void visitFPTrunc(User &I);
676 void visitFPExt(User &I);
677 void visitFPToUI(User &I);
678 void visitFPToSI(User &I);
679 void visitUIToFP(User &I);
680 void visitSIToFP(User &I);
681 void visitPtrToInt(User &I);
682 void visitIntToPtr(User &I);
683 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000684
Chris Lattner2bbd8102006-03-29 00:11:43 +0000685 void visitExtractElement(User &I);
686 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000687 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000688
Chris Lattner1c08c712005-01-07 07:47:53 +0000689 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000690 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000691
692 void visitMalloc(MallocInst &I);
693 void visitFree(FreeInst &I);
694 void visitAlloca(AllocaInst &I);
695 void visitLoad(LoadInst &I);
696 void visitStore(StoreInst &I);
697 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
698 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000699 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000700 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000701 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000702
Chris Lattner1c08c712005-01-07 07:47:53 +0000703 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000704 void visitVAArg(VAArgInst &I);
705 void visitVAEnd(CallInst &I);
706 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707
Dan Gohmanef5d1942008-03-11 21:11:25 +0000708 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000709
Chris Lattner1c08c712005-01-07 07:47:53 +0000710 void visitUserOp1(Instruction &I) {
711 assert(0 && "UserOp1 should not exist at instruction selection time!");
712 abort();
713 }
714 void visitUserOp2(Instruction &I) {
715 assert(0 && "UserOp2 should not exist at instruction selection time!");
716 abort();
717 }
718};
719} // end namespace llvm
720
Dan Gohman6183f782007-07-05 20:12:34 +0000721
Duncan Sandsb988bac2008-02-11 20:58:28 +0000722/// getCopyFromParts - Create a value that contains the specified legal parts
723/// combined into the value they represent. If the parts combine to a type
724/// larger then ValueVT then AssertOp can be used to specify whether the extra
725/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000726/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000727static SDOperand getCopyFromParts(SelectionDAG &DAG,
728 const SDOperand *Parts,
729 unsigned NumParts,
730 MVT::ValueType PartVT,
731 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000732 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000733 assert(NumParts > 0 && "No parts to assemble!");
734 TargetLowering &TLI = DAG.getTargetLoweringInfo();
735 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000736
Duncan Sands014e04a2008-02-12 20:46:31 +0000737 if (NumParts > 1) {
738 // Assemble the value from multiple parts.
739 if (!MVT::isVector(ValueVT)) {
740 unsigned PartBits = MVT::getSizeInBits(PartVT);
741 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000742
Duncan Sands014e04a2008-02-12 20:46:31 +0000743 // Assemble the power of 2 part.
744 unsigned RoundParts = NumParts & (NumParts - 1) ?
745 1 << Log2_32(NumParts) : NumParts;
746 unsigned RoundBits = PartBits * RoundParts;
747 MVT::ValueType RoundVT = RoundBits == ValueBits ?
748 ValueVT : MVT::getIntegerType(RoundBits);
749 SDOperand Lo, Hi;
750
751 if (RoundParts > 2) {
752 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
753 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
754 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
755 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000756 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000757 Lo = Parts[0];
758 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000759 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000760 if (TLI.isBigEndian())
761 std::swap(Lo, Hi);
762 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
763
764 if (RoundParts < NumParts) {
765 // Assemble the trailing non-power-of-2 part.
766 unsigned OddParts = NumParts - RoundParts;
767 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
768 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
769
770 // Combine the round and odd parts.
771 Lo = Val;
772 if (TLI.isBigEndian())
773 std::swap(Lo, Hi);
774 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
775 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
776 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
777 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
778 TLI.getShiftAmountTy()));
779 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
780 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
781 }
782 } else {
783 // Handle a multi-element vector.
784 MVT::ValueType IntermediateVT, RegisterVT;
785 unsigned NumIntermediates;
786 unsigned NumRegs =
787 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
788 RegisterVT);
789
790 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
791 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
792 assert(RegisterVT == Parts[0].getValueType() &&
793 "Part type doesn't match part!");
794
795 // Assemble the parts into intermediate operands.
796 SmallVector<SDOperand, 8> Ops(NumIntermediates);
797 if (NumIntermediates == NumParts) {
798 // If the register was not expanded, truncate or copy the value,
799 // as appropriate.
800 for (unsigned i = 0; i != NumParts; ++i)
801 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
802 PartVT, IntermediateVT);
803 } else if (NumParts > 0) {
804 // If the intermediate type was expanded, build the intermediate operands
805 // from the parts.
806 assert(NumParts % NumIntermediates == 0 &&
807 "Must expand into a divisible number of parts!");
808 unsigned Factor = NumParts / NumIntermediates;
809 for (unsigned i = 0; i != NumIntermediates; ++i)
810 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
811 PartVT, IntermediateVT);
812 }
813
814 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
815 // operands.
816 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
817 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
818 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000819 }
Dan Gohman6183f782007-07-05 20:12:34 +0000820 }
821
Duncan Sands014e04a2008-02-12 20:46:31 +0000822 // There is now one part, held in Val. Correct it to match ValueVT.
823 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000824
Duncan Sands014e04a2008-02-12 20:46:31 +0000825 if (PartVT == ValueVT)
826 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000827
Duncan Sands014e04a2008-02-12 20:46:31 +0000828 if (MVT::isVector(PartVT)) {
829 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
830 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000831 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000832
833 if (MVT::isVector(ValueVT)) {
834 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
835 MVT::getVectorNumElements(ValueVT) == 1 &&
836 "Only trivial scalar-to-vector conversions should get here!");
837 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
838 }
839
840 if (MVT::isInteger(PartVT) &&
841 MVT::isInteger(ValueVT)) {
842 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
843 // For a truncate, see if we have any information to
844 // indicate whether the truncated bits will always be
845 // zero or sign-extension.
846 if (AssertOp != ISD::DELETED_NODE)
847 Val = DAG.getNode(AssertOp, PartVT, Val,
848 DAG.getValueType(ValueVT));
849 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
850 } else {
851 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
852 }
853 }
854
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000855 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
856 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000857 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000858 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000859 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000860 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
861 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000862
863 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
864 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
865
866 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000867 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000868}
869
Duncan Sandsb988bac2008-02-11 20:58:28 +0000870/// getCopyToParts - Create a series of nodes that contain the specified value
871/// split into legal parts. If the parts contain more bits than Val, then, for
872/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000873static void getCopyToParts(SelectionDAG &DAG,
874 SDOperand Val,
875 SDOperand *Parts,
876 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000877 MVT::ValueType PartVT,
878 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000879 TargetLowering &TLI = DAG.getTargetLoweringInfo();
880 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000881 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000882 unsigned PartBits = MVT::getSizeInBits(PartVT);
883 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000884
Duncan Sands014e04a2008-02-12 20:46:31 +0000885 if (!NumParts)
886 return;
887
888 if (!MVT::isVector(ValueVT)) {
889 if (PartVT == ValueVT) {
890 assert(NumParts == 1 && "No-op copy with multiple parts!");
891 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000892 return;
893 }
894
Duncan Sands014e04a2008-02-12 20:46:31 +0000895 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
896 // If the parts cover more bits than the value has, promote the value.
897 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
898 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000899 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000900 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
901 ValueVT = MVT::getIntegerType(NumParts * PartBits);
902 Val = DAG.getNode(ExtendKind, ValueVT, Val);
903 } else {
904 assert(0 && "Unknown mismatch!");
905 }
906 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
907 // Different types of the same size.
908 assert(NumParts == 1 && PartVT != ValueVT);
909 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
910 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
911 // If the parts cover less bits than value has, truncate the value.
912 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
913 ValueVT = MVT::getIntegerType(NumParts * PartBits);
914 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000915 } else {
916 assert(0 && "Unknown mismatch!");
917 }
918 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000919
920 // The value may have changed - recompute ValueVT.
921 ValueVT = Val.getValueType();
922 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
923 "Failed to tile the value with PartVT!");
924
925 if (NumParts == 1) {
926 assert(PartVT == ValueVT && "Type conversion failed!");
927 Parts[0] = Val;
928 return;
929 }
930
931 // Expand the value into multiple parts.
932 if (NumParts & (NumParts - 1)) {
933 // The number of parts is not a power of 2. Split off and copy the tail.
934 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
935 "Do not know what to expand to!");
936 unsigned RoundParts = 1 << Log2_32(NumParts);
937 unsigned RoundBits = RoundParts * PartBits;
938 unsigned OddParts = NumParts - RoundParts;
939 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
940 DAG.getConstant(RoundBits,
941 TLI.getShiftAmountTy()));
942 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
943 if (TLI.isBigEndian())
944 // The odd parts were reversed by getCopyToParts - unreverse them.
945 std::reverse(Parts + RoundParts, Parts + NumParts);
946 NumParts = RoundParts;
947 ValueVT = MVT::getIntegerType(NumParts * PartBits);
948 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
949 }
950
951 // The number of parts is a power of 2. Repeatedly bisect the value using
952 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000953 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
954 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
955 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000956 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
957 for (unsigned i = 0; i < NumParts; i += StepSize) {
958 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000959 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
960 SDOperand &Part0 = Parts[i];
961 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000962
Duncan Sands25eb0432008-03-12 20:30:08 +0000963 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
964 DAG.getConstant(1, PtrVT));
965 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
966 DAG.getConstant(0, PtrVT));
967
968 if (ThisBits == PartBits && ThisVT != PartVT) {
969 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
970 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
971 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000972 }
973 }
974
975 if (TLI.isBigEndian())
976 std::reverse(Parts, Parts + NumParts);
977
978 return;
979 }
980
981 // Vector ValueVT.
982 if (NumParts == 1) {
983 if (PartVT != ValueVT) {
984 if (MVT::isVector(PartVT)) {
985 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
986 } else {
987 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
988 MVT::getVectorNumElements(ValueVT) == 1 &&
989 "Only trivial vector-to-scalar conversions should get here!");
990 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
991 DAG.getConstant(0, PtrVT));
992 }
993 }
994
Dan Gohman6183f782007-07-05 20:12:34 +0000995 Parts[0] = Val;
996 return;
997 }
998
999 // Handle a multi-element vector.
1000 MVT::ValueType IntermediateVT, RegisterVT;
1001 unsigned NumIntermediates;
1002 unsigned NumRegs =
1003 DAG.getTargetLoweringInfo()
1004 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1005 RegisterVT);
1006 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1007
1008 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1009 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1010
1011 // Split the vector into intermediate operands.
1012 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1013 for (unsigned i = 0; i != NumIntermediates; ++i)
1014 if (MVT::isVector(IntermediateVT))
1015 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1016 IntermediateVT, Val,
1017 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001018 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001019 else
1020 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1021 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001022 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001023
1024 // Split the intermediate operands into legal parts.
1025 if (NumParts == NumIntermediates) {
1026 // If the register was not expanded, promote or copy the value,
1027 // as appropriate.
1028 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001029 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001030 } else if (NumParts > 0) {
1031 // If the intermediate type was expanded, split each the value into
1032 // legal parts.
1033 assert(NumParts % NumIntermediates == 0 &&
1034 "Must expand into a divisible number of parts!");
1035 unsigned Factor = NumParts / NumIntermediates;
1036 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001037 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001038 }
1039}
1040
1041
Chris Lattner199862b2006-03-16 19:57:50 +00001042SDOperand SelectionDAGLowering::getValue(const Value *V) {
1043 SDOperand &N = NodeMap[V];
1044 if (N.Val) return N;
1045
1046 const Type *VTy = V->getType();
Dan Gohman23ce5022008-04-25 18:27:55 +00001047 MVT::ValueType VT = TLI.getValueType(VTy, true);
Chris Lattner199862b2006-03-16 19:57:50 +00001048 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1050 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +00001051 SDOperand N1 = NodeMap[V];
1052 assert(N1.Val && "visit didn't populate the ValueMap!");
1053 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +00001054 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
1055 return N = DAG.getGlobalAddress(GV, VT);
1056 } else if (isa<ConstantPointerNull>(C)) {
1057 return N = DAG.getConstant(0, TLI.getPointerTy());
1058 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001059 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +00001060 return N = DAG.getNode(ISD::UNDEF, VT);
1061
Dan Gohman7f321562007-06-25 16:23:39 +00001062 // Create a BUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001063 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +00001064 unsigned NumElements = PTy->getNumElements();
1065 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1066
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001067 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +00001068 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1069
1070 // Create a VConstant node with generic Vector type.
Dan Gohman7f321562007-06-25 16:23:39 +00001071 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1072 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001073 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001074 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001075 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +00001076 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +00001077 unsigned NumElements = PTy->getNumElements();
1078 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +00001079
1080 // Now that we know the number and type of the elements, push a
1081 // Constant or ConstantFP node onto the ops list for each element of
Dan Gohman07a96762007-07-16 14:29:03 +00001082 // the vector constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001083 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001084 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +00001085 for (unsigned i = 0; i != NumElements; ++i)
1086 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +00001087 } else {
Dan Gohman07a96762007-07-16 14:29:03 +00001088 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Chris Lattner199862b2006-03-16 19:57:50 +00001089 SDOperand Op;
1090 if (MVT::isFloatingPoint(PVT))
1091 Op = DAG.getConstantFP(0, PVT);
1092 else
1093 Op = DAG.getConstant(0, PVT);
1094 Ops.assign(NumElements, Op);
1095 }
1096
Dan Gohman7f321562007-06-25 16:23:39 +00001097 // Create a BUILD_VECTOR node.
1098 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1099 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner0da331f2007-02-04 01:31:47 +00001100 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001101 } else {
1102 // Canonicalize all constant ints to be unsigned.
Dan Gohmanc6f9a062008-02-29 01:41:59 +00001103 return N = DAG.getConstant(cast<ConstantInt>(C)->getValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +00001104 }
1105 }
1106
1107 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1108 std::map<const AllocaInst*, int>::iterator SI =
1109 FuncInfo.StaticAllocaMap.find(AI);
1110 if (SI != FuncInfo.StaticAllocaMap.end())
1111 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1112 }
1113
Chris Lattner251db182007-02-25 18:40:32 +00001114 unsigned InReg = FuncInfo.ValueMap[V];
1115 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001116
Dan Gohman23ce5022008-04-25 18:27:55 +00001117 RegsForValue RFV(TLI, InReg, VTy);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001118 SDOperand Chain = DAG.getEntryNode();
1119
1120 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001121}
1122
1123
Chris Lattner1c08c712005-01-07 07:47:53 +00001124void SelectionDAGLowering::visitRet(ReturnInst &I) {
1125 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001126 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001127 return;
1128 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001129 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001130 NewValues.push_back(getControlRoot());
1131 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001132 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001133 MVT::ValueType VT = RetOp.getValueType();
1134
Evan Cheng8e7d0562006-05-26 23:09:09 +00001135 // FIXME: C calling convention requires the return type to be promoted to
1136 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001137 if (MVT::isInteger(VT)) {
1138 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1139 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1140 VT = MinVT;
1141 }
1142
1143 unsigned NumParts = TLI.getNumRegisters(VT);
1144 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1145 SmallVector<SDOperand, 4> Parts(NumParts);
1146 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1147
1148 const Function *F = I.getParent()->getParent();
1149 if (F->paramHasAttr(0, ParamAttr::SExt))
1150 ExtendKind = ISD::SIGN_EXTEND;
1151 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1152 ExtendKind = ISD::ZERO_EXTEND;
1153
1154 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1155
1156 for (unsigned i = 0; i < NumParts; ++i) {
1157 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001158 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001159 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001160 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001161 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1162 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001163}
1164
Chris Lattner571e4342006-10-27 21:36:01 +00001165/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1166/// the current basic block, add it to ValueMap now so that we'll get a
1167/// CopyTo/FromReg.
1168void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1169 // No need to export constants.
1170 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1171
1172 // Already exported?
1173 if (FuncInfo.isExportedInst(V)) return;
1174
1175 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001176 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001177}
1178
Chris Lattner8c494ab2006-10-27 23:50:33 +00001179bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1180 const BasicBlock *FromBB) {
1181 // The operands of the setcc have to be in this block. We don't know
1182 // how to export them from some other block.
1183 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1184 // Can export from current BB.
1185 if (VI->getParent() == FromBB)
1186 return true;
1187
1188 // Is already exported, noop.
1189 return FuncInfo.isExportedInst(V);
1190 }
1191
1192 // If this is an argument, we can export it if the BB is the entry block or
1193 // if it is already exported.
1194 if (isa<Argument>(V)) {
1195 if (FromBB == &FromBB->getParent()->getEntryBlock())
1196 return true;
1197
1198 // Otherwise, can only export this if it is already exported.
1199 return FuncInfo.isExportedInst(V);
1200 }
1201
1202 // Otherwise, constants can always be exported.
1203 return true;
1204}
1205
Chris Lattner6a586c82006-10-29 21:01:20 +00001206static bool InBlock(const Value *V, const BasicBlock *BB) {
1207 if (const Instruction *I = dyn_cast<Instruction>(V))
1208 return I->getParent() == BB;
1209 return true;
1210}
1211
Chris Lattner571e4342006-10-27 21:36:01 +00001212/// FindMergedConditions - If Cond is an expression like
1213void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1214 MachineBasicBlock *TBB,
1215 MachineBasicBlock *FBB,
1216 MachineBasicBlock *CurBB,
1217 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001218 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001219 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001220
Reid Spencere4d87aa2006-12-23 06:05:41 +00001221 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1222 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001223 BOp->getParent() != CurBB->getBasicBlock() ||
1224 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1225 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001226 const BasicBlock *BB = CurBB->getBasicBlock();
1227
Reid Spencere4d87aa2006-12-23 06:05:41 +00001228 // If the leaf of the tree is a comparison, merge the condition into
1229 // the caseblock.
1230 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1231 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001232 // how to export them from some other block. If this is the first block
1233 // of the sequence, no exporting is needed.
1234 (CurBB == CurMBB ||
1235 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1236 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001237 BOp = cast<Instruction>(Cond);
1238 ISD::CondCode Condition;
1239 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1240 switch (IC->getPredicate()) {
1241 default: assert(0 && "Unknown icmp predicate opcode!");
1242 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1243 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1244 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1245 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1246 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1247 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1248 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1249 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1250 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1251 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1252 }
1253 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1254 ISD::CondCode FPC, FOC;
1255 switch (FC->getPredicate()) {
1256 default: assert(0 && "Unknown fcmp predicate opcode!");
1257 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1258 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1259 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1260 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1261 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1262 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1263 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1264 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1265 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1266 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1267 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1268 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1269 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1270 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1271 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1272 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1273 }
1274 if (FiniteOnlyFPMath())
1275 Condition = FOC;
1276 else
1277 Condition = FPC;
1278 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001279 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001280 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001281 }
1282
Chris Lattner571e4342006-10-27 21:36:01 +00001283 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001284 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001285 SwitchCases.push_back(CB);
1286 return;
1287 }
1288
1289 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001290 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001291 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001292 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001293 return;
1294 }
1295
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001296
1297 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001298 MachineFunction::iterator BBI = CurBB;
1299 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1300 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1301
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001302 if (Opc == Instruction::Or) {
1303 // Codegen X | Y as:
1304 // jmp_if_X TBB
1305 // jmp TmpBB
1306 // TmpBB:
1307 // jmp_if_Y TBB
1308 // jmp FBB
1309 //
Chris Lattner571e4342006-10-27 21:36:01 +00001310
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001311 // Emit the LHS condition.
1312 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1313
1314 // Emit the RHS condition into TmpBB.
1315 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1316 } else {
1317 assert(Opc == Instruction::And && "Unknown merge op!");
1318 // Codegen X & Y as:
1319 // jmp_if_X TmpBB
1320 // jmp FBB
1321 // TmpBB:
1322 // jmp_if_Y TBB
1323 // jmp FBB
1324 //
1325 // This requires creation of TmpBB after CurBB.
1326
1327 // Emit the LHS condition.
1328 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1329
1330 // Emit the RHS condition into TmpBB.
1331 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1332 }
Chris Lattner571e4342006-10-27 21:36:01 +00001333}
1334
Chris Lattnerdf19f272006-10-31 22:37:42 +00001335/// If the set of cases should be emitted as a series of branches, return true.
1336/// If we should emit this as a bunch of and/or'd together conditions, return
1337/// false.
1338static bool
1339ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1340 if (Cases.size() != 2) return true;
1341
Chris Lattner0ccb5002006-10-31 23:06:00 +00001342 // If this is two comparisons of the same values or'd or and'd together, they
1343 // will get folded into a single comparison, so don't emit two blocks.
1344 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1345 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1346 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1347 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1348 return false;
1349 }
1350
Chris Lattnerdf19f272006-10-31 22:37:42 +00001351 return true;
1352}
1353
Chris Lattner1c08c712005-01-07 07:47:53 +00001354void SelectionDAGLowering::visitBr(BranchInst &I) {
1355 // Update machine-CFG edges.
1356 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001357
1358 // Figure out which block is immediately after the current one.
1359 MachineBasicBlock *NextBlock = 0;
1360 MachineFunction::iterator BBI = CurMBB;
1361 if (++BBI != CurMBB->getParent()->end())
1362 NextBlock = BBI;
1363
1364 if (I.isUnconditional()) {
1365 // If this is not a fall-through branch, emit the branch.
1366 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001367 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001368 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001369
Chris Lattner57ab6592006-10-24 17:57:59 +00001370 // Update machine-CFG edges.
1371 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001372 return;
1373 }
1374
1375 // If this condition is one of the special cases we handle, do special stuff
1376 // now.
1377 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001378 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001379
1380 // If this is a series of conditions that are or'd or and'd together, emit
1381 // this as a sequence of branches instead of setcc's with and/or operations.
1382 // For example, instead of something like:
1383 // cmp A, B
1384 // C = seteq
1385 // cmp D, E
1386 // F = setle
1387 // or C, F
1388 // jnz foo
1389 // Emit:
1390 // cmp A, B
1391 // je foo
1392 // cmp D, E
1393 // jle foo
1394 //
1395 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1396 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001397 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001398 BOp->getOpcode() == Instruction::Or)) {
1399 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001400 // If the compares in later blocks need to use values not currently
1401 // exported from this block, export them now. This block should always
1402 // be the first entry.
1403 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1404
Chris Lattnerdf19f272006-10-31 22:37:42 +00001405 // Allow some cases to be rejected.
1406 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001407 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1408 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1409 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1410 }
1411
1412 // Emit the branch for this block.
1413 visitSwitchCase(SwitchCases[0]);
1414 SwitchCases.erase(SwitchCases.begin());
1415 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001416 }
1417
Chris Lattner0ccb5002006-10-31 23:06:00 +00001418 // Okay, we decided not to do this, remove any inserted MBB's and clear
1419 // SwitchCases.
1420 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1421 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1422
Chris Lattnerdf19f272006-10-31 22:37:42 +00001423 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001424 }
1425 }
Chris Lattner24525952006-10-24 18:07:37 +00001426
1427 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001428 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001429 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001430 // Use visitSwitchCase to actually insert the fast branch sequence for this
1431 // cond branch.
1432 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001433}
1434
Nate Begemanf15485a2006-03-27 01:32:24 +00001435/// visitSwitchCase - Emits the necessary code to represent a single node in
1436/// the binary search tree resulting from lowering a switch instruction.
1437void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001438 SDOperand Cond;
1439 SDOperand CondLHS = getValue(CB.CmpLHS);
1440
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001441 // Build the setcc now.
1442 if (CB.CmpMHS == NULL) {
1443 // Fold "(X == true)" to X and "(X == false)" to !X to
1444 // handle common cases produced by branch lowering.
1445 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1446 Cond = CondLHS;
1447 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1448 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1449 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1450 } else
1451 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1452 } else {
1453 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001454
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001455 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1456 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1457
1458 SDOperand CmpOp = getValue(CB.CmpMHS);
1459 MVT::ValueType VT = CmpOp.getValueType();
1460
1461 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1462 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1463 } else {
1464 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1465 Cond = DAG.getSetCC(MVT::i1, SUB,
1466 DAG.getConstant(High-Low, VT), ISD::SETULE);
1467 }
1468
1469 }
1470
Nate Begemanf15485a2006-03-27 01:32:24 +00001471 // Set NextBlock to be the MBB immediately after the current one, if any.
1472 // This is used to avoid emitting unnecessary branches to the next block.
1473 MachineBasicBlock *NextBlock = 0;
1474 MachineFunction::iterator BBI = CurMBB;
1475 if (++BBI != CurMBB->getParent()->end())
1476 NextBlock = BBI;
1477
1478 // If the lhs block is the next block, invert the condition so that we can
1479 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001480 if (CB.TrueBB == NextBlock) {
1481 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001482 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1483 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1484 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001485 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001486 DAG.getBasicBlock(CB.TrueBB));
1487 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001488 DAG.setRoot(BrCond);
1489 else
1490 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001491 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001492 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001493 CurMBB->addSuccessor(CB.TrueBB);
1494 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001495}
1496
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001497/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001498void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001499 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001500 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001501 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001502 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001503 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1504 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1505 Table, Index));
1506 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001507}
1508
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001509/// visitJumpTableHeader - This function emits necessary code to produce index
1510/// in the JumpTable from switch case.
1511void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1512 SelectionDAGISel::JumpTableHeader &JTH) {
1513 // Subtract the lowest switch case value from the value being switched on
1514 // and conditional branch to default mbb if the result is greater than the
1515 // difference between smallest and largest cases.
1516 SDOperand SwitchOp = getValue(JTH.SValue);
1517 MVT::ValueType VT = SwitchOp.getValueType();
1518 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1519 DAG.getConstant(JTH.First, VT));
1520
1521 // The SDNode we just created, which holds the value being switched on
1522 // minus the the smallest case value, needs to be copied to a virtual
1523 // register so it can be used as an index into the jump table in a
1524 // subsequent basic block. This value may be smaller or larger than the
1525 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001526 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001527 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1528 else
1529 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1530
1531 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001532 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001533 JT.Reg = JumpTableReg;
1534
1535 // Emit the range check for the jump table, and branch to the default
1536 // block for the switch statement if the value being switched on exceeds
1537 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001538 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001539 DAG.getConstant(JTH.Last-JTH.First,VT),
1540 ISD::SETUGT);
1541
1542 // Set NextBlock to be the MBB immediately after the current one, if any.
1543 // This is used to avoid emitting unnecessary branches to the next block.
1544 MachineBasicBlock *NextBlock = 0;
1545 MachineFunction::iterator BBI = CurMBB;
1546 if (++BBI != CurMBB->getParent()->end())
1547 NextBlock = BBI;
1548
1549 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1550 DAG.getBasicBlock(JT.Default));
1551
1552 if (JT.MBB == NextBlock)
1553 DAG.setRoot(BrCond);
1554 else
1555 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001556 DAG.getBasicBlock(JT.MBB)));
1557
1558 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001559}
1560
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001561/// visitBitTestHeader - This function emits necessary code to produce value
1562/// suitable for "bit tests"
1563void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1564 // Subtract the minimum value
1565 SDOperand SwitchOp = getValue(B.SValue);
1566 MVT::ValueType VT = SwitchOp.getValueType();
1567 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1568 DAG.getConstant(B.First, VT));
1569
1570 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001571 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001572 DAG.getConstant(B.Range, VT),
1573 ISD::SETUGT);
1574
1575 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001576 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001577 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1578 else
1579 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1580
1581 // Make desired shift
1582 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1583 DAG.getConstant(1, TLI.getPointerTy()),
1584 ShiftOp);
1585
1586 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001587 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001588 B.Reg = SwitchReg;
1589
1590 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1591 DAG.getBasicBlock(B.Default));
1592
1593 // Set NextBlock to be the MBB immediately after the current one, if any.
1594 // This is used to avoid emitting unnecessary branches to the next block.
1595 MachineBasicBlock *NextBlock = 0;
1596 MachineFunction::iterator BBI = CurMBB;
1597 if (++BBI != CurMBB->getParent()->end())
1598 NextBlock = BBI;
1599
1600 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1601 if (MBB == NextBlock)
1602 DAG.setRoot(BrRange);
1603 else
1604 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1605 DAG.getBasicBlock(MBB)));
1606
1607 CurMBB->addSuccessor(B.Default);
1608 CurMBB->addSuccessor(MBB);
1609
1610 return;
1611}
1612
1613/// visitBitTestCase - this function produces one "bit test"
1614void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1615 unsigned Reg,
1616 SelectionDAGISel::BitTestCase &B) {
1617 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001618 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001619
1620 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1621 SwitchVal,
1622 DAG.getConstant(B.Mask,
1623 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001624 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001625 DAG.getConstant(0, TLI.getPointerTy()),
1626 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001627 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001628 AndCmp, DAG.getBasicBlock(B.TargetBB));
1629
1630 // Set NextBlock to be the MBB immediately after the current one, if any.
1631 // This is used to avoid emitting unnecessary branches to the next block.
1632 MachineBasicBlock *NextBlock = 0;
1633 MachineFunction::iterator BBI = CurMBB;
1634 if (++BBI != CurMBB->getParent()->end())
1635 NextBlock = BBI;
1636
1637 if (NextMBB == NextBlock)
1638 DAG.setRoot(BrAnd);
1639 else
1640 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1641 DAG.getBasicBlock(NextMBB)));
1642
1643 CurMBB->addSuccessor(B.TargetBB);
1644 CurMBB->addSuccessor(NextMBB);
1645
1646 return;
1647}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001648
Jim Laskeyb180aa12007-02-21 22:53:45 +00001649void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1650 // Retrieve successors.
1651 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001652 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001653
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001654 if (isa<InlineAsm>(I.getCalledValue()))
1655 visitInlineAsm(&I);
1656 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001657 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001658
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001659 // If the value of the invoke is used outside of its defining block, make it
1660 // available as a virtual register.
1661 if (!I.use_empty()) {
1662 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1663 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001664 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001665 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001666
1667 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001668 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001669 DAG.getBasicBlock(Return)));
1670
1671 // Update successor info
1672 CurMBB->addSuccessor(Return);
1673 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001674}
1675
1676void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1677}
1678
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001679/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001680/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001681bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001682 CaseRecVector& WorkList,
1683 Value* SV,
1684 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001685 Case& BackCase = *(CR.Range.second-1);
1686
1687 // Size is the number of Cases represented by this range.
1688 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001689 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001690 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001691
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001692 // Get the MachineFunction which holds the current MBB. This is used when
1693 // inserting any additional MBBs necessary to represent the switch.
1694 MachineFunction *CurMF = CurMBB->getParent();
1695
1696 // Figure out which block is immediately after the current one.
1697 MachineBasicBlock *NextBlock = 0;
1698 MachineFunction::iterator BBI = CR.CaseBB;
1699
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001700 if (++BBI != CurMBB->getParent()->end())
1701 NextBlock = BBI;
1702
1703 // TODO: If any two of the cases has the same destination, and if one value
1704 // is the same as the other, but has one bit unset that the other has set,
1705 // use bit manipulation to do two compares at once. For example:
1706 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1707
1708 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001709 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001710 // The last case block won't fall through into 'NextBlock' if we emit the
1711 // branches in this order. See if rearranging a case value would help.
1712 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001713 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001714 std::swap(*I, BackCase);
1715 break;
1716 }
1717 }
1718 }
1719
1720 // Create a CaseBlock record representing a conditional branch to
1721 // the Case's target mbb if the value being switched on SV is equal
1722 // to C.
1723 MachineBasicBlock *CurBlock = CR.CaseBB;
1724 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1725 MachineBasicBlock *FallThrough;
1726 if (I != E-1) {
1727 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1728 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1729 } else {
1730 // If the last case doesn't match, go to the default block.
1731 FallThrough = Default;
1732 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001733
1734 Value *RHS, *LHS, *MHS;
1735 ISD::CondCode CC;
1736 if (I->High == I->Low) {
1737 // This is just small small case range :) containing exactly 1 case
1738 CC = ISD::SETEQ;
1739 LHS = SV; RHS = I->High; MHS = NULL;
1740 } else {
1741 CC = ISD::SETLE;
1742 LHS = I->Low; MHS = SV; RHS = I->High;
1743 }
1744 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1745 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001746
1747 // If emitting the first comparison, just call visitSwitchCase to emit the
1748 // code into the current block. Otherwise, push the CaseBlock onto the
1749 // vector to be later processed by SDISel, and insert the node's MBB
1750 // before the next MBB.
1751 if (CurBlock == CurMBB)
1752 visitSwitchCase(CB);
1753 else
1754 SwitchCases.push_back(CB);
1755
1756 CurBlock = FallThrough;
1757 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001758
1759 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001760}
1761
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001762static inline bool areJTsAllowed(const TargetLowering &TLI) {
1763 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1764 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1765}
1766
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001767/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001768bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001769 CaseRecVector& WorkList,
1770 Value* SV,
1771 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001772 Case& FrontCase = *CR.Range.first;
1773 Case& BackCase = *(CR.Range.second-1);
1774
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001775 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1776 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1777
1778 uint64_t TSize = 0;
1779 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1780 I!=E; ++I)
1781 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001782
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001783 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001784 return false;
1785
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001786 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1787 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001788 return false;
1789
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001790 DOUT << "Lowering jump table\n"
1791 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001792 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001793
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001794 // Get the MachineFunction which holds the current MBB. This is used when
1795 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001796 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001797
1798 // Figure out which block is immediately after the current one.
1799 MachineBasicBlock *NextBlock = 0;
1800 MachineFunction::iterator BBI = CR.CaseBB;
1801
1802 if (++BBI != CurMBB->getParent()->end())
1803 NextBlock = BBI;
1804
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001805 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1806
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001807 // Create a new basic block to hold the code for loading the address
1808 // of the jump table, and jumping to it. Update successor information;
1809 // we will either branch to the default case for the switch, or the jump
1810 // table.
1811 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1812 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1813 CR.CaseBB->addSuccessor(Default);
1814 CR.CaseBB->addSuccessor(JumpTableBB);
1815
1816 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001817 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001818 // a case statement, push the case's BB onto the vector, otherwise, push
1819 // the default BB.
1820 std::vector<MachineBasicBlock*> DestBBs;
1821 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001822 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1823 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1824 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1825
1826 if ((Low <= TEI) && (TEI <= High)) {
1827 DestBBs.push_back(I->BB);
1828 if (TEI==High)
1829 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001830 } else {
1831 DestBBs.push_back(Default);
1832 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001833 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001834
1835 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001836 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001837 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1838 E = DestBBs.end(); I != E; ++I) {
1839 if (!SuccsHandled[(*I)->getNumber()]) {
1840 SuccsHandled[(*I)->getNumber()] = true;
1841 JumpTableBB->addSuccessor(*I);
1842 }
1843 }
1844
1845 // Create a jump table index for this jump table, or return an existing
1846 // one.
1847 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1848
1849 // Set the jump table information so that we can codegen it as a second
1850 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001851 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001852 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1853 (CR.CaseBB == CurMBB));
1854 if (CR.CaseBB == CurMBB)
1855 visitJumpTableHeader(JT, JTH);
1856
1857 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001858
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001859 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001860}
1861
1862/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1863/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001864bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001865 CaseRecVector& WorkList,
1866 Value* SV,
1867 MachineBasicBlock* Default) {
1868 // Get the MachineFunction which holds the current MBB. This is used when
1869 // inserting any additional MBBs necessary to represent the switch.
1870 MachineFunction *CurMF = CurMBB->getParent();
1871
1872 // Figure out which block is immediately after the current one.
1873 MachineBasicBlock *NextBlock = 0;
1874 MachineFunction::iterator BBI = CR.CaseBB;
1875
1876 if (++BBI != CurMBB->getParent()->end())
1877 NextBlock = BBI;
1878
1879 Case& FrontCase = *CR.Range.first;
1880 Case& BackCase = *(CR.Range.second-1);
1881 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1882
1883 // Size is the number of Cases represented by this range.
1884 unsigned Size = CR.Range.second - CR.Range.first;
1885
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001886 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1887 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001888 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001889 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001890
1891 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1892 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001893 uint64_t TSize = 0;
1894 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1895 I!=E; ++I)
1896 TSize += I->size();
1897
1898 uint64_t LSize = FrontCase.size();
1899 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001900 DOUT << "Selecting best pivot: \n"
1901 << "First: " << First << ", Last: " << Last <<"\n"
1902 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001903 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001904 J!=E; ++I, ++J) {
1905 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1906 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001907 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001908 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1909 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001910 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001911 // Should always split in some non-trivial place
1912 DOUT <<"=>Step\n"
1913 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1914 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1915 << "Metric: " << Metric << "\n";
1916 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001917 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001918 FMetric = Metric;
1919 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001920 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001921
1922 LSize += J->size();
1923 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001924 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001925 if (areJTsAllowed(TLI)) {
1926 // If our case is dense we *really* should handle it earlier!
1927 assert((FMetric > 0) && "Should handle dense range earlier!");
1928 } else {
1929 Pivot = CR.Range.first + Size/2;
1930 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001931
1932 CaseRange LHSR(CR.Range.first, Pivot);
1933 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001934 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001935 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1936
1937 // We know that we branch to the LHS if the Value being switched on is
1938 // less than the Pivot value, C. We use this to optimize our binary
1939 // tree a bit, by recognizing that if SV is greater than or equal to the
1940 // LHS's Case Value, and that Case Value is exactly one less than the
1941 // Pivot's Value, then we can branch directly to the LHS's Target,
1942 // rather than creating a leaf node for it.
1943 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001944 LHSR.first->High == CR.GE &&
1945 cast<ConstantInt>(C)->getSExtValue() ==
1946 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1947 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001948 } else {
1949 TrueBB = new MachineBasicBlock(LLVMBB);
1950 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1951 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1952 }
1953
1954 // Similar to the optimization above, if the Value being switched on is
1955 // known to be less than the Constant CR.LT, and the current Case Value
1956 // is CR.LT - 1, then we can branch directly to the target block for
1957 // the current Case Value, rather than emitting a RHS leaf node for it.
1958 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001959 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1960 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1961 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001962 } else {
1963 FalseBB = new MachineBasicBlock(LLVMBB);
1964 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1965 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1966 }
1967
1968 // Create a CaseBlock record representing a conditional branch to
1969 // the LHS node if the value being switched on SV is less than C.
1970 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001971 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1972 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001973
1974 if (CR.CaseBB == CurMBB)
1975 visitSwitchCase(CB);
1976 else
1977 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001978
1979 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001980}
1981
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001982/// handleBitTestsSwitchCase - if current case range has few destination and
1983/// range span less, than machine word bitwidth, encode case range into series
1984/// of masks and emit bit tests with these masks.
1985bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1986 CaseRecVector& WorkList,
1987 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001988 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001989 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001990
1991 Case& FrontCase = *CR.Range.first;
1992 Case& BackCase = *(CR.Range.second-1);
1993
1994 // Get the MachineFunction which holds the current MBB. This is used when
1995 // inserting any additional MBBs necessary to represent the switch.
1996 MachineFunction *CurMF = CurMBB->getParent();
1997
1998 unsigned numCmps = 0;
1999 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2000 I!=E; ++I) {
2001 // Single case counts one, case range - two.
2002 if (I->Low == I->High)
2003 numCmps +=1;
2004 else
2005 numCmps +=2;
2006 }
2007
2008 // Count unique destinations
2009 SmallSet<MachineBasicBlock*, 4> Dests;
2010 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2011 Dests.insert(I->BB);
2012 if (Dests.size() > 3)
2013 // Don't bother the code below, if there are too much unique destinations
2014 return false;
2015 }
2016 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2017 << "Total number of comparisons: " << numCmps << "\n";
2018
2019 // Compute span of values.
2020 Constant* minValue = FrontCase.Low;
2021 Constant* maxValue = BackCase.High;
2022 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2023 cast<ConstantInt>(minValue)->getSExtValue();
2024 DOUT << "Compare range: " << range << "\n"
2025 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2026 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2027
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002028 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002029 (!(Dests.size() == 1 && numCmps >= 3) &&
2030 !(Dests.size() == 2 && numCmps >= 5) &&
2031 !(Dests.size() >= 3 && numCmps >= 6)))
2032 return false;
2033
2034 DOUT << "Emitting bit tests\n";
2035 int64_t lowBound = 0;
2036
2037 // Optimize the case where all the case values fit in a
2038 // word without having to subtract minValue. In this case,
2039 // we can optimize away the subtraction.
2040 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002041 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002042 range = cast<ConstantInt>(maxValue)->getSExtValue();
2043 } else {
2044 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2045 }
2046
2047 CaseBitsVector CasesBits;
2048 unsigned i, count = 0;
2049
2050 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2051 MachineBasicBlock* Dest = I->BB;
2052 for (i = 0; i < count; ++i)
2053 if (Dest == CasesBits[i].BB)
2054 break;
2055
2056 if (i == count) {
2057 assert((count < 3) && "Too much destinations to test!");
2058 CasesBits.push_back(CaseBits(0, Dest, 0));
2059 count++;
2060 }
2061
2062 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2063 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2064
2065 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002066 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002067 CasesBits[i].Bits++;
2068 }
2069
2070 }
2071 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2072
2073 SelectionDAGISel::BitTestInfo BTC;
2074
2075 // Figure out which block is immediately after the current one.
2076 MachineFunction::iterator BBI = CR.CaseBB;
2077 ++BBI;
2078
2079 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2080
2081 DOUT << "Cases:\n";
2082 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2083 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2084 << ", BB: " << CasesBits[i].BB << "\n";
2085
2086 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2087 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2088 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2089 CaseBB,
2090 CasesBits[i].BB));
2091 }
2092
2093 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002094 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002095 CR.CaseBB, Default, BTC);
2096
2097 if (CR.CaseBB == CurMBB)
2098 visitBitTestHeader(BTB);
2099
2100 BitTestCases.push_back(BTB);
2101
2102 return true;
2103}
2104
2105
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002106/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002107unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2108 const SwitchInst& SI) {
2109 unsigned numCmps = 0;
2110
2111 // Start with "simple" cases
2112 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2113 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2114 Cases.push_back(Case(SI.getSuccessorValue(i),
2115 SI.getSuccessorValue(i),
2116 SMBB));
2117 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002118 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002119
2120 // Merge case into clusters
2121 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002122 // Must recompute end() each iteration because it may be
2123 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002124 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002125 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2126 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2127 MachineBasicBlock* nextBB = J->BB;
2128 MachineBasicBlock* currentBB = I->BB;
2129
2130 // If the two neighboring cases go to the same destination, merge them
2131 // into a single case.
2132 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2133 I->High = J->High;
2134 J = Cases.erase(J);
2135 } else {
2136 I = J++;
2137 }
2138 }
2139
2140 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2141 if (I->Low != I->High)
2142 // A range counts double, since it requires two compares.
2143 ++numCmps;
2144 }
2145
2146 return numCmps;
2147}
2148
2149void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002150 // Figure out which block is immediately after the current one.
2151 MachineBasicBlock *NextBlock = 0;
2152 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002153
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002154 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002155
Nate Begemanf15485a2006-03-27 01:32:24 +00002156 // If there is only the default destination, branch to it if it is not the
2157 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002158 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002159 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002160
Nate Begemanf15485a2006-03-27 01:32:24 +00002161 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002162 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002163 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002164 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002165
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002166 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002167 return;
2168 }
2169
2170 // If there are any non-default case statements, create a vector of Cases
2171 // representing each one, and sort the vector so that we can efficiently
2172 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002173 CaseVector Cases;
2174 unsigned numCmps = Clusterify(Cases, SI);
2175 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2176 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002177
Nate Begemanf15485a2006-03-27 01:32:24 +00002178 // Get the Value to be switched on and default basic blocks, which will be
2179 // inserted into CaseBlock records, representing basic blocks in the binary
2180 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002181 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002182
Nate Begemanf15485a2006-03-27 01:32:24 +00002183 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002184 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002185 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2186
2187 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002188 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002189 CaseRec CR = WorkList.back();
2190 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002191
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002192 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2193 continue;
2194
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002195 // If the range has few cases (two or less) emit a series of specific
2196 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002197 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2198 continue;
2199
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002200 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002201 // target supports indirect branches, then emit a jump table rather than
2202 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002203 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2204 continue;
2205
2206 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2207 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2208 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002209 }
2210}
2211
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002212
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002213void SelectionDAGLowering::visitSub(User &I) {
2214 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002215 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002216 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002217 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2218 const VectorType *DestTy = cast<VectorType>(I.getType());
2219 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002220 if (ElTy->isFloatingPoint()) {
2221 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002222 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002223 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2224 if (CV == CNZ) {
2225 SDOperand Op2 = getValue(I.getOperand(1));
2226 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2227 return;
2228 }
Dan Gohman7f321562007-06-25 16:23:39 +00002229 }
2230 }
2231 }
2232 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002234 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002235 SDOperand Op2 = getValue(I.getOperand(1));
2236 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2237 return;
2238 }
Dan Gohman7f321562007-06-25 16:23:39 +00002239 }
2240
2241 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002242}
2243
Dan Gohman7f321562007-06-25 16:23:39 +00002244void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002245 SDOperand Op1 = getValue(I.getOperand(0));
2246 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002247
2248 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002249}
2250
Nate Begemane21ea612005-11-18 07:42:56 +00002251void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2252 SDOperand Op1 = getValue(I.getOperand(0));
2253 SDOperand Op2 = getValue(I.getOperand(1));
2254
Dan Gohman7f321562007-06-25 16:23:39 +00002255 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2256 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002257 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2258 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2259 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002260
Chris Lattner1c08c712005-01-07 07:47:53 +00002261 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2262}
2263
Reid Spencer45fb3f32006-11-20 01:22:35 +00002264void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002265 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2266 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2267 predicate = IC->getPredicate();
2268 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2269 predicate = ICmpInst::Predicate(IC->getPredicate());
2270 SDOperand Op1 = getValue(I.getOperand(0));
2271 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002272 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002273 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002274 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2275 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2276 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2277 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2278 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2279 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2280 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2281 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2282 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2283 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2284 default:
2285 assert(!"Invalid ICmp predicate value");
2286 Opcode = ISD::SETEQ;
2287 break;
2288 }
2289 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2290}
2291
2292void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002293 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2294 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2295 predicate = FC->getPredicate();
2296 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2297 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002298 SDOperand Op1 = getValue(I.getOperand(0));
2299 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002300 ISD::CondCode Condition, FOC, FPC;
2301 switch (predicate) {
2302 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2303 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2304 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2305 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2306 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2307 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2308 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2309 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2310 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2311 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2312 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2313 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2314 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2315 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2316 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2317 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2318 default:
2319 assert(!"Invalid FCmp predicate value");
2320 FOC = FPC = ISD::SETFALSE;
2321 break;
2322 }
2323 if (FiniteOnlyFPMath())
2324 Condition = FOC;
2325 else
2326 Condition = FPC;
2327 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002328}
2329
2330void SelectionDAGLowering::visitSelect(User &I) {
2331 SDOperand Cond = getValue(I.getOperand(0));
2332 SDOperand TrueVal = getValue(I.getOperand(1));
2333 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002334 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2335 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002336}
2337
Reid Spencer3da59db2006-11-27 01:05:10 +00002338
2339void SelectionDAGLowering::visitTrunc(User &I) {
2340 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2341 SDOperand N = getValue(I.getOperand(0));
2342 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2343 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2344}
2345
2346void SelectionDAGLowering::visitZExt(User &I) {
2347 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2348 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2349 SDOperand N = getValue(I.getOperand(0));
2350 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2351 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2352}
2353
2354void SelectionDAGLowering::visitSExt(User &I) {
2355 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2356 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2357 SDOperand N = getValue(I.getOperand(0));
2358 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2359 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2360}
2361
2362void SelectionDAGLowering::visitFPTrunc(User &I) {
2363 // FPTrunc is never a no-op cast, no need to check
2364 SDOperand N = getValue(I.getOperand(0));
2365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002366 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002367}
2368
2369void SelectionDAGLowering::visitFPExt(User &I){
2370 // FPTrunc is never a no-op cast, no need to check
2371 SDOperand N = getValue(I.getOperand(0));
2372 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2373 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2374}
2375
2376void SelectionDAGLowering::visitFPToUI(User &I) {
2377 // FPToUI is never a no-op cast, no need to check
2378 SDOperand N = getValue(I.getOperand(0));
2379 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2380 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2381}
2382
2383void SelectionDAGLowering::visitFPToSI(User &I) {
2384 // FPToSI is never a no-op cast, no need to check
2385 SDOperand N = getValue(I.getOperand(0));
2386 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2387 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2388}
2389
2390void SelectionDAGLowering::visitUIToFP(User &I) {
2391 // UIToFP is never a no-op cast, no need to check
2392 SDOperand N = getValue(I.getOperand(0));
2393 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2394 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2395}
2396
2397void SelectionDAGLowering::visitSIToFP(User &I){
2398 // UIToFP is never a no-op cast, no need to check
2399 SDOperand N = getValue(I.getOperand(0));
2400 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2401 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2402}
2403
2404void SelectionDAGLowering::visitPtrToInt(User &I) {
2405 // What to do depends on the size of the integer and the size of the pointer.
2406 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002407 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002408 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002409 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002410 SDOperand Result;
2411 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2412 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2413 else
2414 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2415 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2416 setValue(&I, Result);
2417}
Chris Lattner1c08c712005-01-07 07:47:53 +00002418
Reid Spencer3da59db2006-11-27 01:05:10 +00002419void SelectionDAGLowering::visitIntToPtr(User &I) {
2420 // What to do depends on the size of the integer and the size of the pointer.
2421 // We can either truncate, zero extend, or no-op, accordingly.
2422 SDOperand N = getValue(I.getOperand(0));
2423 MVT::ValueType SrcVT = N.getValueType();
2424 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2425 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2426 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2427 else
2428 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2429 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2430}
2431
2432void SelectionDAGLowering::visitBitCast(User &I) {
2433 SDOperand N = getValue(I.getOperand(0));
2434 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002435
2436 // BitCast assures us that source and destination are the same size so this
2437 // is either a BIT_CONVERT or a no-op.
2438 if (DestVT != N.getValueType())
2439 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2440 else
2441 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002442}
2443
Chris Lattner2bbd8102006-03-29 00:11:43 +00002444void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002445 SDOperand InVec = getValue(I.getOperand(0));
2446 SDOperand InVal = getValue(I.getOperand(1));
2447 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2448 getValue(I.getOperand(2)));
2449
Dan Gohman7f321562007-06-25 16:23:39 +00002450 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2451 TLI.getValueType(I.getType()),
2452 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002453}
2454
Chris Lattner2bbd8102006-03-29 00:11:43 +00002455void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002456 SDOperand InVec = getValue(I.getOperand(0));
2457 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2458 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002460 TLI.getValueType(I.getType()), InVec, InIdx));
2461}
Chris Lattnerc7029802006-03-18 01:44:44 +00002462
Chris Lattner3e104b12006-04-08 04:15:24 +00002463void SelectionDAGLowering::visitShuffleVector(User &I) {
2464 SDOperand V1 = getValue(I.getOperand(0));
2465 SDOperand V2 = getValue(I.getOperand(1));
2466 SDOperand Mask = getValue(I.getOperand(2));
2467
Dan Gohman7f321562007-06-25 16:23:39 +00002468 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2469 TLI.getValueType(I.getType()),
2470 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002471}
2472
2473
Chris Lattner1c08c712005-01-07 07:47:53 +00002474void SelectionDAGLowering::visitGetElementPtr(User &I) {
2475 SDOperand N = getValue(I.getOperand(0));
2476 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002477
2478 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2479 OI != E; ++OI) {
2480 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002481 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002482 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002483 if (Field) {
2484 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002485 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002486 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002487 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002488 }
2489 Ty = StTy->getElementType(Field);
2490 } else {
2491 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002492
Chris Lattner7c0104b2005-11-09 04:45:33 +00002493 // If this is a constant subscript, handle it quickly.
2494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002495 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002496 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002497 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002498 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2499 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002500 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002501 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002502
2503 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002504 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002505 SDOperand IdxN = getValue(Idx);
2506
2507 // If the index is smaller or larger than intptr_t, truncate or extend
2508 // it.
2509 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002510 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002511 } else if (IdxN.getValueType() > N.getValueType())
2512 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2513
2514 // If this is a multiply by a power of two, turn it into a shl
2515 // immediately. This is a very common case.
2516 if (isPowerOf2_64(ElementSize)) {
2517 unsigned Amt = Log2_64(ElementSize);
2518 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002519 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002520 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2521 continue;
2522 }
2523
Chris Lattner0bd48932008-01-17 07:00:52 +00002524 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002525 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2526 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002527 }
2528 }
2529 setValue(&I, N);
2530}
2531
2532void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2533 // If this is a fixed sized alloca in the entry block of the function,
2534 // allocate it statically on the stack.
2535 if (FuncInfo.StaticAllocaMap.count(&I))
2536 return; // getValue will auto-populate this.
2537
2538 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002539 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002540 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002541 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002542 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002543
2544 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002545 MVT::ValueType IntPtr = TLI.getPointerTy();
2546 if (IntPtr < AllocSize.getValueType())
2547 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2548 else if (IntPtr > AllocSize.getValueType())
2549 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002550
Chris Lattner68cd65e2005-01-22 23:04:37 +00002551 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002552 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002553
Evan Cheng45157792007-08-16 23:46:29 +00002554 // Handle alignment. If the requested alignment is less than or equal to
2555 // the stack alignment, ignore it. If the size is greater than or equal to
2556 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002557 unsigned StackAlign =
2558 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002559 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002560 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002561
2562 // Round the size of the allocation up to the stack alignment size
2563 // by add SA-1 to the size.
2564 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002565 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002566 // Mask out the low bits for alignment purposes.
2567 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002568 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002569
Chris Lattner0bd48932008-01-17 07:00:52 +00002570 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002571 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2572 MVT::Other);
2573 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002574 setValue(&I, DSA);
2575 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002576
2577 // Inform the Frame Information that we have just allocated a variable-sized
2578 // object.
2579 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2580}
2581
Chris Lattner1c08c712005-01-07 07:47:53 +00002582void SelectionDAGLowering::visitLoad(LoadInst &I) {
2583 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002584
Chris Lattnerd3948112005-01-17 22:19:26 +00002585 SDOperand Root;
2586 if (I.isVolatile())
2587 Root = getRoot();
2588 else {
2589 // Do not serialize non-volatile loads against each other.
2590 Root = DAG.getRoot();
2591 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002592
Evan Cheng466685d2006-10-09 20:57:25 +00002593 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002594 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002595}
2596
2597SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002598 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002599 bool isVolatile,
2600 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002601 SDOperand L =
2602 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2603 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002604
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002605 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002606 DAG.setRoot(L.getValue(1));
2607 else
2608 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002609
2610 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002611}
2612
2613
2614void SelectionDAGLowering::visitStore(StoreInst &I) {
2615 Value *SrcV = I.getOperand(0);
2616 SDOperand Src = getValue(SrcV);
2617 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002618 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002619 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002620}
2621
Chris Lattner0eade312006-03-24 02:22:33 +00002622/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2623/// node.
2624void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2625 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002626 bool HasChain = !I.doesNotAccessMemory();
2627 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2628
Chris Lattner0eade312006-03-24 02:22:33 +00002629 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002630 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002631 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2632 if (OnlyLoad) {
2633 // We don't need to serialize loads against other loads.
2634 Ops.push_back(DAG.getRoot());
2635 } else {
2636 Ops.push_back(getRoot());
2637 }
2638 }
Chris Lattner0eade312006-03-24 02:22:33 +00002639
2640 // Add the intrinsic ID as an integer operand.
2641 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2642
2643 // Add all operands of the call to the operand list.
2644 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2645 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002646 assert(TLI.isTypeLegal(Op.getValueType()) &&
2647 "Intrinsic uses a non-legal type?");
2648 Ops.push_back(Op);
2649 }
2650
2651 std::vector<MVT::ValueType> VTs;
2652 if (I.getType() != Type::VoidTy) {
2653 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002654 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002655 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002656 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2657
2658 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2659 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2660 }
2661
2662 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2663 VTs.push_back(VT);
2664 }
2665 if (HasChain)
2666 VTs.push_back(MVT::Other);
2667
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002668 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2669
Chris Lattner0eade312006-03-24 02:22:33 +00002670 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002671 SDOperand Result;
2672 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002673 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2674 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002675 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002676 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2677 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002678 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002679 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2680 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002681
Chris Lattnere58a7802006-04-02 03:41:14 +00002682 if (HasChain) {
2683 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2684 if (OnlyLoad)
2685 PendingLoads.push_back(Chain);
2686 else
2687 DAG.setRoot(Chain);
2688 }
Chris Lattner0eade312006-03-24 02:22:33 +00002689 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002690 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002691 MVT::ValueType VT = TLI.getValueType(PTy);
2692 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002693 }
2694 setValue(&I, Result);
2695 }
2696}
2697
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002698/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002699static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002700 V = IntrinsicInst::StripPointerCasts(V);
2701 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002702 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002703 "TypeInfo must be a global variable or NULL");
2704 return GV;
2705}
2706
Duncan Sandsf4070822007-06-15 19:04:19 +00002707/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002708/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002709static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2710 MachineBasicBlock *MBB) {
2711 // Inform the MachineModuleInfo of the personality for this landing pad.
2712 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2713 assert(CE->getOpcode() == Instruction::BitCast &&
2714 isa<Function>(CE->getOperand(0)) &&
2715 "Personality should be a function");
2716 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2717
2718 // Gather all the type infos for this landing pad and pass them along to
2719 // MachineModuleInfo.
2720 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002721 unsigned N = I.getNumOperands();
2722
2723 for (unsigned i = N - 1; i > 2; --i) {
2724 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2725 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002726 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002727 assert (FirstCatch <= N && "Invalid filter length");
2728
2729 if (FirstCatch < N) {
2730 TyInfo.reserve(N - FirstCatch);
2731 for (unsigned j = FirstCatch; j < N; ++j)
2732 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2733 MMI->addCatchTypeInfo(MBB, TyInfo);
2734 TyInfo.clear();
2735 }
2736
Duncan Sands6590b042007-08-27 15:47:50 +00002737 if (!FilterLength) {
2738 // Cleanup.
2739 MMI->addCleanup(MBB);
2740 } else {
2741 // Filter.
2742 TyInfo.reserve(FilterLength - 1);
2743 for (unsigned j = i + 1; j < FirstCatch; ++j)
2744 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2745 MMI->addFilterTypeInfo(MBB, TyInfo);
2746 TyInfo.clear();
2747 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002748
2749 N = i;
2750 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002751 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002752
2753 if (N > 3) {
2754 TyInfo.reserve(N - 3);
2755 for (unsigned j = 3; j < N; ++j)
2756 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002757 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002758 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002759}
2760
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002761/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2762/// we want to emit this as a call to a named external function, return the name
2763/// otherwise lower it and return null.
2764const char *
2765SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2766 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002767 default:
2768 // By default, turn this into a target intrinsic node.
2769 visitTargetIntrinsic(I, Intrinsic);
2770 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002771 case Intrinsic::vastart: visitVAStart(I); return 0;
2772 case Intrinsic::vaend: visitVAEnd(I); return 0;
2773 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002774 case Intrinsic::returnaddress:
2775 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2776 getValue(I.getOperand(1))));
2777 return 0;
2778 case Intrinsic::frameaddress:
2779 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2780 getValue(I.getOperand(1))));
2781 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002782 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002783 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002784 break;
2785 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002786 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002787 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002788 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002789 case Intrinsic::memcpy_i64: {
2790 SDOperand Op1 = getValue(I.getOperand(1));
2791 SDOperand Op2 = getValue(I.getOperand(2));
2792 SDOperand Op3 = getValue(I.getOperand(3));
2793 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2794 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2795 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002796 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002797 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002798 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002799 case Intrinsic::memset_i64: {
2800 SDOperand Op1 = getValue(I.getOperand(1));
2801 SDOperand Op2 = getValue(I.getOperand(2));
2802 SDOperand Op3 = getValue(I.getOperand(3));
2803 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2804 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2805 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002806 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002807 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002808 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002809 case Intrinsic::memmove_i64: {
2810 SDOperand Op1 = getValue(I.getOperand(1));
2811 SDOperand Op2 = getValue(I.getOperand(2));
2812 SDOperand Op3 = getValue(I.getOperand(3));
2813 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2814
2815 // If the source and destination are known to not be aliases, we can
2816 // lower memmove as memcpy.
2817 uint64_t Size = -1ULL;
2818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2819 Size = C->getValue();
2820 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2821 AliasAnalysis::NoAlias) {
2822 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2823 I.getOperand(1), 0, I.getOperand(2), 0));
2824 return 0;
2825 }
2826
2827 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2828 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002829 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002830 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002831 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002832 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002833 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002834 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002835 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002836
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002837 Ops[0] = getRoot();
2838 Ops[1] = getValue(SPI.getLineValue());
2839 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002840
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002841 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002842 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002843 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2844
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002845 Ops[3] = DAG.getString(CompileUnit->getFileName());
2846 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002847
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002848 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002849 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002850
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002851 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002852 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002853 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002854 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002855 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002856 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2857 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002858 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002859 DAG.getConstant(LabelID, MVT::i32),
2860 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002861 }
2862
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002863 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002864 }
2865 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002866 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002867 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002868 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2869 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002870 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2871 DAG.getConstant(LabelID, MVT::i32),
2872 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002873 }
2874
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002875 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002876 }
2877 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002878 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002879 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002880 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002881 Value *SP = FSI.getSubprogram();
2882 if (SP && MMI->Verify(SP)) {
2883 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2884 // what (most?) gdb expects.
2885 DebugInfoDesc *DD = MMI->getDescFor(SP);
2886 assert(DD && "Not a debug information descriptor");
2887 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2888 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2889 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2890 CompileUnit->getFileName());
2891 // Record the source line but does create a label. It will be emitted
2892 // at asm emission time.
2893 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002894 }
2895
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002896 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002897 }
2898 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002899 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002900 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002901 Value *Variable = DI.getVariable();
2902 if (MMI && Variable && MMI->Verify(Variable))
2903 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2904 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002905 return 0;
2906 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002907
Jim Laskeyb180aa12007-02-21 22:53:45 +00002908 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002909 if (!CurMBB->isLandingPad()) {
2910 // FIXME: Mark exception register as live in. Hack for PR1508.
2911 unsigned Reg = TLI.getExceptionAddressRegister();
2912 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00002913 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002914 // Insert the EXCEPTIONADDR instruction.
2915 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2916 SDOperand Ops[1];
2917 Ops[0] = DAG.getRoot();
2918 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2919 setValue(&I, Op);
2920 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002921 return 0;
2922 }
2923
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002924 case Intrinsic::eh_selector_i32:
2925 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002926 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002927 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2928 MVT::i32 : MVT::i64);
2929
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002930 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002931 if (CurMBB->isLandingPad())
2932 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002933 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002934#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002935 FuncInfo.CatchInfoLost.insert(&I);
2936#endif
Duncan Sands90291952007-07-06 09:18:59 +00002937 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2938 unsigned Reg = TLI.getExceptionSelectorRegister();
2939 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002940 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002941
2942 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002943 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002944 SDOperand Ops[2];
2945 Ops[0] = getValue(I.getOperand(1));
2946 Ops[1] = getRoot();
2947 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2948 setValue(&I, Op);
2949 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002950 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002951 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002952 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002953
2954 return 0;
2955 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002956
2957 case Intrinsic::eh_typeid_for_i32:
2958 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002959 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002960 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2961 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002962
Jim Laskey735b6f82007-02-22 15:38:06 +00002963 if (MMI) {
2964 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002965 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002966
Jim Laskey735b6f82007-02-22 15:38:06 +00002967 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002968 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00002969 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002970 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002971 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002972 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002973
2974 return 0;
2975 }
2976
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002977 case Intrinsic::eh_return: {
2978 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2979
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002980 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002981 MMI->setCallsEHReturn(true);
2982 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2983 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002984 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002985 getValue(I.getOperand(1)),
2986 getValue(I.getOperand(2))));
2987 } else {
2988 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2989 }
2990
2991 return 0;
2992 }
2993
2994 case Intrinsic::eh_unwind_init: {
2995 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2996 MMI->setCallsUnwindInit(true);
2997 }
2998
2999 return 0;
3000 }
3001
3002 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003003 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3004 SDOperand CfaArg;
3005 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3006 CfaArg = DAG.getNode(ISD::TRUNCATE,
3007 TLI.getPointerTy(), getValue(I.getOperand(1)));
3008 else
3009 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3010 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003011
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003012 SDOperand Offset = DAG.getNode(ISD::ADD,
3013 TLI.getPointerTy(),
3014 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3015 TLI.getPointerTy()),
3016 CfaArg);
3017 setValue(&I, DAG.getNode(ISD::ADD,
3018 TLI.getPointerTy(),
3019 DAG.getNode(ISD::FRAMEADDR,
3020 TLI.getPointerTy(),
3021 DAG.getConstant(0,
3022 TLI.getPointerTy())),
3023 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003024 return 0;
3025 }
3026
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003027 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003028 setValue(&I, DAG.getNode(ISD::FSQRT,
3029 getValue(I.getOperand(1)).getValueType(),
3030 getValue(I.getOperand(1))));
3031 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003032 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003033 setValue(&I, DAG.getNode(ISD::FPOWI,
3034 getValue(I.getOperand(1)).getValueType(),
3035 getValue(I.getOperand(1)),
3036 getValue(I.getOperand(2))));
3037 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003038 case Intrinsic::sin:
3039 setValue(&I, DAG.getNode(ISD::FSIN,
3040 getValue(I.getOperand(1)).getValueType(),
3041 getValue(I.getOperand(1))));
3042 return 0;
3043 case Intrinsic::cos:
3044 setValue(&I, DAG.getNode(ISD::FCOS,
3045 getValue(I.getOperand(1)).getValueType(),
3046 getValue(I.getOperand(1))));
3047 return 0;
3048 case Intrinsic::pow:
3049 setValue(&I, DAG.getNode(ISD::FPOW,
3050 getValue(I.getOperand(1)).getValueType(),
3051 getValue(I.getOperand(1)),
3052 getValue(I.getOperand(2))));
3053 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003054 case Intrinsic::pcmarker: {
3055 SDOperand Tmp = getValue(I.getOperand(1));
3056 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3057 return 0;
3058 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003059 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003060 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003061 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3062 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3063 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003064 setValue(&I, Tmp);
3065 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003066 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003067 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003068 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003069 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003070 assert(0 && "part_select intrinsic not implemented");
3071 abort();
3072 }
3073 case Intrinsic::part_set: {
3074 // Currently not implemented: just abort
3075 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003076 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003077 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003078 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003079 setValue(&I, DAG.getNode(ISD::BSWAP,
3080 getValue(I.getOperand(1)).getValueType(),
3081 getValue(I.getOperand(1))));
3082 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003083 case Intrinsic::cttz: {
3084 SDOperand Arg = getValue(I.getOperand(1));
3085 MVT::ValueType Ty = Arg.getValueType();
3086 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003087 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003088 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003089 }
3090 case Intrinsic::ctlz: {
3091 SDOperand Arg = getValue(I.getOperand(1));
3092 MVT::ValueType Ty = Arg.getValueType();
3093 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003094 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003095 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003096 }
3097 case Intrinsic::ctpop: {
3098 SDOperand Arg = getValue(I.getOperand(1));
3099 MVT::ValueType Ty = Arg.getValueType();
3100 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003101 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003102 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003103 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003104 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003105 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003106 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3107 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003108 setValue(&I, Tmp);
3109 DAG.setRoot(Tmp.getValue(1));
3110 return 0;
3111 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003112 case Intrinsic::stackrestore: {
3113 SDOperand Tmp = getValue(I.getOperand(1));
3114 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003115 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003116 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003117 case Intrinsic::var_annotation:
3118 // Discard annotate attributes
3119 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003120
Duncan Sands36397f52007-07-27 12:58:54 +00003121 case Intrinsic::init_trampoline: {
3122 const Function *F =
3123 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3124
3125 SDOperand Ops[6];
3126 Ops[0] = getRoot();
3127 Ops[1] = getValue(I.getOperand(1));
3128 Ops[2] = getValue(I.getOperand(2));
3129 Ops[3] = getValue(I.getOperand(3));
3130 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3131 Ops[5] = DAG.getSrcValue(F);
3132
Duncan Sandsf7331b32007-09-11 14:10:23 +00003133 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3134 DAG.getNodeValueTypes(TLI.getPointerTy(),
3135 MVT::Other), 2,
3136 Ops, 6);
3137
3138 setValue(&I, Tmp);
3139 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003140 return 0;
3141 }
Gordon Henriksence224772008-01-07 01:30:38 +00003142
3143 case Intrinsic::gcroot:
3144 if (GCI) {
3145 Value *Alloca = I.getOperand(1);
3146 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3147
3148 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3149 GCI->addStackRoot(FI->getIndex(), TypeMap);
3150 }
3151 return 0;
3152
3153 case Intrinsic::gcread:
3154 case Intrinsic::gcwrite:
3155 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3156 return 0;
3157
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003158 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003159 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003160 return 0;
3161 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003162
3163 case Intrinsic::trap: {
3164 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3165 return 0;
3166 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003167 case Intrinsic::prefetch: {
3168 SDOperand Ops[4];
3169 Ops[0] = getRoot();
3170 Ops[1] = getValue(I.getOperand(1));
3171 Ops[2] = getValue(I.getOperand(2));
3172 Ops[3] = getValue(I.getOperand(3));
3173 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3174 return 0;
3175 }
3176
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003177 case Intrinsic::memory_barrier: {
3178 SDOperand Ops[6];
3179 Ops[0] = getRoot();
3180 for (int x = 1; x < 6; ++x)
3181 Ops[x] = getValue(I.getOperand(x));
3182
3183 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3184 return 0;
3185 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003186 case Intrinsic::atomic_lcs: {
3187 SDOperand Root = getRoot();
3188 SDOperand O3 = getValue(I.getOperand(3));
3189 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3190 getValue(I.getOperand(1)),
3191 getValue(I.getOperand(2)),
3192 O3, O3.getValueType());
3193 setValue(&I, L);
3194 DAG.setRoot(L.getValue(1));
3195 return 0;
3196 }
3197 case Intrinsic::atomic_las: {
3198 SDOperand Root = getRoot();
3199 SDOperand O2 = getValue(I.getOperand(2));
3200 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3201 getValue(I.getOperand(1)),
3202 O2, O2.getValueType());
3203 setValue(&I, L);
3204 DAG.setRoot(L.getValue(1));
3205 return 0;
3206 }
3207 case Intrinsic::atomic_swap: {
3208 SDOperand Root = getRoot();
3209 SDOperand O2 = getValue(I.getOperand(2));
3210 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3211 getValue(I.getOperand(1)),
3212 O2, O2.getValueType());
3213 setValue(&I, L);
3214 DAG.setRoot(L.getValue(1));
3215 return 0;
3216 }
3217
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003218 }
3219}
3220
3221
Duncan Sands6f74b482007-12-19 09:48:52 +00003222void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003223 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003224 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003225 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003226 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003227 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3228 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003229
Jim Laskey735b6f82007-02-22 15:38:06 +00003230 TargetLowering::ArgListTy Args;
3231 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003232 Args.reserve(CS.arg_size());
3233 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3234 i != e; ++i) {
3235 SDOperand ArgNode = getValue(*i);
3236 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003237
Duncan Sands6f74b482007-12-19 09:48:52 +00003238 unsigned attrInd = i - CS.arg_begin() + 1;
3239 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3240 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3241 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3242 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3243 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3244 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003245 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003246 Args.push_back(Entry);
3247 }
3248
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003249 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003250 // Insert a label before the invoke call to mark the try range. This can be
3251 // used to detect deletion of the invoke via the MachineModuleInfo.
3252 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003253 // Both PendingLoads and PendingExports must be flushed here;
3254 // this call might not return.
3255 (void)getRoot();
3256 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003257 DAG.getConstant(BeginLabel, MVT::i32),
3258 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003259 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003260
Jim Laskey735b6f82007-02-22 15:38:06 +00003261 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003262 TLI.LowerCallTo(getRoot(), CS.getType(),
3263 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003264 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003265 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003266 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003267 if (CS.getType() != Type::VoidTy)
3268 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003269 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003270
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003271 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003272 // Insert a label at the end of the invoke call to mark the try range. This
3273 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3274 EndLabel = MMI->NextLabelID();
3275 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003276 DAG.getConstant(EndLabel, MVT::i32),
3277 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003278
Duncan Sands6f74b482007-12-19 09:48:52 +00003279 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003280 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3281 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003282}
3283
3284
Chris Lattner1c08c712005-01-07 07:47:53 +00003285void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003286 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003287 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003288 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003289 if (unsigned IID = F->getIntrinsicID()) {
3290 RenameFn = visitIntrinsicCall(I, IID);
3291 if (!RenameFn)
3292 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003293 }
3294 }
3295
3296 // Check for well-known libc/libm calls. If the function is internal, it
3297 // can't be a library call.
3298 unsigned NameLen = F->getNameLen();
3299 if (!F->hasInternalLinkage() && NameLen) {
3300 const char *NameStr = F->getNameStart();
3301 if (NameStr[0] == 'c' &&
3302 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3303 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3304 if (I.getNumOperands() == 3 && // Basic sanity checks.
3305 I.getOperand(1)->getType()->isFloatingPoint() &&
3306 I.getType() == I.getOperand(1)->getType() &&
3307 I.getType() == I.getOperand(2)->getType()) {
3308 SDOperand LHS = getValue(I.getOperand(1));
3309 SDOperand RHS = getValue(I.getOperand(2));
3310 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3311 LHS, RHS));
3312 return;
3313 }
3314 } else if (NameStr[0] == 'f' &&
3315 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003316 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3317 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003318 if (I.getNumOperands() == 2 && // Basic sanity checks.
3319 I.getOperand(1)->getType()->isFloatingPoint() &&
3320 I.getType() == I.getOperand(1)->getType()) {
3321 SDOperand Tmp = getValue(I.getOperand(1));
3322 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3323 return;
3324 }
3325 } else if (NameStr[0] == 's' &&
3326 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003327 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3328 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003329 if (I.getNumOperands() == 2 && // Basic sanity checks.
3330 I.getOperand(1)->getType()->isFloatingPoint() &&
3331 I.getType() == I.getOperand(1)->getType()) {
3332 SDOperand Tmp = getValue(I.getOperand(1));
3333 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3334 return;
3335 }
3336 } else if (NameStr[0] == 'c' &&
3337 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003338 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3339 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003340 if (I.getNumOperands() == 2 && // Basic sanity checks.
3341 I.getOperand(1)->getType()->isFloatingPoint() &&
3342 I.getType() == I.getOperand(1)->getType()) {
3343 SDOperand Tmp = getValue(I.getOperand(1));
3344 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3345 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003346 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003347 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003348 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003349 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003350 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003351 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003352 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003353
Chris Lattner64e14b12005-01-08 22:48:57 +00003354 SDOperand Callee;
3355 if (!RenameFn)
3356 Callee = getValue(I.getOperand(0));
3357 else
3358 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003359
Duncan Sands6f74b482007-12-19 09:48:52 +00003360 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003361}
3362
Jim Laskey735b6f82007-02-22 15:38:06 +00003363
Dan Gohmanef5d1942008-03-11 21:11:25 +00003364void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003365 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003366 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3367 setValue(&I, Undef);
3368 } else {
3369 SDOperand Call = getValue(I.getOperand(0));
Dan Gohman23ce5022008-04-25 18:27:55 +00003370
3371 // To add support for individual return values with aggregate types,
3372 // we'd need a way to take a getresult index and determine which
3373 // values of the Call SDNode are associated with it.
3374 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3375 "Individual return values must not be aggregates!");
3376
Dan Gohman3dc34f62008-04-23 20:21:29 +00003377 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3378 }
Dan Gohmanef5d1942008-03-11 21:11:25 +00003379}
3380
3381
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003382/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3383/// this value and returns the result as a ValueVT value. This uses
3384/// Chain/Flag as the input and updates them for the output Chain/Flag.
3385/// If the Flag pointer is NULL, no flag is used.
3386SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3387 SDOperand &Chain, SDOperand *Flag)const{
Dan Gohman23ce5022008-04-25 18:27:55 +00003388 // Assemble the legal parts into the final values.
3389 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3390 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3391 // Copy the legal parts from the registers.
3392 MVT::ValueType ValueVT = ValueVTs[Value];
3393 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3394 MVT::ValueType RegisterVT = RegVTs[Value];
3395
3396 SmallVector<SDOperand, 8> Parts(NumRegs);
3397 for (unsigned i = 0; i != NumRegs; ++i) {
3398 SDOperand P = Flag ?
3399 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag) :
3400 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3401 Chain = P.getValue(1);
3402 if (Flag)
3403 *Flag = P.getValue(2);
3404 Parts[Part+i] = P;
3405 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003406
Dan Gohman23ce5022008-04-25 18:27:55 +00003407 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3408 ValueVT);
3409 Part += NumRegs;
3410 }
3411 return DAG.getNode(ISD::MERGE_VALUES,
3412 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3413 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003414}
3415
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003416/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3417/// specified value into the registers specified by this object. This uses
3418/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003419/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003420void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003421 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003422 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003423 unsigned NumRegs = Regs.size();
3424 SmallVector<SDOperand, 8> Parts(NumRegs);
3425 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3426 MVT::ValueType ValueVT = ValueVTs[Value];
3427 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3428 MVT::ValueType RegisterVT = RegVTs[Value];
3429
3430 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3431 &Parts[Part], NumParts, RegisterVT);
3432 Part += NumParts;
3433 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003434
3435 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003436 SmallVector<SDOperand, 8> Chains(NumRegs);
3437 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003438 SDOperand Part = Flag ?
Dan Gohman532dc2e2007-07-09 20:59:04 +00003439 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3440 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003441 Chains[i] = Part.getValue(0);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003442 if (Flag)
3443 *Flag = Part.getValue(1);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003444 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003445 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003446}
Chris Lattner864635a2006-02-22 22:37:12 +00003447
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003448/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3449/// operand list. This adds the code marker and includes the number of
3450/// values added into it.
3451void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003452 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003453 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3454 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Dan Gohman23ce5022008-04-25 18:27:55 +00003455 for (unsigned Value = 0, Reg = 0; Value != ValueVTs.size(); ++Value) {
3456 MVT::ValueType ValueVT = ValueVTs[Value];
3457 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3458 MVT::ValueType RegisterVT = RegVTs[Value];
3459 for (unsigned i = 0; i != NumRegs; ++i) {
3460 SDOperand RegOp = DAG.getRegister(Regs[Reg+i], RegisterVT);
3461 Ops.push_back(RegOp);
3462 }
3463 Reg += NumRegs;
3464 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003465}
Chris Lattner864635a2006-02-22 22:37:12 +00003466
3467/// isAllocatableRegister - If the specified register is safe to allocate,
3468/// i.e. it isn't a stack pointer or some other special register, return the
3469/// register class for the register. Otherwise, return null.
3470static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003471isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003472 const TargetLowering &TLI,
3473 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003474 MVT::ValueType FoundVT = MVT::Other;
3475 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003476 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3477 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003478 MVT::ValueType ThisVT = MVT::Other;
3479
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003480 const TargetRegisterClass *RC = *RCI;
3481 // If none of the the value types for this register class are valid, we
3482 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003483 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3484 I != E; ++I) {
3485 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003486 // If we have already found this register in a different register class,
3487 // choose the one with the largest VT specified. For example, on
3488 // PowerPC, we favor f64 register classes over f32.
3489 if (FoundVT == MVT::Other ||
3490 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3491 ThisVT = *I;
3492 break;
3493 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003494 }
3495 }
3496
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003497 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003498
Chris Lattner864635a2006-02-22 22:37:12 +00003499 // NOTE: This isn't ideal. In particular, this might allocate the
3500 // frame pointer in functions that need it (due to them not being taken
3501 // out of allocation, because a variable sized allocation hasn't been seen
3502 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003503 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3504 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003505 if (*I == Reg) {
3506 // We found a matching register class. Keep looking at others in case
3507 // we find one with larger registers that this physreg is also in.
3508 FoundRC = RC;
3509 FoundVT = ThisVT;
3510 break;
3511 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003512 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003513 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003514}
3515
Chris Lattner4e4b5762006-02-01 18:59:47 +00003516
Chris Lattner0c583402007-04-28 20:49:53 +00003517namespace {
3518/// AsmOperandInfo - This contains information for each constraint that we are
3519/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003520struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3521 /// CallOperand - If this is the result output operand or a clobber
3522 /// this is null, otherwise it is the incoming operand to the CallInst.
3523 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003524 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003525
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003526 /// AssignedRegs - If this is a register or register class operand, this
3527 /// contains the set of register corresponding to the operand.
3528 RegsForValue AssignedRegs;
3529
Dan Gohman23ce5022008-04-25 18:27:55 +00003530 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003531 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003532 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003533
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003534 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3535 /// busy in OutputRegs/InputRegs.
3536 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3537 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003538 std::set<unsigned> &InputRegs,
3539 const TargetRegisterInfo &TRI) const {
3540 if (isOutReg) {
3541 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3542 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3543 }
3544 if (isInReg) {
3545 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3546 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3547 }
3548 }
3549
3550private:
3551 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3552 /// specified set.
3553 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3554 const TargetRegisterInfo &TRI) {
3555 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3556 Regs.insert(Reg);
3557 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3558 for (; *Aliases; ++Aliases)
3559 Regs.insert(*Aliases);
3560 }
Chris Lattner0c583402007-04-28 20:49:53 +00003561};
3562} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003563
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003564
Chris Lattner0fe71e92008-02-21 19:43:13 +00003565/// GetRegistersForValue - Assign registers (virtual or physical) for the
3566/// specified operand. We prefer to assign virtual registers, to allow the
3567/// register allocator handle the assignment process. However, if the asm uses
3568/// features that we can't model on machineinstrs, we have SDISel do the
3569/// allocation. This produces generally horrible, but correct, code.
3570///
3571/// OpInfo describes the operand.
3572/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3573/// or any explicitly clobbered registers.
3574/// Input and OutputRegs are the set of already allocated physical registers.
3575///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003576void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003577GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003578 std::set<unsigned> &OutputRegs,
3579 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003580 // Compute whether this value requires an input register, an output register,
3581 // or both.
3582 bool isOutReg = false;
3583 bool isInReg = false;
3584 switch (OpInfo.Type) {
3585 case InlineAsm::isOutput:
3586 isOutReg = true;
3587
3588 // If this is an early-clobber output, or if there is an input
3589 // constraint that matches this, we need to reserve the input register
3590 // so no other inputs allocate to it.
3591 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3592 break;
3593 case InlineAsm::isInput:
3594 isInReg = true;
3595 isOutReg = false;
3596 break;
3597 case InlineAsm::isClobber:
3598 isOutReg = true;
3599 isInReg = true;
3600 break;
3601 }
3602
3603
3604 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003605 std::vector<unsigned> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003606
3607 // If this is a constraint for a single physreg, or a constraint for a
3608 // register class, find it.
3609 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3610 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3611 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003612
3613 unsigned NumRegs = 1;
3614 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003615 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003616 MVT::ValueType RegVT;
3617 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3618
Chris Lattnerbf996f12007-04-30 17:29:31 +00003619
3620 // If this is a constraint for a specific physical register, like {r17},
3621 // assign it now.
3622 if (PhysReg.first) {
3623 if (OpInfo.ConstraintVT == MVT::Other)
3624 ValueVT = *PhysReg.second->vt_begin();
3625
3626 // Get the actual register value type. This is important, because the user
3627 // may have asked for (e.g.) the AX register in i32 type. We need to
3628 // remember that AX is actually i16 to get the right extension.
3629 RegVT = *PhysReg.second->vt_begin();
3630
3631 // This is a explicit reference to a physical register.
3632 Regs.push_back(PhysReg.first);
3633
3634 // If this is an expanded reference, add the rest of the regs to Regs.
3635 if (NumRegs != 1) {
3636 TargetRegisterClass::iterator I = PhysReg.second->begin();
3637 TargetRegisterClass::iterator E = PhysReg.second->end();
3638 for (; *I != PhysReg.first; ++I)
3639 assert(I != E && "Didn't find reg!");
3640
3641 // Already added the first reg.
3642 --NumRegs; ++I;
3643 for (; NumRegs; --NumRegs, ++I) {
3644 assert(I != E && "Ran out of registers to allocate!");
3645 Regs.push_back(*I);
3646 }
3647 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003648 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003649 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3650 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003651 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003652 }
3653
3654 // Otherwise, if this was a reference to an LLVM register class, create vregs
3655 // for this reference.
3656 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003657 const TargetRegisterClass *RC = PhysReg.second;
3658 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003659 // If this is an early clobber or tied register, our regalloc doesn't know
3660 // how to maintain the constraint. If it isn't, go ahead and create vreg
3661 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003662 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3663 // If there is some other early clobber and this is an input register,
3664 // then we are forced to pre-allocate the input reg so it doesn't
3665 // conflict with the earlyclobber.
3666 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003667 RegVT = *PhysReg.second->vt_begin();
3668
3669 if (OpInfo.ConstraintVT == MVT::Other)
3670 ValueVT = RegVT;
3671
3672 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003673 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003674 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003675 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003676
Dan Gohman23ce5022008-04-25 18:27:55 +00003677 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003678 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003679 }
3680
3681 // Otherwise, we can't allocate it. Let the code below figure out how to
3682 // maintain these constraints.
3683 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3684
3685 } else {
3686 // This is a reference to a register class that doesn't directly correspond
3687 // to an LLVM register class. Allocate NumRegs consecutive, available,
3688 // registers from the class.
3689 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3690 OpInfo.ConstraintVT);
3691 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003692
Dan Gohman6f0d0242008-02-10 18:45:23 +00003693 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003694 unsigned NumAllocated = 0;
3695 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3696 unsigned Reg = RegClassRegs[i];
3697 // See if this register is available.
3698 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3699 (isInReg && InputRegs.count(Reg))) { // Already used.
3700 // Make sure we find consecutive registers.
3701 NumAllocated = 0;
3702 continue;
3703 }
3704
3705 // Check to see if this register is allocatable (i.e. don't give out the
3706 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003707 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003708 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003709 if (!RC) { // Couldn't allocate this register.
3710 // Reset NumAllocated to make sure we return consecutive registers.
3711 NumAllocated = 0;
3712 continue;
3713 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003714 }
3715
3716 // Okay, this register is good, we can use it.
3717 ++NumAllocated;
3718
3719 // If we allocated enough consecutive registers, succeed.
3720 if (NumAllocated == NumRegs) {
3721 unsigned RegStart = (i-NumAllocated)+1;
3722 unsigned RegEnd = i+1;
3723 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003724 for (unsigned i = RegStart; i != RegEnd; ++i)
3725 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003726
Dan Gohman23ce5022008-04-25 18:27:55 +00003727 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003728 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003729 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003730 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003731 }
3732 }
3733
3734 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003735 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003736}
3737
3738
Chris Lattnerce7518c2006-01-26 22:24:51 +00003739/// visitInlineAsm - Handle a call to an InlineAsm object.
3740///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003741void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3742 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003743
Chris Lattner0c583402007-04-28 20:49:53 +00003744 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003745 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003746
3747 SDOperand Chain = getRoot();
3748 SDOperand Flag;
3749
Chris Lattner4e4b5762006-02-01 18:59:47 +00003750 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003751
Chris Lattner0c583402007-04-28 20:49:53 +00003752 // Do a prepass over the constraints, canonicalizing them, and building up the
3753 // ConstraintOperands list.
3754 std::vector<InlineAsm::ConstraintInfo>
3755 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003756
3757 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3758 // constraint. If so, we can't let the register allocator allocate any input
3759 // registers, because it will not know to avoid the earlyclobbered output reg.
3760 bool SawEarlyClobber = false;
3761
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003762 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattner0c583402007-04-28 20:49:53 +00003763 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003764 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3765 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003766
Chris Lattner0c583402007-04-28 20:49:53 +00003767 MVT::ValueType OpVT = MVT::Other;
3768
3769 // Compute the value type for each operand.
3770 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003771 case InlineAsm::isOutput:
Chris Lattner0c583402007-04-28 20:49:53 +00003772 if (!OpInfo.isIndirect) {
3773 // The return value of the call is this value. As such, there is no
3774 // corresponding argument.
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003775 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3776 OpVT = TLI.getValueType(CS.getType());
Chris Lattner1efa40f2006-02-22 00:56:39 +00003777 } else {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003778 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003779 }
3780 break;
3781 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003782 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003783 break;
3784 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003785 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003786 break;
3787 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003788
Chris Lattner0c583402007-04-28 20:49:53 +00003789 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003790 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003791 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003792 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3793 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003794 else {
3795 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3796 const Type *OpTy = OpInfo.CallOperandVal->getType();
3797 // If this is an indirect operand, the operand is a pointer to the
3798 // accessed type.
3799 if (OpInfo.isIndirect)
3800 OpTy = cast<PointerType>(OpTy)->getElementType();
3801
3802 // If OpTy is not a first-class value, it may be a struct/union that we
3803 // can tile with integers.
3804 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3805 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3806 switch (BitSize) {
3807 default: break;
3808 case 1:
3809 case 8:
3810 case 16:
3811 case 32:
3812 case 64:
3813 OpTy = IntegerType::get(BitSize);
3814 break;
3815 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003816 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003817
3818 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003819 }
3820 }
3821
3822 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003823
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003824 // Compute the constraint code and ConstraintType to use.
Chris Lattner4376fea2008-04-27 00:09:47 +00003825 TLI.ComputeConstraintToUse(OpInfo);
Chris Lattner0c583402007-04-28 20:49:53 +00003826
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003827 // Keep track of whether we see an earlyclobber.
3828 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003829
Chris Lattner0fe71e92008-02-21 19:43:13 +00003830 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003831 if (!SawEarlyClobber &&
3832 OpInfo.Type == InlineAsm::isClobber &&
3833 OpInfo.ConstraintType == TargetLowering::C_Register) {
3834 // Note that we want to ignore things that we don't trick here, like
3835 // dirflag, fpsr, flags, etc.
3836 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3837 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3838 OpInfo.ConstraintVT);
3839 if (PhysReg.first || PhysReg.second) {
3840 // This is a register we know of.
3841 SawEarlyClobber = true;
3842 }
3843 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003844
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003845 // If this is a memory input, and if the operand is not indirect, do what we
3846 // need to to provide an address for the memory input.
3847 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3848 !OpInfo.isIndirect) {
3849 assert(OpInfo.Type == InlineAsm::isInput &&
3850 "Can only indirectify direct input operands!");
3851
3852 // Memory operands really want the address of the value. If we don't have
3853 // an indirect input, put it in the constpool if we can, otherwise spill
3854 // it to a stack slot.
3855
3856 // If the operand is a float, integer, or vector constant, spill to a
3857 // constant pool entry to get its address.
3858 Value *OpVal = OpInfo.CallOperandVal;
3859 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3860 isa<ConstantVector>(OpVal)) {
3861 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3862 TLI.getPointerTy());
3863 } else {
3864 // Otherwise, create a stack slot and emit a store to it before the
3865 // asm.
3866 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003867 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003868 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3869 MachineFunction &MF = DAG.getMachineFunction();
3870 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3871 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3872 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3873 OpInfo.CallOperand = StackSlot;
3874 }
3875
3876 // There is no longer a Value* corresponding to this operand.
3877 OpInfo.CallOperandVal = 0;
3878 // It is now an indirect operand.
3879 OpInfo.isIndirect = true;
3880 }
3881
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003882 // If this constraint is for a specific register, allocate it before
3883 // anything else.
3884 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3885 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003886 }
Chris Lattner0c583402007-04-28 20:49:53 +00003887 ConstraintInfos.clear();
3888
3889
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003890 // Second pass - Loop over all of the operands, assigning virtual or physregs
3891 // to registerclass operands.
3892 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003893 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003894
3895 // C_Register operands have already been allocated, Other/Memory don't need
3896 // to be.
3897 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3898 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3899 }
3900
Chris Lattner0c583402007-04-28 20:49:53 +00003901 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3902 std::vector<SDOperand> AsmNodeOperands;
3903 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3904 AsmNodeOperands.push_back(
3905 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3906
Chris Lattner2cc2f662006-02-01 01:28:23 +00003907
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003908 // Loop over all of the inputs, copying the operand values into the
3909 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003910 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003911
Chris Lattner0c583402007-04-28 20:49:53 +00003912 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3913 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3914
3915 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003916 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003917
Chris Lattner0c583402007-04-28 20:49:53 +00003918 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003919 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003920 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3921 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003922 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003923 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003924
Chris Lattner22873462006-02-27 23:45:39 +00003925 // Add information to the INLINEASM node to know about this output.
3926 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003927 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3928 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003929 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003930 break;
3931 }
3932
Chris Lattner2a600be2007-04-28 21:01:43 +00003933 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003934
Chris Lattner864635a2006-02-22 22:37:12 +00003935 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003936 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003937 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003938 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003939 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003940 exit(1);
3941 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003942
Chris Lattner0c583402007-04-28 20:49:53 +00003943 if (!OpInfo.isIndirect) {
3944 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003945 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003946 "Cannot have multiple output constraints yet!");
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003947 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003948 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003949 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003950 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003951 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003952 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003953
3954 // Add information to the INLINEASM node to know that this register is
3955 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003956 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3957 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003958 break;
3959 }
3960 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003961 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003962
Chris Lattner0c583402007-04-28 20:49:53 +00003963 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003964 // If this is required to match an output register we have already set,
3965 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003966 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003967
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003968 // Scan until we find the definition we already emitted of this operand.
3969 // When we find it, create a RegsForValue operand.
3970 unsigned CurOp = 2; // The first operand.
3971 for (; OperandNo; --OperandNo) {
3972 // Advance to the next operand.
3973 unsigned NumOps =
3974 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003975 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3976 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003977 "Skipped past definitions?");
3978 CurOp += (NumOps>>3)+1;
3979 }
3980
3981 unsigned NumOps =
3982 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003983 if ((NumOps & 7) == 2 /*REGDEF*/) {
3984 // Add NumOps>>3 registers to MatchedRegs.
3985 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00003986 MatchedRegs.TLI = &TLI;
3987 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
3988 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00003989 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3990 unsigned Reg =
3991 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3992 MatchedRegs.Regs.push_back(Reg);
3993 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003994
Chris Lattner527fae12007-02-01 01:21:12 +00003995 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003996 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00003997 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3998 break;
3999 } else {
4000 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004001 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4002 // Add information to the INLINEASM node to know about this input.
4003 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4004 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4005 TLI.getPointerTy()));
4006 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4007 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004008 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004009 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004010
Chris Lattner2a600be2007-04-28 21:01:43 +00004011 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004012 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004013 "Don't know how to handle indirect other inputs yet!");
4014
Chris Lattner48884cd2007-08-25 00:47:38 +00004015 std::vector<SDOperand> Ops;
4016 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4017 Ops, DAG);
4018 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004019 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004020 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004021 exit(1);
4022 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004023
4024 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004025 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004026 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4027 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004028 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004029 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004030 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004031 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004032 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4033 "Memory operands expect pointer values");
4034
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004035 // Add information to the INLINEASM node to know about this input.
4036 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004037 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4038 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004039 AsmNodeOperands.push_back(InOperandVal);
4040 break;
4041 }
4042
Chris Lattner2a600be2007-04-28 21:01:43 +00004043 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4044 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4045 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004046 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004047 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004048
4049 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004050 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4051 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004052
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004053 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004054
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004055 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4056 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004057 break;
4058 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004059 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004060 // Add the clobbered value to the operand list, so that the register
4061 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004062 if (!OpInfo.AssignedRegs.Regs.empty())
4063 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4064 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004065 break;
4066 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004067 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004068 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004069
4070 // Finish up input operands.
4071 AsmNodeOperands[0] = Chain;
4072 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4073
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004074 Chain = DAG.getNode(ISD::INLINEASM,
4075 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004076 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004077 Flag = Chain.getValue(1);
4078
Chris Lattner6656dd12006-01-31 02:03:41 +00004079 // If this asm returns a register value, copy the result from that register
4080 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004081 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004082 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00004083
4084 // If the result of the inline asm is a vector, it may have the wrong
4085 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004086 // bit_convert.
4087 if (MVT::isVector(Val.getValueType())) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004088 const VectorType *VTy = cast<VectorType>(CS.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004089 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00004090
Dan Gohman7f321562007-06-25 16:23:39 +00004091 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004092 }
4093
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004094 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004095 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004096
Chris Lattner6656dd12006-01-31 02:03:41 +00004097 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4098
4099 // Process indirect outputs, first output all of the flagged copies out of
4100 // physregs.
4101 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004102 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004103 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004104 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004105 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004106 }
4107
4108 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004109 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004110 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004111 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004112 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004113 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004114 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004115 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4116 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004117 DAG.setRoot(Chain);
4118}
4119
4120
Chris Lattner1c08c712005-01-07 07:47:53 +00004121void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4122 SDOperand Src = getValue(I.getOperand(0));
4123
4124 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004125
4126 if (IntPtr < Src.getValueType())
4127 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4128 else if (IntPtr > Src.getValueType())
4129 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004130
4131 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004132 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004133 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004134 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004135
Reid Spencer47857812006-12-31 05:55:36 +00004136 TargetLowering::ArgListTy Args;
4137 TargetLowering::ArgListEntry Entry;
4138 Entry.Node = Src;
4139 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004140 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004141
4142 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004143 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4144 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004145 setValue(&I, Result.first); // Pointers always fit in registers
4146 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004147}
4148
4149void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004150 TargetLowering::ArgListTy Args;
4151 TargetLowering::ArgListEntry Entry;
4152 Entry.Node = getValue(I.getOperand(0));
4153 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004154 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004155 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004156 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004157 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4158 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004159 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4160 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004161}
4162
Evan Chengff9b3732008-01-30 18:18:23 +00004163// EmitInstrWithCustomInserter - This method should be implemented by targets
4164// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004165// instructions are special in various ways, which require special support to
4166// insert. The specified MachineInstr is created but not inserted into any
4167// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004168MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004169 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004170 cerr << "If a target marks an instruction with "
4171 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004172 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004173 abort();
4174 return 0;
4175}
4176
Chris Lattner39ae3622005-01-09 00:00:49 +00004177void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004178 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4179 getValue(I.getOperand(1)),
4180 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004181}
4182
4183void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004184 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4185 getValue(I.getOperand(0)),
4186 DAG.getSrcValue(I.getOperand(0)));
4187 setValue(&I, V);
4188 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004189}
4190
4191void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004192 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4193 getValue(I.getOperand(1)),
4194 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004195}
4196
4197void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004198 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4199 getValue(I.getOperand(1)),
4200 getValue(I.getOperand(2)),
4201 DAG.getSrcValue(I.getOperand(1)),
4202 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004203}
4204
Chris Lattnerfdfded52006-04-12 16:20:43 +00004205/// TargetLowering::LowerArguments - This is the default LowerArguments
4206/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004207/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4208/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004209std::vector<SDOperand>
4210TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4211 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4212 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004213 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004214 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4215 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4216
4217 // Add one result value for each formal argument.
4218 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004219 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004220 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4221 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004222 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004223 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004224 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004225 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004226
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004227 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004228 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004229 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004230 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004231 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004232 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004233 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004234 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004235 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004236 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004237 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004238 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004239 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004240 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004241 // For ByVal, alignment should be passed from FE. BE will guess if
4242 // this info is not there but there are cases it cannot get right.
4243 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004244 FrameAlign = F.getParamAlignment(j);
4245 Flags.setByValAlign(FrameAlign);
4246 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004247 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004248 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004249 Flags.setNest();
4250 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004251
4252 MVT::ValueType RegisterVT = getRegisterType(VT);
4253 unsigned NumRegs = getNumRegisters(VT);
4254 for (unsigned i = 0; i != NumRegs; ++i) {
4255 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004256 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004257 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004258 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004259 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004260 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004261 MyFlags.setOrigAlign(1);
4262 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004263 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004264 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004265
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004266 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004267
4268 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004269 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004270 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004271 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004272
4273 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4274 // allows exposing the loads that may be part of the argument access to the
4275 // first DAGCombiner pass.
4276 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4277
4278 // The number of results should match up, except that the lowered one may have
4279 // an extra flag result.
4280 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4281 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4282 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4283 && "Lowering produced unexpected number of results!");
4284 Result = TmpRes.Val;
4285
Dan Gohman27a70be2007-07-02 16:18:06 +00004286 unsigned NumArgRegs = Result->getNumValues() - 1;
4287 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004288
4289 // Set up the return result vector.
4290 Ops.clear();
4291 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004292 unsigned Idx = 1;
4293 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4294 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004295 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004296 MVT::ValueType PartVT = getRegisterType(VT);
4297
4298 unsigned NumParts = getNumRegisters(VT);
4299 SmallVector<SDOperand, 4> Parts(NumParts);
4300 for (unsigned j = 0; j != NumParts; ++j)
4301 Parts[j] = SDOperand(Result, i++);
4302
4303 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4304 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4305 AssertOp = ISD::AssertSext;
4306 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4307 AssertOp = ISD::AssertZext;
4308
4309 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004310 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004311 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004312 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004313 return Ops;
4314}
4315
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004316
4317/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4318/// implementation, which just inserts an ISD::CALL node, which is later custom
4319/// lowered by the target to something concrete. FIXME: When all targets are
4320/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4321std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004322TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4323 bool RetSExt, bool RetZExt, bool isVarArg,
4324 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004325 SDOperand Callee,
4326 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004327 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004328 Ops.push_back(Chain); // Op#0 - Chain
4329 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4330 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4331 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4332 Ops.push_back(Callee);
4333
4334 // Handle all of the outgoing arguments.
4335 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004336 MVT::ValueType VT = getValueType(Args[i].Ty);
4337 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004338 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004339 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004340 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004341
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004342 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004343 Flags.setZExt();
4344 if (Args[i].isSExt)
4345 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004346 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004347 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004348 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004349 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004350 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004351 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004352 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004353 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004354 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004355 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004356 // For ByVal, alignment should come from FE. BE will guess if this
4357 // info is not there but there are cases it cannot get right.
4358 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004359 FrameAlign = Args[i].Alignment;
4360 Flags.setByValAlign(FrameAlign);
4361 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004362 }
Duncan Sands36397f52007-07-27 12:58:54 +00004363 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004364 Flags.setNest();
4365 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004366
Duncan Sandsb988bac2008-02-11 20:58:28 +00004367 MVT::ValueType PartVT = getRegisterType(VT);
4368 unsigned NumParts = getNumRegisters(VT);
4369 SmallVector<SDOperand, 4> Parts(NumParts);
4370 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4371
4372 if (Args[i].isSExt)
4373 ExtendKind = ISD::SIGN_EXTEND;
4374 else if (Args[i].isZExt)
4375 ExtendKind = ISD::ZERO_EXTEND;
4376
4377 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4378
4379 for (unsigned i = 0; i != NumParts; ++i) {
4380 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004381 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004382 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004383 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004384 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004385 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004386
4387 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004388 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004389 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004390 }
4391
Dan Gohmanef5d1942008-03-11 21:11:25 +00004392 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004393 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004394 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4395 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004396 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004397
Dan Gohman23ce5022008-04-25 18:27:55 +00004398 // Then we translate that to a list of legal types.
4399 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4400 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004401 MVT::ValueType RegisterVT = getRegisterType(VT);
4402 unsigned NumRegs = getNumRegisters(VT);
4403 for (unsigned i = 0; i != NumRegs; ++i)
4404 LoweredRetTys.push_back(RegisterVT);
4405 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004406
Dan Gohmanef5d1942008-03-11 21:11:25 +00004407 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004408
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004409 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004410 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004411 DAG.getVTList(&LoweredRetTys[0],
4412 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004413 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004414 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004415
4416 // Gather up the call result into a single value.
4417 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004418 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4419
4420 if (RetSExt)
4421 AssertOp = ISD::AssertSext;
4422 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004423 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004424
Dan Gohmanef5d1942008-03-11 21:11:25 +00004425 SmallVector<SDOperand, 4> ReturnValues;
4426 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004427 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4428 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004429 MVT::ValueType RegisterVT = getRegisterType(VT);
4430 unsigned NumRegs = getNumRegisters(VT);
4431 unsigned RegNoEnd = NumRegs + RegNo;
4432 SmallVector<SDOperand, 4> Results;
4433 for (; RegNo != RegNoEnd; ++RegNo)
4434 Results.push_back(Res.getValue(RegNo));
4435 SDOperand ReturnValue =
4436 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4437 AssertOp);
4438 ReturnValues.push_back(ReturnValue);
4439 }
4440 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4441 DAG.getNode(ISD::MERGE_VALUES,
4442 DAG.getVTList(&RetTys[0], RetTys.size()),
4443 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004444 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004445
4446 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004447}
4448
Chris Lattner50381b62005-05-14 05:50:48 +00004449SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004450 assert(0 && "LowerOperation not implemented for this target!");
4451 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004452 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004453}
4454
Nate Begeman0aed7842006-01-28 03:14:31 +00004455SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4456 SelectionDAG &DAG) {
4457 assert(0 && "CustomPromoteOperation not implemented for this target!");
4458 abort();
4459 return SDOperand();
4460}
4461
Chris Lattner7041ee32005-01-11 05:56:49 +00004462//===----------------------------------------------------------------------===//
4463// SelectionDAGISel code
4464//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004465
4466unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004467 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004468}
4469
Chris Lattner495a0b52005-08-17 06:37:43 +00004470void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004471 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004472 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004473 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004474}
Chris Lattner1c08c712005-01-07 07:47:53 +00004475
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004476
Chris Lattnerbad7f482006-10-28 19:22:10 +00004477
Chris Lattner1c08c712005-01-07 07:47:53 +00004478bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004479 // Get alias analysis for load/store combining.
4480 AA = &getAnalysis<AliasAnalysis>();
4481
Chris Lattner1c08c712005-01-07 07:47:53 +00004482 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004483 if (MF.getFunction()->hasCollector())
4484 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4485 else
4486 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004487 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004488 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004489
4490 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4491
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004492 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4493 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4494 // Mark landing pad.
4495 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004496
4497 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004498 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004499
Evan Chengad2070c2007-02-10 02:43:39 +00004500 // Add function live-ins to entry block live-in set.
4501 BasicBlock *EntryBB = &Fn.getEntryBlock();
4502 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004503 if (!RegInfo->livein_empty())
4504 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4505 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004506 BB->addLiveIn(I->first);
4507
Duncan Sandsf4070822007-06-15 19:04:19 +00004508#ifndef NDEBUG
4509 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4510 "Not all catch info was assigned to a landing pad!");
4511#endif
4512
Chris Lattner1c08c712005-01-07 07:47:53 +00004513 return true;
4514}
4515
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004516void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4517 unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004518 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004519 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004520 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004521 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004522 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004523
Dan Gohman23ce5022008-04-25 18:27:55 +00004524 RegsForValue RFV(TLI, Reg, V->getType());
4525 SDOperand Chain = DAG.getEntryNode();
4526 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4527 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004528}
4529
Chris Lattner068a81e2005-01-17 17:15:02 +00004530void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004531LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004532 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004533 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004534 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004535 SDOperand OldRoot = SDL.DAG.getRoot();
4536 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004537
Chris Lattnerbf209482005-10-30 19:42:35 +00004538 unsigned a = 0;
4539 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4540 AI != E; ++AI, ++a)
4541 if (!AI->use_empty()) {
4542 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004543
Chris Lattnerbf209482005-10-30 19:42:35 +00004544 // If this argument is live outside of the entry block, insert a copy from
4545 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004546 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4547 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004548 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004549 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004550 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004551
Chris Lattnerbf209482005-10-30 19:42:35 +00004552 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004553 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004554 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004555}
4556
Duncan Sandsf4070822007-06-15 19:04:19 +00004557static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4558 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004559 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004560 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004561 // Apply the catch info to DestBB.
4562 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4563#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004564 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4565 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004566#endif
4567 }
4568}
4569
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004570/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004571/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004572static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4573 TargetLowering& TLI) {
4574 SDNode * Ret = NULL;
4575 SDOperand Terminator = DAG.getRoot();
4576
4577 // Find RET node.
4578 if (Terminator.getOpcode() == ISD::RET) {
4579 Ret = Terminator.Val;
4580 }
4581
4582 // Fix tail call attribute of CALL nodes.
4583 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4584 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4585 if (BI->getOpcode() == ISD::CALL) {
4586 SDOperand OpRet(Ret, 0);
4587 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4588 bool isMarkedTailCall =
4589 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4590 // If CALL node has tail call attribute set to true and the call is not
4591 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004592 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004593 // must correctly identify tail call optimizable calls.
4594 if (isMarkedTailCall &&
4595 (Ret==NULL ||
4596 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4597 SmallVector<SDOperand, 32> Ops;
4598 unsigned idx=0;
4599 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4600 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4601 if (idx!=3)
4602 Ops.push_back(*I);
4603 else
4604 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4605 }
4606 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4607 }
4608 }
4609 }
4610}
4611
Chris Lattner1c08c712005-01-07 07:47:53 +00004612void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4613 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004614 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004615 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004616
Chris Lattnerbf209482005-10-30 19:42:35 +00004617 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004618 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004619 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004620
4621 BB = FuncInfo.MBBMap[LLVMBB];
4622 SDL.setCurrentBasicBlock(BB);
4623
Duncan Sandsf4070822007-06-15 19:04:19 +00004624 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004625
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004626 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004627 // Add a label to mark the beginning of the landing pad. Deletion of the
4628 // landing pad can thus be detected via the MachineModuleInfo.
4629 unsigned LabelID = MMI->addLandingPad(BB);
4630 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004631 DAG.getConstant(LabelID, MVT::i32),
4632 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004633
Evan Chenge47c3332007-06-27 18:45:32 +00004634 // Mark exception register as live in.
4635 unsigned Reg = TLI.getExceptionAddressRegister();
4636 if (Reg) BB->addLiveIn(Reg);
4637
4638 // Mark exception selector register as live in.
4639 Reg = TLI.getExceptionSelectorRegister();
4640 if (Reg) BB->addLiveIn(Reg);
4641
Duncan Sandsf4070822007-06-15 19:04:19 +00004642 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4643 // function and list of typeids logically belong to the invoke (or, if you
4644 // like, the basic block containing the invoke), and need to be associated
4645 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004646 // information is provided by an intrinsic (eh.selector) that can be moved
4647 // to unexpected places by the optimizers: if the unwind edge is critical,
4648 // then breaking it can result in the intrinsics being in the successor of
4649 // the landing pad, not the landing pad itself. This results in exceptions
4650 // not being caught because no typeids are associated with the invoke.
4651 // This may not be the only way things can go wrong, but it is the only way
4652 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004653 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4654
4655 if (Br && Br->isUnconditional()) { // Critical edge?
4656 BasicBlock::iterator I, E;
4657 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004658 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004659 break;
4660
4661 if (I == E)
4662 // No catch info found - try to extract some from the successor.
4663 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004664 }
4665 }
4666
Chris Lattner1c08c712005-01-07 07:47:53 +00004667 // Lower all of the non-terminator instructions.
4668 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4669 I != E; ++I)
4670 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004671
Chris Lattner1c08c712005-01-07 07:47:53 +00004672 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004673 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004674 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004675 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004676 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004677 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004678 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004679 }
4680
4681 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4682 // ensure constants are generated when needed. Remember the virtual registers
4683 // that need to be added to the Machine PHI nodes as input. We cannot just
4684 // directly add them, because expansion might result in multiple MBB's for one
4685 // BB. As such, the start of the BB might correspond to a different MBB than
4686 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004687 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004688 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004689
4690 // Emit constants only once even if used by multiple PHI nodes.
4691 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004692
Chris Lattner8c494ab2006-10-27 23:50:33 +00004693 // Vector bool would be better, but vector<bool> is really slow.
4694 std::vector<unsigned char> SuccsHandled;
4695 if (TI->getNumSuccessors())
4696 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4697
Dan Gohman532dc2e2007-07-09 20:59:04 +00004698 // Check successor nodes' PHI nodes that expect a constant to be available
4699 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004700 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4701 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004702 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004703 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004704
Chris Lattner8c494ab2006-10-27 23:50:33 +00004705 // If this terminator has multiple identical successors (common for
4706 // switches), only handle each succ once.
4707 unsigned SuccMBBNo = SuccMBB->getNumber();
4708 if (SuccsHandled[SuccMBBNo]) continue;
4709 SuccsHandled[SuccMBBNo] = true;
4710
4711 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004712 PHINode *PN;
4713
4714 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4715 // nodes and Machine PHI nodes, but the incoming operands have not been
4716 // emitted yet.
4717 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004718 (PN = dyn_cast<PHINode>(I)); ++I) {
4719 // Ignore dead phi's.
4720 if (PN->use_empty()) continue;
4721
4722 unsigned Reg;
4723 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004724
Chris Lattner8c494ab2006-10-27 23:50:33 +00004725 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4726 unsigned &RegOut = ConstantsOut[C];
4727 if (RegOut == 0) {
4728 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004729 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004730 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004731 Reg = RegOut;
4732 } else {
4733 Reg = FuncInfo.ValueMap[PHIOp];
4734 if (Reg == 0) {
4735 assert(isa<AllocaInst>(PHIOp) &&
4736 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4737 "Didn't codegen value into a register!??");
4738 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004739 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004740 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004741 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004742
4743 // Remember that this register needs to added to the machine PHI node as
4744 // the input for this MBB.
4745 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004746 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004747 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004748 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4749 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004750 }
4751 ConstantsOut.clear();
4752
4753 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004754 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004755
Nate Begemanf15485a2006-03-27 01:32:24 +00004756 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004757 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004758 SwitchCases.clear();
4759 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004760 JTCases.clear();
4761 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004762 BitTestCases.clear();
4763 BitTestCases = SDL.BitTestCases;
4764
Chris Lattnera651cf62005-01-17 19:43:36 +00004765 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004766 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004767
4768 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4769 // with correct tailcall attribute so that the target can rely on the tailcall
4770 // attribute indicating whether the call is really eligible for tail call
4771 // optimization.
4772 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004773}
4774
Nate Begemanf15485a2006-03-27 01:32:24 +00004775void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004776 DOUT << "Lowered selection DAG:\n";
4777 DEBUG(DAG.dump());
4778
Chris Lattneraf21d552005-10-10 16:47:10 +00004779 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004780 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004781
Dan Gohman417e11b2007-10-08 15:12:17 +00004782 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004783 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004784
Chris Lattner1c08c712005-01-07 07:47:53 +00004785 // Second step, hack on the DAG until it only uses operations and types that
4786 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004787#if 0 // Enable this some day.
4788 DAG.LegalizeTypes();
4789 // Someday even later, enable a dag combine pass here.
4790#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004791 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004792
Bill Wendling832171c2006-12-07 20:04:42 +00004793 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004794 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004795
Chris Lattneraf21d552005-10-10 16:47:10 +00004796 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004797 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004798
Dan Gohman417e11b2007-10-08 15:12:17 +00004799 DOUT << "Optimized legalized selection DAG:\n";
4800 DEBUG(DAG.dump());
4801
Evan Chenga9c20912006-01-21 02:32:06 +00004802 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004803
Chris Lattnera33ef482005-03-30 01:10:47 +00004804 // Third, instruction select all of the operations to machine code, adding the
4805 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004806 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004807
Bill Wendling832171c2006-12-07 20:04:42 +00004808 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004809 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004810}
Chris Lattner1c08c712005-01-07 07:47:53 +00004811
Nate Begemanf15485a2006-03-27 01:32:24 +00004812void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4813 FunctionLoweringInfo &FuncInfo) {
4814 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4815 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004816 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004817 CurDAG = &DAG;
4818
4819 // First step, lower LLVM code to some DAG. This DAG may use operations and
4820 // types that are not supported by the target.
4821 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4822
4823 // Second step, emit the lowered DAG as machine code.
4824 CodeGenAndEmitDAG(DAG);
4825 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004826
4827 DOUT << "Total amount of phi nodes to update: "
4828 << PHINodesToUpdate.size() << "\n";
4829 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4830 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4831 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004832
Chris Lattnera33ef482005-03-30 01:10:47 +00004833 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004834 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004835 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004836 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4837 MachineInstr *PHI = PHINodesToUpdate[i].first;
4838 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4839 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004840 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4841 false));
4842 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004843 }
4844 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004845 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004846
4847 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4848 // Lower header first, if it wasn't already lowered
4849 if (!BitTestCases[i].Emitted) {
4850 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4851 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004852 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004853 // Set the current basic block to the mbb we wish to insert the code into
4854 BB = BitTestCases[i].Parent;
4855 HSDL.setCurrentBasicBlock(BB);
4856 // Emit the code
4857 HSDL.visitBitTestHeader(BitTestCases[i]);
4858 HSDAG.setRoot(HSDL.getRoot());
4859 CodeGenAndEmitDAG(HSDAG);
4860 }
4861
4862 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4863 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4864 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004865 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004866 // Set the current basic block to the mbb we wish to insert the code into
4867 BB = BitTestCases[i].Cases[j].ThisBB;
4868 BSDL.setCurrentBasicBlock(BB);
4869 // Emit the code
4870 if (j+1 != ej)
4871 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4872 BitTestCases[i].Reg,
4873 BitTestCases[i].Cases[j]);
4874 else
4875 BSDL.visitBitTestCase(BitTestCases[i].Default,
4876 BitTestCases[i].Reg,
4877 BitTestCases[i].Cases[j]);
4878
4879
4880 BSDAG.setRoot(BSDL.getRoot());
4881 CodeGenAndEmitDAG(BSDAG);
4882 }
4883
4884 // Update PHI Nodes
4885 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4886 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4887 MachineBasicBlock *PHIBB = PHI->getParent();
4888 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4889 "This is not a machine PHI node that we are updating!");
4890 // This is "default" BB. We have two jumps to it. From "header" BB and
4891 // from last "case" BB.
4892 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004893 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4894 false));
4895 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4896 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4897 false));
4898 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4899 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004900 }
4901 // One of "cases" BB.
4902 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4903 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4904 if (cBB->succ_end() !=
4905 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004906 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4907 false));
4908 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004909 }
4910 }
4911 }
4912 }
4913
Nate Begeman9453eea2006-04-23 06:26:20 +00004914 // If the JumpTable record is filled in, then we need to emit a jump table.
4915 // Updating the PHI nodes is tricky in this case, since we need to determine
4916 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004917 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4918 // Lower header first, if it wasn't already lowered
4919 if (!JTCases[i].first.Emitted) {
4920 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4921 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004922 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004923 // Set the current basic block to the mbb we wish to insert the code into
4924 BB = JTCases[i].first.HeaderBB;
4925 HSDL.setCurrentBasicBlock(BB);
4926 // Emit the code
4927 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4928 HSDAG.setRoot(HSDL.getRoot());
4929 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004930 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004931
4932 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4933 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004934 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00004935 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004936 BB = JTCases[i].second.MBB;
4937 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004938 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004939 JSDL.visitJumpTable(JTCases[i].second);
4940 JSDAG.setRoot(JSDL.getRoot());
4941 CodeGenAndEmitDAG(JSDAG);
4942
Nate Begeman37efe672006-04-22 18:53:45 +00004943 // Update PHI Nodes
4944 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4945 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4946 MachineBasicBlock *PHIBB = PHI->getParent();
4947 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4948 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004949 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004950 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004951 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4952 false));
4953 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00004954 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004955 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004956 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004957 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4958 false));
4959 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00004960 }
4961 }
Nate Begeman37efe672006-04-22 18:53:45 +00004962 }
4963
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004964 // If the switch block involved a branch to one of the actual successors, we
4965 // need to update PHI nodes in that block.
4966 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4967 MachineInstr *PHI = PHINodesToUpdate[i].first;
4968 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4969 "This is not a machine PHI node that we are updating!");
4970 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004971 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4972 false));
4973 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004974 }
4975 }
4976
Nate Begemanf15485a2006-03-27 01:32:24 +00004977 // If we generated any switch lowering information, build and codegen any
4978 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004979 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004980 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004981 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004982 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004983
Nate Begemanf15485a2006-03-27 01:32:24 +00004984 // Set the current basic block to the mbb we wish to insert the code into
4985 BB = SwitchCases[i].ThisBB;
4986 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004987
Nate Begemanf15485a2006-03-27 01:32:24 +00004988 // Emit the code
4989 SDL.visitSwitchCase(SwitchCases[i]);
4990 SDAG.setRoot(SDL.getRoot());
4991 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004992
4993 // Handle any PHI nodes in successors of this chunk, as if we were coming
4994 // from the original BB before switch expansion. Note that PHI nodes can
4995 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4996 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004997 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004998 for (MachineBasicBlock::iterator Phi = BB->begin();
4999 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5000 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5001 for (unsigned pn = 0; ; ++pn) {
5002 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5003 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005004 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5005 second, false));
5006 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005007 break;
5008 }
5009 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005010 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005011
5012 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005013 if (BB == SwitchCases[i].FalseBB)
5014 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005015
5016 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005017 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005018 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005019 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005020 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005021 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005022}
Evan Chenga9c20912006-01-21 02:32:06 +00005023
Jim Laskey13ec7022006-08-01 14:21:23 +00005024
Evan Chenga9c20912006-01-21 02:32:06 +00005025//===----------------------------------------------------------------------===//
5026/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5027/// target node in the graph.
5028void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5029 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005030
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005031 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005032
5033 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005034 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005035 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005036 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005037
Jim Laskey9ff542f2006-08-01 18:29:48 +00005038 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005039 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005040
5041 if (ViewSUnitDAGs) SL->viewGraph();
5042
Evan Chengcccf1232006-02-04 06:49:00 +00005043 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005044}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005045
Chris Lattner03fc53c2006-03-06 00:22:00 +00005046
Jim Laskey9ff542f2006-08-01 18:29:48 +00005047HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5048 return new HazardRecognizer();
5049}
5050
Chris Lattner75548062006-10-11 03:58:02 +00005051//===----------------------------------------------------------------------===//
5052// Helper functions used by the generated instruction selector.
5053//===----------------------------------------------------------------------===//
5054// Calls to these methods are generated by tblgen.
5055
5056/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5057/// the dag combiner simplified the 255, we still want to match. RHS is the
5058/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5059/// specified in the .td file (e.g. 255).
5060bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005061 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005062 const APInt &ActualMask = RHS->getAPIntValue();
5063 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005064
5065 // If the actual mask exactly matches, success!
5066 if (ActualMask == DesiredMask)
5067 return true;
5068
5069 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005070 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005071 return false;
5072
5073 // Otherwise, the DAG Combiner may have proven that the value coming in is
5074 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005075 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005076 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005077 return true;
5078
5079 // TODO: check to see if missing bits are just not demanded.
5080
5081 // Otherwise, this pattern doesn't match.
5082 return false;
5083}
5084
5085/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5086/// the dag combiner simplified the 255, we still want to match. RHS is the
5087/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5088/// specified in the .td file (e.g. 255).
5089bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005090 int64_t DesiredMaskS) const {
5091 const APInt &ActualMask = RHS->getAPIntValue();
5092 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005093
5094 // If the actual mask exactly matches, success!
5095 if (ActualMask == DesiredMask)
5096 return true;
5097
5098 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005099 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005100 return false;
5101
5102 // Otherwise, the DAG Combiner may have proven that the value coming in is
5103 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005104 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005105
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005106 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005107 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005108
5109 // If all the missing bits in the or are already known to be set, match!
5110 if ((NeededMask & KnownOne) == NeededMask)
5111 return true;
5112
5113 // TODO: check to see if missing bits are just not demanded.
5114
5115 // Otherwise, this pattern doesn't match.
5116 return false;
5117}
5118
Jim Laskey9ff542f2006-08-01 18:29:48 +00005119
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005120/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5121/// by tblgen. Others should not call it.
5122void SelectionDAGISel::
5123SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5124 std::vector<SDOperand> InOps;
5125 std::swap(InOps, Ops);
5126
5127 Ops.push_back(InOps[0]); // input chain.
5128 Ops.push_back(InOps[1]); // input asm string.
5129
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005130 unsigned i = 2, e = InOps.size();
5131 if (InOps[e-1].getValueType() == MVT::Flag)
5132 --e; // Don't process a flag operand if it is here.
5133
5134 while (i != e) {
5135 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5136 if ((Flags & 7) != 4 /*MEM*/) {
5137 // Just skip over this operand, copying the operands verbatim.
5138 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5139 i += (Flags >> 3) + 1;
5140 } else {
5141 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5142 // Otherwise, this is a memory operand. Ask the target to select it.
5143 std::vector<SDOperand> SelOps;
5144 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005145 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005146 exit(1);
5147 }
5148
5149 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005150 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005151 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005152 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005153 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5154 i += 2;
5155 }
5156 }
5157
5158 // Add the flag input back if present.
5159 if (e != InOps.size())
5160 Ops.push_back(InOps.back());
5161}
Devang Patel794fd752007-05-01 21:15:47 +00005162
Devang Patel19974732007-05-03 01:11:54 +00005163char SelectionDAGISel::ID = 0;