blob: 1dc6753268f474fe4a7d53378b4acfe9c71d0341 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000077static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
82 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084static RegisterScheduler
85defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087
Evan Cheng5c807602008-02-26 02:33:44 +000088namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000089
Chris Lattnerf899fce2008-04-27 23:48:12 +000090/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
Duncan Sands83ec4b62008-06-06 12:08:01 +000091/// MVTs that represent all the individual underlying
Chris Lattnerf899fce2008-04-27 23:48:12 +000092/// non-aggregate types that comprise it.
93static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
Duncan Sands83ec4b62008-06-06 12:08:01 +000094 SmallVectorImpl<MVT> &ValueVTs) {
Chris Lattnerf899fce2008-04-27 23:48:12 +000095 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 for (StructType::element_iterator EI = STy->element_begin(),
98 EB = STy->element_end();
99 EI != EB; ++EI)
100 ComputeValueVTs(TLI, *EI, ValueVTs);
101 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000102 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000103 // Given an array type, recursively traverse the elements.
104 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
105 const Type *EltTy = ATy->getElementType();
106 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
107 ComputeValueVTs(TLI, EltTy, ValueVTs);
108 return;
109 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000110 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000111 ValueVTs.push_back(TLI.getValueType(Ty));
112}
Dan Gohman23ce5022008-04-25 18:27:55 +0000113
Chris Lattnerf899fce2008-04-27 23:48:12 +0000114namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000115 /// RegsForValue - This struct represents the registers (physical or virtual)
116 /// that a particular set of values is assigned, and the type information about
117 /// the value. The most common situation is to represent one value at a time,
118 /// but struct or array values are handled element-wise as multiple values.
119 /// The splitting of aggregates is performed recursively, so that we never
120 /// have aggregate-typed registers. The values at this point do not necessarily
121 /// have legal types, so each value may require one or more registers of some
122 /// legal type.
123 ///
Chris Lattner95255282006-06-28 23:17:24 +0000124 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000125 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000126 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 const TargetLowering *TLI;
128
Dan Gohman0fe00902008-04-28 18:10:39 +0000129 /// ValueVTs - The value types of the values, which may not be legal, and
130 /// may need be promoted or synthesized from one or more registers.
131 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000132 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000133
Dan Gohman0fe00902008-04-28 18:10:39 +0000134 /// RegVTs - The value types of the registers. This is the same size as
135 /// ValueVTs and it records, for each value, what the type of the assigned
136 /// register or registers are. (Individual values are never synthesized
137 /// from more than one type of register.)
138 ///
139 /// With virtual registers, the contents of RegVTs is redundant with TLI's
140 /// getRegisterType member function, however when with physical registers
141 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000142 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000143 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman0fe00902008-04-28 18:10:39 +0000145 /// Regs - This list holds the registers assigned to the values.
146 /// Each legal or promoted value requires one register, and each
147 /// expanded value requires multiple registers.
148 ///
149 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000150
Dan Gohman23ce5022008-04-25 18:27:55 +0000151 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000154 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000155 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000156 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000157 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000158 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000159 const SmallVector<MVT, 4> &regvts,
160 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
163 unsigned Reg, const Type *Ty) : TLI(&tli) {
164 ComputeValueVTs(tli, Ty, ValueVTs);
165
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000166 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000167 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000168 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000169 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000170 for (unsigned i = 0; i != NumRegs; ++i)
171 Regs.push_back(Reg + i);
172 RegVTs.push_back(RegisterVT);
173 Reg += NumRegs;
174 }
Chris Lattner864635a2006-02-22 22:37:12 +0000175 }
176
Chris Lattner41f62592008-04-29 04:29:54 +0000177 /// append - Add the specified values to this one.
178 void append(const RegsForValue &RHS) {
179 TLI = RHS.TLI;
180 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
181 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
182 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
183 }
184
185
Chris Lattner864635a2006-02-22 22:37:12 +0000186 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000187 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000189 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000190 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000192
193 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
194 /// specified value into the registers specified by this object. This uses
195 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000196 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000197 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199
200 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
201 /// operand list. This adds the code marker and includes the number of
202 /// values added into it.
203 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000204 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000205 };
206}
Evan Cheng4ef10862006-01-23 07:01:07 +0000207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208namespace llvm {
209 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000210 /// createDefaultScheduler - This creates an instruction scheduler appropriate
211 /// for the target.
212 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
213 SelectionDAG *DAG,
214 MachineBasicBlock *BB) {
215 TargetLowering &TLI = IS->getTargetLowering();
216
217 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
218 return createTDListDAGScheduler(IS, DAG, BB);
219 } else {
220 assert(TLI.getSchedulingPreference() ==
221 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
222 return createBURRListDAGScheduler(IS, DAG, BB);
223 }
224 }
225
226
227 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 /// FunctionLoweringInfo - This contains information that is global to a
229 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000230 class FunctionLoweringInfo {
231 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000232 TargetLowering &TLI;
233 Function &Fn;
234 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000235 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000236
237 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
238
239 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
240 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
241
242 /// ValueMap - Since we emit code for the function a basic block at a time,
243 /// we must remember which virtual registers hold the values for
244 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000245 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000246
247 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
248 /// the entry block. This allows the allocas to be efficiently referenced
249 /// anywhere in the function.
250 std::map<const AllocaInst*, int> StaticAllocaMap;
251
Duncan Sandsf4070822007-06-15 19:04:19 +0000252#ifndef NDEBUG
253 SmallSet<Instruction*, 8> CatchInfoLost;
254 SmallSet<Instruction*, 8> CatchInfoFound;
255#endif
256
Duncan Sands83ec4b62008-06-06 12:08:01 +0000257 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 }
Chris Lattner571e4342006-10-27 21:36:01 +0000260
261 /// isExportedInst - Return true if the specified value is an instruction
262 /// exported from its block.
263 bool isExportedInst(const Value *V) {
264 return ValueMap.count(V);
265 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000266
Chris Lattner3c384492006-03-16 19:51:18 +0000267 unsigned CreateRegForValue(const Value *V);
268
Chris Lattner1c08c712005-01-07 07:47:53 +0000269 unsigned InitializeRegForValue(const Value *V) {
270 unsigned &R = ValueMap[V];
271 assert(R == 0 && "Already initialized this value register!");
272 return R = CreateRegForValue(V);
273 }
274 };
275}
276
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000277/// isSelector - Return true if this instruction is a call to the
278/// eh.selector intrinsic.
279static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000281 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
282 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000283 return false;
284}
285
Chris Lattner1c08c712005-01-07 07:47:53 +0000286/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000287/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000288/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000289static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
290 if (isa<PHINode>(I)) return true;
291 BasicBlock *BB = I->getParent();
292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000293 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000294 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 return true;
297 return false;
298}
299
Chris Lattnerbf209482005-10-30 19:42:35 +0000300/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000301/// entry block, return true. This includes arguments used by switches, since
302/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000303static bool isOnlyUsedInEntryBlock(Argument *A) {
304 BasicBlock *Entry = A->getParent()->begin();
305 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000306 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000307 return false; // Use not in entry block.
308 return true;
309}
310
Chris Lattner1c08c712005-01-07 07:47:53 +0000311FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000313 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000314
Chris Lattnerbf209482005-10-30 19:42:35 +0000315 // Create a vreg for each argument register that is not dead and is used
316 // outside of the entry block for the function.
317 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
318 AI != E; ++AI)
319 if (!isOnlyUsedInEntryBlock(AI))
320 InitializeRegForValue(AI);
321
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 // Initialize the mapping of values to registers. This is only set up for
323 // instruction values that are used outside of the block that defines
324 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000325 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
327 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000329 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000330 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000331 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000332 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000333 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000334
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000336 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000337 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000338 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 }
340
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000341 for (; BB != EB; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000343 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
344 if (!isa<AllocaInst>(I) ||
345 !StaticAllocaMap.count(cast<AllocaInst>(I)))
346 InitializeRegForValue(I);
347
348 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
349 // also creates the initial PHI MachineInstrs, though none of the input
350 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000351 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000352 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
353 MBBMap[BB] = MBB;
354 MF.getBasicBlockList().push_back(MBB);
355
356 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
357 // appropriate.
358 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000359 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
360 if (PN->use_empty()) continue;
361
Duncan Sands83ec4b62008-06-06 12:08:01 +0000362 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000363 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000364 unsigned PHIReg = ValueMap[PN];
365 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000366 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000367 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000369 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 }
371}
372
Chris Lattner3c384492006-03-16 19:51:18 +0000373/// CreateRegForValue - Allocate the appropriate number of virtual registers of
374/// the correctly promoted or expanded types. Assign these registers
375/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000376///
377/// In the case that the given value has struct or array type, this function
378/// will assign registers for each member or element.
379///
Chris Lattner3c384492006-03-16 19:51:18 +0000380unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000381 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000383
Dan Gohman23ce5022008-04-25 18:27:55 +0000384 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000386 MVT ValueVT = ValueVTs[Value];
387 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000388
Chris Lattnerb606dba2008-04-28 06:44:42 +0000389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
393 }
394 }
395 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000396}
Chris Lattner1c08c712005-01-07 07:47:53 +0000397
398//===----------------------------------------------------------------------===//
399/// SelectionDAGLowering - This is the common target-independent lowering
400/// implementation that is parameterized by a TargetLowering object.
401/// Also, targets can overload any lowering method.
402///
403namespace llvm {
404class SelectionDAGLowering {
405 MachineBasicBlock *CurMBB;
406
Chris Lattner0da331f2007-02-04 01:31:47 +0000407 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Chris Lattnerd3948112005-01-17 22:19:26 +0000409 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
410 /// them up and then emit token factor nodes when possible. This allows us to
411 /// get simple disambiguation between loads without worrying about alias
412 /// analysis.
413 std::vector<SDOperand> PendingLoads;
414
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000415 /// PendingExports - CopyToReg nodes that copy values to virtual registers
416 /// for export to other blocks need to be emitted before any terminator
417 /// instruction, but they have no other ordering requirements. We bunch them
418 /// up and the emit a single tokenfactor for them just before terminator
419 /// instructions.
420 std::vector<SDOperand> PendingExports;
421
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000422 /// Case - A struct to record the Value for a switch case, and the
423 /// case's target basic block.
424 struct Case {
425 Constant* Low;
426 Constant* High;
427 MachineBasicBlock* BB;
428
429 Case() : Low(0), High(0), BB(0) { }
430 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
431 Low(low), High(high), BB(bb) { }
432 uint64_t size() const {
433 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
434 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
435 return (rHigh - rLow + 1ULL);
436 }
437 };
438
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000439 struct CaseBits {
440 uint64_t Mask;
441 MachineBasicBlock* BB;
442 unsigned Bits;
443
444 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
445 Mask(mask), BB(bb), Bits(bits) { }
446 };
447
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000448 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000449 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef CaseVector::iterator CaseItr;
451 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000452
453 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
454 /// of conditional branches.
455 struct CaseRec {
456 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
457 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
458
459 /// CaseBB - The MBB in which to emit the compare and branch
460 MachineBasicBlock *CaseBB;
461 /// LT, GE - If nonzero, we know the current case value must be less-than or
462 /// greater-than-or-equal-to these Constants.
463 Constant *LT;
464 Constant *GE;
465 /// Range - A pair of iterators representing the range of case values to be
466 /// processed at this point in the binary search tree.
467 CaseRange Range;
468 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000469
470 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000471
472 /// The comparison function for sorting the switch case values in the vector.
473 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000474 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000475 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000476 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
477 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
478 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
479 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000480 }
481 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000482
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000483 struct CaseBitsCmp {
484 bool operator () (const CaseBits& C1, const CaseBits& C2) {
485 return C1.Bits > C2.Bits;
486 }
487 };
488
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000489 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000490
Chris Lattner1c08c712005-01-07 07:47:53 +0000491public:
492 // TLI - This is information that describes the available target features we
493 // need for lowering. This indicates when operations are unavailable,
494 // implemented with a libcall, etc.
495 TargetLowering &TLI;
496 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000497 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000498 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000499
Nate Begemanf15485a2006-03-27 01:32:24 +0000500 /// SwitchCases - Vector of CaseBlock structures used to communicate
501 /// SwitchInst code generation information.
502 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000503 /// JTCases - Vector of JumpTable structures used to communicate
504 /// SwitchInst code generation information.
505 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000506 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000507
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 /// FuncInfo - Information about the function as a whole.
509 ///
510 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000511
512 /// GCI - Garbage collection metadata for the function.
513 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000514
515 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000516 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000517 FunctionLoweringInfo &funcinfo,
518 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000519 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000520 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000521 }
522
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000523 /// getRoot - Return the current virtual root of the Selection DAG,
524 /// flushing any PendingLoad items. This must be done before emitting
525 /// a store or any other node that may need to be ordered after any
526 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 ///
528 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000529 if (PendingLoads.empty())
530 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000531
Chris Lattnerd3948112005-01-17 22:19:26 +0000532 if (PendingLoads.size() == 1) {
533 SDOperand Root = PendingLoads[0];
534 DAG.setRoot(Root);
535 PendingLoads.clear();
536 return Root;
537 }
538
539 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000540 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
541 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000542 PendingLoads.clear();
543 DAG.setRoot(Root);
544 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000545 }
546
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000547 /// getControlRoot - Similar to getRoot, but instead of flushing all the
548 /// PendingLoad items, flush all the PendingExports items. It is necessary
549 /// to do this before emitting a terminator instruction.
550 ///
551 SDOperand getControlRoot() {
552 SDOperand Root = DAG.getRoot();
553
554 if (PendingExports.empty())
555 return Root;
556
557 // Turn all of the CopyToReg chains into one factored node.
558 if (Root.getOpcode() != ISD::EntryToken) {
559 unsigned i = 0, e = PendingExports.size();
560 for (; i != e; ++i) {
561 assert(PendingExports[i].Val->getNumOperands() > 1);
562 if (PendingExports[i].Val->getOperand(0) == Root)
563 break; // Don't add the root if we already indirectly depend on it.
564 }
565
566 if (i == e)
567 PendingExports.push_back(Root);
568 }
569
570 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
571 &PendingExports[0],
572 PendingExports.size());
573 PendingExports.clear();
574 DAG.setRoot(Root);
575 return Root;
576 }
577
578 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000579
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visit(Instruction &I) { visit(I.getOpcode(), I); }
581
582 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000583 // Note: this doesn't use InstVisitor, because it has to work with
584 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 switch (Opcode) {
586 default: assert(0 && "Unknown instruction type encountered!");
587 abort();
588 // Build the switch statement using the Instruction.def file.
589#define HANDLE_INST(NUM, OPCODE, CLASS) \
590 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
591#include "llvm/Instruction.def"
592 }
593 }
594
595 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
596
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000597 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000598 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000599 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
Chris Lattner199862b2006-03-16 19:57:50 +0000601 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner0da331f2007-02-04 01:31:47 +0000603 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000604 SDOperand &N = NodeMap[V];
605 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000606 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000608
Evan Cheng5c807602008-02-26 02:33:44 +0000609 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000610 std::set<unsigned> &OutputRegs,
611 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000612
Chris Lattner571e4342006-10-27 21:36:01 +0000613 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
614 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
615 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000616 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000617 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000618 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000619 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000620
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 // Terminator instructions.
622 void visitRet(ReturnInst &I);
623 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000624 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitUnreachable(UnreachableInst &I) { /* noop */ }
626
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000627 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000632 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000636 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000637 CaseRecVector& WorkList,
638 Value* SV,
639 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000640 bool handleBitTestsSwitchCase(CaseRec& CR,
641 CaseRecVector& WorkList,
642 Value* SV,
643 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000644 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000645 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
646 void visitBitTestCase(MachineBasicBlock* NextMBB,
647 unsigned Reg,
648 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000649 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000650 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
651 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000652
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000654 void visitInvoke(InvokeInst &I);
655 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000656
Dan Gohman7f321562007-06-25 16:23:39 +0000657 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000658 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000659 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000660 if (I.getType()->isFPOrFPVector())
661 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000662 else
Dan Gohman7f321562007-06-25 16:23:39 +0000663 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000664 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000665 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000666 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000667 if (I.getType()->isFPOrFPVector())
668 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000669 else
Dan Gohman7f321562007-06-25 16:23:39 +0000670 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000671 }
Dan Gohman7f321562007-06-25 16:23:39 +0000672 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
673 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
674 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
675 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
676 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
677 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
678 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
679 void visitOr (User &I) { visitBinary(I, ISD::OR); }
680 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000681 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000682 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
683 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000684 void visitICmp(User &I);
685 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000686 void visitVICmp(User &I);
687 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Chris Lattner2bbd8102006-03-29 00:11:43 +0000702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000704 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000705
Dan Gohman041e2eb2008-05-15 19:50:34 +0000706 void visitExtractValue(User &I);
707 void visitInsertValue(User &I);
708
Chris Lattner1c08c712005-01-07 07:47:53 +0000709 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000710 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000711
712 void visitMalloc(MallocInst &I);
713 void visitFree(FreeInst &I);
714 void visitAlloca(AllocaInst &I);
715 void visitLoad(LoadInst &I);
716 void visitStore(StoreInst &I);
717 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
718 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000719 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000720 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000721 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000722
Chris Lattner1c08c712005-01-07 07:47:53 +0000723 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724 void visitVAArg(VAArgInst &I);
725 void visitVAEnd(CallInst &I);
726 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000727
Dan Gohmanef5d1942008-03-11 21:11:25 +0000728 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000729
Chris Lattner1c08c712005-01-07 07:47:53 +0000730 void visitUserOp1(Instruction &I) {
731 assert(0 && "UserOp1 should not exist at instruction selection time!");
732 abort();
733 }
734 void visitUserOp2(Instruction &I) {
735 assert(0 && "UserOp2 should not exist at instruction selection time!");
736 abort();
737 }
Mon P Wang63307c32008-05-05 19:05:59 +0000738
739private:
740 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
741
Chris Lattner1c08c712005-01-07 07:47:53 +0000742};
743} // end namespace llvm
744
Dan Gohman6183f782007-07-05 20:12:34 +0000745
Duncan Sandsb988bac2008-02-11 20:58:28 +0000746/// getCopyFromParts - Create a value that contains the specified legal parts
747/// combined into the value they represent. If the parts combine to a type
748/// larger then ValueVT then AssertOp can be used to specify whether the extra
749/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000750/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000751static SDOperand getCopyFromParts(SelectionDAG &DAG,
752 const SDOperand *Parts,
753 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000754 MVT PartVT,
755 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000756 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000757 assert(NumParts > 0 && "No parts to assemble!");
758 TargetLowering &TLI = DAG.getTargetLoweringInfo();
759 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000760
Duncan Sands014e04a2008-02-12 20:46:31 +0000761 if (NumParts > 1) {
762 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000763 if (!ValueVT.isVector()) {
764 unsigned PartBits = PartVT.getSizeInBits();
765 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000766
Duncan Sands014e04a2008-02-12 20:46:31 +0000767 // Assemble the power of 2 part.
768 unsigned RoundParts = NumParts & (NumParts - 1) ?
769 1 << Log2_32(NumParts) : NumParts;
770 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000771 MVT RoundVT = RoundBits == ValueBits ?
772 ValueVT : MVT::getIntegerVT(RoundBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000773 SDOperand Lo, Hi;
774
775 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000776 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000777 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
778 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
779 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000780 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000781 Lo = Parts[0];
782 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000783 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000784 if (TLI.isBigEndian())
785 std::swap(Lo, Hi);
786 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
787
788 if (RoundParts < NumParts) {
789 // Assemble the trailing non-power-of-2 part.
790 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000791 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000792 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
793
794 // Combine the round and odd parts.
795 Lo = Val;
796 if (TLI.isBigEndian())
797 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000798 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000799 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
800 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000801 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000802 TLI.getShiftAmountTy()));
803 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
804 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
805 }
806 } else {
807 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000808 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000809 unsigned NumIntermediates;
810 unsigned NumRegs =
811 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
812 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000813 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000814 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000815 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
816 assert(RegisterVT == Parts[0].getValueType() &&
817 "Part type doesn't match part!");
818
819 // Assemble the parts into intermediate operands.
820 SmallVector<SDOperand, 8> Ops(NumIntermediates);
821 if (NumIntermediates == NumParts) {
822 // If the register was not expanded, truncate or copy the value,
823 // as appropriate.
824 for (unsigned i = 0; i != NumParts; ++i)
825 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
826 PartVT, IntermediateVT);
827 } else if (NumParts > 0) {
828 // If the intermediate type was expanded, build the intermediate operands
829 // from the parts.
830 assert(NumParts % NumIntermediates == 0 &&
831 "Must expand into a divisible number of parts!");
832 unsigned Factor = NumParts / NumIntermediates;
833 for (unsigned i = 0; i != NumIntermediates; ++i)
834 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
835 PartVT, IntermediateVT);
836 }
837
838 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
839 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000840 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000841 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
842 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000843 }
Dan Gohman6183f782007-07-05 20:12:34 +0000844 }
845
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 // There is now one part, held in Val. Correct it to match ValueVT.
847 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000848
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 if (PartVT == ValueVT)
850 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000851
Duncan Sands83ec4b62008-06-06 12:08:01 +0000852 if (PartVT.isVector()) {
853 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000854 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000855 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000856
Duncan Sands83ec4b62008-06-06 12:08:01 +0000857 if (ValueVT.isVector()) {
858 assert(ValueVT.getVectorElementType() == PartVT &&
859 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000860 "Only trivial scalar-to-vector conversions should get here!");
861 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
862 }
863
Duncan Sands83ec4b62008-06-06 12:08:01 +0000864 if (PartVT.isInteger() &&
865 ValueVT.isInteger()) {
866 if (ValueVT.getSizeInBits() < PartVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000867 // For a truncate, see if we have any information to
868 // indicate whether the truncated bits will always be
869 // zero or sign-extension.
870 if (AssertOp != ISD::DELETED_NODE)
871 Val = DAG.getNode(AssertOp, PartVT, Val,
872 DAG.getValueType(ValueVT));
873 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
874 } else {
875 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
876 }
877 }
878
Duncan Sands83ec4b62008-06-06 12:08:01 +0000879 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000880 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000881 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000882 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000883 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000884 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
885 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000886
Duncan Sands83ec4b62008-06-06 12:08:01 +0000887 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000888 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
889
890 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000891 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000892}
893
Duncan Sandsb988bac2008-02-11 20:58:28 +0000894/// getCopyToParts - Create a series of nodes that contain the specified value
895/// split into legal parts. If the parts contain more bits than Val, then, for
896/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000897static void getCopyToParts(SelectionDAG &DAG,
898 SDOperand Val,
899 SDOperand *Parts,
900 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000901 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000902 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000903 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000904 MVT PtrVT = TLI.getPointerTy();
905 MVT ValueVT = Val.getValueType();
906 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +0000907 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000908
Duncan Sands014e04a2008-02-12 20:46:31 +0000909 if (!NumParts)
910 return;
911
Duncan Sands83ec4b62008-06-06 12:08:01 +0000912 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000913 if (PartVT == ValueVT) {
914 assert(NumParts == 1 && "No-op copy with multiple parts!");
915 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000916 return;
917 }
918
Duncan Sands83ec4b62008-06-06 12:08:01 +0000919 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000920 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000921 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000922 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000923 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000924 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
925 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000926 Val = DAG.getNode(ExtendKind, ValueVT, Val);
927 } else {
928 assert(0 && "Unknown mismatch!");
929 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000930 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000931 // Different types of the same size.
932 assert(NumParts == 1 && PartVT != ValueVT);
933 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000934 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000935 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000936 if (PartVT.isInteger() && ValueVT.isInteger()) {
937 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000938 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000939 } else {
940 assert(0 && "Unknown mismatch!");
941 }
942 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000943
944 // The value may have changed - recompute ValueVT.
945 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000946 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000947 "Failed to tile the value with PartVT!");
948
949 if (NumParts == 1) {
950 assert(PartVT == ValueVT && "Type conversion failed!");
951 Parts[0] = Val;
952 return;
953 }
954
955 // Expand the value into multiple parts.
956 if (NumParts & (NumParts - 1)) {
957 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000958 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000959 "Do not know what to expand to!");
960 unsigned RoundParts = 1 << Log2_32(NumParts);
961 unsigned RoundBits = RoundParts * PartBits;
962 unsigned OddParts = NumParts - RoundParts;
963 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
964 DAG.getConstant(RoundBits,
965 TLI.getShiftAmountTy()));
966 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
967 if (TLI.isBigEndian())
968 // The odd parts were reversed by getCopyToParts - unreverse them.
969 std::reverse(Parts + RoundParts, Parts + NumParts);
970 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000971 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000972 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
973 }
974
975 // The number of parts is a power of 2. Repeatedly bisect the value using
976 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000977 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000978 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +0000979 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000980 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
981 for (unsigned i = 0; i < NumParts; i += StepSize) {
982 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000983 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Duncan Sands25eb0432008-03-12 20:30:08 +0000984 SDOperand &Part0 = Parts[i];
985 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000986
Duncan Sands25eb0432008-03-12 20:30:08 +0000987 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
988 DAG.getConstant(1, PtrVT));
989 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
990 DAG.getConstant(0, PtrVT));
991
992 if (ThisBits == PartBits && ThisVT != PartVT) {
993 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
994 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
995 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000996 }
997 }
998
999 if (TLI.isBigEndian())
1000 std::reverse(Parts, Parts + NumParts);
1001
1002 return;
1003 }
1004
1005 // Vector ValueVT.
1006 if (NumParts == 1) {
1007 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001008 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001009 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1010 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001011 assert(ValueVT.getVectorElementType() == PartVT &&
1012 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001013 "Only trivial vector-to-scalar conversions should get here!");
1014 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1015 DAG.getConstant(0, PtrVT));
1016 }
1017 }
1018
Dan Gohman6183f782007-07-05 20:12:34 +00001019 Parts[0] = Val;
1020 return;
1021 }
1022
1023 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001024 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001025 unsigned NumIntermediates;
1026 unsigned NumRegs =
1027 DAG.getTargetLoweringInfo()
1028 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1029 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001030 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001031
1032 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001033 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001034 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1035
1036 // Split the vector into intermediate operands.
1037 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1038 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001039 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001040 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1041 IntermediateVT, Val,
1042 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001043 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001044 else
1045 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1046 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001047 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001048
1049 // Split the intermediate operands into legal parts.
1050 if (NumParts == NumIntermediates) {
1051 // If the register was not expanded, promote or copy the value,
1052 // as appropriate.
1053 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001054 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001055 } else if (NumParts > 0) {
1056 // If the intermediate type was expanded, split each the value into
1057 // legal parts.
1058 assert(NumParts % NumIntermediates == 0 &&
1059 "Must expand into a divisible number of parts!");
1060 unsigned Factor = NumParts / NumIntermediates;
1061 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001062 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001063 }
1064}
1065
1066
Chris Lattner199862b2006-03-16 19:57:50 +00001067SDOperand SelectionDAGLowering::getValue(const Value *V) {
1068 SDOperand &N = NodeMap[V];
1069 if (N.Val) return N;
1070
Chris Lattner199862b2006-03-16 19:57:50 +00001071 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001072 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001073
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1075 return N = DAG.getConstant(CI->getValue(), VT);
1076
1077 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001078 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001079
1080 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001081 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001082
1083 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1084 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1085
Chris Lattner6833b062008-04-28 07:16:35 +00001086 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1087 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001088
1089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1090 visit(CE->getOpcode(), *CE);
1091 SDOperand N1 = NodeMap[V];
1092 assert(N1.Val && "visit didn't populate the ValueMap!");
1093 return N1;
1094 }
1095
Chris Lattner6833b062008-04-28 07:16:35 +00001096 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001097 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001098
Chris Lattner6833b062008-04-28 07:16:35 +00001099 // Now that we know the number and type of the elements, get that number of
1100 // elements into the Ops array based on what kind of constant it is.
1101 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001102 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1103 for (unsigned i = 0; i != NumElements; ++i)
1104 Ops.push_back(getValue(CP->getOperand(i)));
1105 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001106 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1107 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001108 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001109
Chris Lattnerb606dba2008-04-28 06:44:42 +00001110 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001111 if (isa<UndefValue>(C))
1112 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001113 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001114 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001115 else
Chris Lattner6833b062008-04-28 07:16:35 +00001116 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001117 Ops.assign(NumElements, Op);
1118 }
1119
1120 // Create a BUILD_VECTOR node.
1121 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001122 }
1123
Chris Lattnerb606dba2008-04-28 06:44:42 +00001124 // If this is a static alloca, generate it as the frameindex instead of
1125 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1127 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001128 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001129 if (SI != FuncInfo.StaticAllocaMap.end())
1130 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1131 }
1132
Chris Lattner251db182007-02-25 18:40:32 +00001133 unsigned InReg = FuncInfo.ValueMap[V];
1134 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001135
Chris Lattner6833b062008-04-28 07:16:35 +00001136 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001137 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001138 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001139}
1140
1141
Chris Lattner1c08c712005-01-07 07:47:53 +00001142void SelectionDAGLowering::visitRet(ReturnInst &I) {
1143 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001144 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001145 return;
1146 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001147
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001148 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001149 NewValues.push_back(getControlRoot());
1150 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001151 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sands83ec4b62008-06-06 12:08:01 +00001152 MVT VT = RetOp.getValueType();
Duncan Sandsb988bac2008-02-11 20:58:28 +00001153
Evan Cheng8e7d0562006-05-26 23:09:09 +00001154 // FIXME: C calling convention requires the return type to be promoted to
1155 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001156 if (VT.isInteger()) {
1157 MVT MinVT = TLI.getRegisterType(MVT::i32);
1158 if (VT.getSizeInBits() < MinVT.getSizeInBits())
Duncan Sandsb988bac2008-02-11 20:58:28 +00001159 VT = MinVT;
1160 }
1161
1162 unsigned NumParts = TLI.getNumRegisters(VT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001163 MVT PartVT = TLI.getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001164 SmallVector<SDOperand, 4> Parts(NumParts);
1165 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1166
1167 const Function *F = I.getParent()->getParent();
1168 if (F->paramHasAttr(0, ParamAttr::SExt))
1169 ExtendKind = ISD::SIGN_EXTEND;
1170 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1171 ExtendKind = ISD::ZERO_EXTEND;
1172
1173 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1174
1175 for (unsigned i = 0; i < NumParts; ++i) {
1176 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001177 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001178 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001179 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001180 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1181 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001182}
1183
Chris Lattner571e4342006-10-27 21:36:01 +00001184/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1185/// the current basic block, add it to ValueMap now so that we'll get a
1186/// CopyTo/FromReg.
1187void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1188 // No need to export constants.
1189 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1190
1191 // Already exported?
1192 if (FuncInfo.isExportedInst(V)) return;
1193
1194 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001195 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001196}
1197
Chris Lattner8c494ab2006-10-27 23:50:33 +00001198bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1199 const BasicBlock *FromBB) {
1200 // The operands of the setcc have to be in this block. We don't know
1201 // how to export them from some other block.
1202 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1203 // Can export from current BB.
1204 if (VI->getParent() == FromBB)
1205 return true;
1206
1207 // Is already exported, noop.
1208 return FuncInfo.isExportedInst(V);
1209 }
1210
1211 // If this is an argument, we can export it if the BB is the entry block or
1212 // if it is already exported.
1213 if (isa<Argument>(V)) {
1214 if (FromBB == &FromBB->getParent()->getEntryBlock())
1215 return true;
1216
1217 // Otherwise, can only export this if it is already exported.
1218 return FuncInfo.isExportedInst(V);
1219 }
1220
1221 // Otherwise, constants can always be exported.
1222 return true;
1223}
1224
Chris Lattner6a586c82006-10-29 21:01:20 +00001225static bool InBlock(const Value *V, const BasicBlock *BB) {
1226 if (const Instruction *I = dyn_cast<Instruction>(V))
1227 return I->getParent() == BB;
1228 return true;
1229}
1230
Chris Lattner571e4342006-10-27 21:36:01 +00001231/// FindMergedConditions - If Cond is an expression like
1232void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1233 MachineBasicBlock *TBB,
1234 MachineBasicBlock *FBB,
1235 MachineBasicBlock *CurBB,
1236 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001237 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001239
Reid Spencere4d87aa2006-12-23 06:05:41 +00001240 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1241 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001242 BOp->getParent() != CurBB->getBasicBlock() ||
1243 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1244 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001245 const BasicBlock *BB = CurBB->getBasicBlock();
1246
Reid Spencere4d87aa2006-12-23 06:05:41 +00001247 // If the leaf of the tree is a comparison, merge the condition into
1248 // the caseblock.
1249 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1250 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001251 // how to export them from some other block. If this is the first block
1252 // of the sequence, no exporting is needed.
1253 (CurBB == CurMBB ||
1254 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1255 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001256 BOp = cast<Instruction>(Cond);
1257 ISD::CondCode Condition;
1258 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1259 switch (IC->getPredicate()) {
1260 default: assert(0 && "Unknown icmp predicate opcode!");
1261 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1262 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1263 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1264 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1265 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1266 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1267 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1268 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1269 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1270 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1271 }
1272 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1273 ISD::CondCode FPC, FOC;
1274 switch (FC->getPredicate()) {
1275 default: assert(0 && "Unknown fcmp predicate opcode!");
1276 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1277 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1278 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1279 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1280 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1281 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1282 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001283 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1284 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001285 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1286 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1287 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1288 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1289 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1290 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1291 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1292 }
1293 if (FiniteOnlyFPMath())
1294 Condition = FOC;
1295 else
1296 Condition = FPC;
1297 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001298 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001299 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001300 }
1301
Chris Lattner571e4342006-10-27 21:36:01 +00001302 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001303 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001304 SwitchCases.push_back(CB);
1305 return;
1306 }
1307
1308 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001309 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001310 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001311 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001312 return;
1313 }
1314
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001315
1316 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001317 MachineFunction::iterator BBI = CurBB;
1318 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1319 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1320
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001321 if (Opc == Instruction::Or) {
1322 // Codegen X | Y as:
1323 // jmp_if_X TBB
1324 // jmp TmpBB
1325 // TmpBB:
1326 // jmp_if_Y TBB
1327 // jmp FBB
1328 //
Chris Lattner571e4342006-10-27 21:36:01 +00001329
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001330 // Emit the LHS condition.
1331 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1332
1333 // Emit the RHS condition into TmpBB.
1334 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1335 } else {
1336 assert(Opc == Instruction::And && "Unknown merge op!");
1337 // Codegen X & Y as:
1338 // jmp_if_X TmpBB
1339 // jmp FBB
1340 // TmpBB:
1341 // jmp_if_Y TBB
1342 // jmp FBB
1343 //
1344 // This requires creation of TmpBB after CurBB.
1345
1346 // Emit the LHS condition.
1347 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1348
1349 // Emit the RHS condition into TmpBB.
1350 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1351 }
Chris Lattner571e4342006-10-27 21:36:01 +00001352}
1353
Chris Lattnerdf19f272006-10-31 22:37:42 +00001354/// If the set of cases should be emitted as a series of branches, return true.
1355/// If we should emit this as a bunch of and/or'd together conditions, return
1356/// false.
1357static bool
1358ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1359 if (Cases.size() != 2) return true;
1360
Chris Lattner0ccb5002006-10-31 23:06:00 +00001361 // If this is two comparisons of the same values or'd or and'd together, they
1362 // will get folded into a single comparison, so don't emit two blocks.
1363 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1364 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1365 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1366 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1367 return false;
1368 }
1369
Chris Lattnerdf19f272006-10-31 22:37:42 +00001370 return true;
1371}
1372
Chris Lattner1c08c712005-01-07 07:47:53 +00001373void SelectionDAGLowering::visitBr(BranchInst &I) {
1374 // Update machine-CFG edges.
1375 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001376
1377 // Figure out which block is immediately after the current one.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 if (I.isUnconditional()) {
1384 // If this is not a fall-through branch, emit the branch.
1385 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001386 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001387 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001388
Chris Lattner57ab6592006-10-24 17:57:59 +00001389 // Update machine-CFG edges.
1390 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001391 return;
1392 }
1393
1394 // If this condition is one of the special cases we handle, do special stuff
1395 // now.
1396 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001397 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001398
1399 // If this is a series of conditions that are or'd or and'd together, emit
1400 // this as a sequence of branches instead of setcc's with and/or operations.
1401 // For example, instead of something like:
1402 // cmp A, B
1403 // C = seteq
1404 // cmp D, E
1405 // F = setle
1406 // or C, F
1407 // jnz foo
1408 // Emit:
1409 // cmp A, B
1410 // je foo
1411 // cmp D, E
1412 // jle foo
1413 //
1414 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1415 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001416 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001417 BOp->getOpcode() == Instruction::Or)) {
1418 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001419 // If the compares in later blocks need to use values not currently
1420 // exported from this block, export them now. This block should always
1421 // be the first entry.
1422 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1423
Chris Lattnerdf19f272006-10-31 22:37:42 +00001424 // Allow some cases to be rejected.
1425 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001426 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1427 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1428 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1429 }
1430
1431 // Emit the branch for this block.
1432 visitSwitchCase(SwitchCases[0]);
1433 SwitchCases.erase(SwitchCases.begin());
1434 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001435 }
1436
Chris Lattner0ccb5002006-10-31 23:06:00 +00001437 // Okay, we decided not to do this, remove any inserted MBB's and clear
1438 // SwitchCases.
1439 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1440 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1441
Chris Lattnerdf19f272006-10-31 22:37:42 +00001442 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001443 }
1444 }
Chris Lattner24525952006-10-24 18:07:37 +00001445
1446 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001447 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001448 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001449 // Use visitSwitchCase to actually insert the fast branch sequence for this
1450 // cond branch.
1451 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001452}
1453
Nate Begemanf15485a2006-03-27 01:32:24 +00001454/// visitSwitchCase - Emits the necessary code to represent a single node in
1455/// the binary search tree resulting from lowering a switch instruction.
1456void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001457 SDOperand Cond;
1458 SDOperand CondLHS = getValue(CB.CmpLHS);
1459
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001460 // Build the setcc now.
1461 if (CB.CmpMHS == NULL) {
1462 // Fold "(X == true)" to X and "(X == false)" to !X to
1463 // handle common cases produced by branch lowering.
1464 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1465 Cond = CondLHS;
1466 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1467 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1468 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1469 } else
1470 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1471 } else {
1472 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001473
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001474 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1475 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1476
1477 SDOperand CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001478 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001479
1480 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1481 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1482 } else {
1483 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1484 Cond = DAG.getSetCC(MVT::i1, SUB,
1485 DAG.getConstant(High-Low, VT), ISD::SETULE);
1486 }
1487
1488 }
1489
Nate Begemanf15485a2006-03-27 01:32:24 +00001490 // Set NextBlock to be the MBB immediately after the current one, if any.
1491 // This is used to avoid emitting unnecessary branches to the next block.
1492 MachineBasicBlock *NextBlock = 0;
1493 MachineFunction::iterator BBI = CurMBB;
1494 if (++BBI != CurMBB->getParent()->end())
1495 NextBlock = BBI;
1496
1497 // If the lhs block is the next block, invert the condition so that we can
1498 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001499 if (CB.TrueBB == NextBlock) {
1500 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001501 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1502 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1503 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001504 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001505 DAG.getBasicBlock(CB.TrueBB));
1506 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001507 DAG.setRoot(BrCond);
1508 else
1509 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001510 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001511 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001512 CurMBB->addSuccessor(CB.TrueBB);
1513 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001514}
1515
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001516/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001517void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001518 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001519 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001520 MVT PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001521 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001522 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1523 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1524 Table, Index));
1525 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001526}
1527
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001528/// visitJumpTableHeader - This function emits necessary code to produce index
1529/// in the JumpTable from switch case.
1530void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1531 SelectionDAGISel::JumpTableHeader &JTH) {
1532 // Subtract the lowest switch case value from the value being switched on
1533 // and conditional branch to default mbb if the result is greater than the
1534 // difference between smallest and largest cases.
1535 SDOperand SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001536 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001537 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1538 DAG.getConstant(JTH.First, VT));
1539
1540 // The SDNode we just created, which holds the value being switched on
1541 // minus the the smallest case value, needs to be copied to a virtual
1542 // register so it can be used as an index into the jump table in a
1543 // subsequent basic block. This value may be smaller or larger than the
1544 // target's pointer type, and therefore require extension or truncating.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001545 if (VT.getSizeInBits() > TLI.getPointerTy().getSizeInBits())
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001546 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1547 else
1548 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1549
1550 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001551 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001552 JT.Reg = JumpTableReg;
1553
1554 // Emit the range check for the jump table, and branch to the default
1555 // block for the switch statement if the value being switched on exceeds
1556 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001557 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001558 DAG.getConstant(JTH.Last-JTH.First,VT),
1559 ISD::SETUGT);
1560
1561 // Set NextBlock to be the MBB immediately after the current one, if any.
1562 // This is used to avoid emitting unnecessary branches to the next block.
1563 MachineBasicBlock *NextBlock = 0;
1564 MachineFunction::iterator BBI = CurMBB;
1565 if (++BBI != CurMBB->getParent()->end())
1566 NextBlock = BBI;
1567
1568 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1569 DAG.getBasicBlock(JT.Default));
1570
1571 if (JT.MBB == NextBlock)
1572 DAG.setRoot(BrCond);
1573 else
1574 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001575 DAG.getBasicBlock(JT.MBB)));
1576
1577 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001578}
1579
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001580/// visitBitTestHeader - This function emits necessary code to produce value
1581/// suitable for "bit tests"
1582void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1583 // Subtract the minimum value
1584 SDOperand SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001585 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001586 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1587 DAG.getConstant(B.First, VT));
1588
1589 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001590 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001591 DAG.getConstant(B.Range, VT),
1592 ISD::SETUGT);
1593
1594 SDOperand ShiftOp;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001595 if (VT.getSizeInBits() > TLI.getShiftAmountTy().getSizeInBits())
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001596 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1597 else
1598 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1599
1600 // Make desired shift
1601 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1602 DAG.getConstant(1, TLI.getPointerTy()),
1603 ShiftOp);
1604
1605 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001606 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001607 B.Reg = SwitchReg;
1608
1609 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1610 DAG.getBasicBlock(B.Default));
1611
1612 // Set NextBlock to be the MBB immediately after the current one, if any.
1613 // This is used to avoid emitting unnecessary branches to the next block.
1614 MachineBasicBlock *NextBlock = 0;
1615 MachineFunction::iterator BBI = CurMBB;
1616 if (++BBI != CurMBB->getParent()->end())
1617 NextBlock = BBI;
1618
1619 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1620 if (MBB == NextBlock)
1621 DAG.setRoot(BrRange);
1622 else
1623 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1624 DAG.getBasicBlock(MBB)));
1625
1626 CurMBB->addSuccessor(B.Default);
1627 CurMBB->addSuccessor(MBB);
1628
1629 return;
1630}
1631
1632/// visitBitTestCase - this function produces one "bit test"
1633void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1634 unsigned Reg,
1635 SelectionDAGISel::BitTestCase &B) {
1636 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001637 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001638
1639 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1640 SwitchVal,
1641 DAG.getConstant(B.Mask,
1642 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001643 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001644 DAG.getConstant(0, TLI.getPointerTy()),
1645 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001646 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001647 AndCmp, DAG.getBasicBlock(B.TargetBB));
1648
1649 // Set NextBlock to be the MBB immediately after the current one, if any.
1650 // This is used to avoid emitting unnecessary branches to the next block.
1651 MachineBasicBlock *NextBlock = 0;
1652 MachineFunction::iterator BBI = CurMBB;
1653 if (++BBI != CurMBB->getParent()->end())
1654 NextBlock = BBI;
1655
1656 if (NextMBB == NextBlock)
1657 DAG.setRoot(BrAnd);
1658 else
1659 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1660 DAG.getBasicBlock(NextMBB)));
1661
1662 CurMBB->addSuccessor(B.TargetBB);
1663 CurMBB->addSuccessor(NextMBB);
1664
1665 return;
1666}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001667
Jim Laskeyb180aa12007-02-21 22:53:45 +00001668void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1669 // Retrieve successors.
1670 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001671 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001672
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001673 if (isa<InlineAsm>(I.getCalledValue()))
1674 visitInlineAsm(&I);
1675 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001676 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001677
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001678 // If the value of the invoke is used outside of its defining block, make it
1679 // available as a virtual register.
1680 if (!I.use_empty()) {
1681 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1682 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001683 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001684 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001685
1686 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001687 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001688 DAG.getBasicBlock(Return)));
1689
1690 // Update successor info
1691 CurMBB->addSuccessor(Return);
1692 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001693}
1694
1695void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1696}
1697
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001698/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001699/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001700bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001701 CaseRecVector& WorkList,
1702 Value* SV,
1703 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001704 Case& BackCase = *(CR.Range.second-1);
1705
1706 // Size is the number of Cases represented by this range.
1707 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001708 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001709 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001710
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001711 // Get the MachineFunction which holds the current MBB. This is used when
1712 // inserting any additional MBBs necessary to represent the switch.
1713 MachineFunction *CurMF = CurMBB->getParent();
1714
1715 // Figure out which block is immediately after the current one.
1716 MachineBasicBlock *NextBlock = 0;
1717 MachineFunction::iterator BBI = CR.CaseBB;
1718
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001719 if (++BBI != CurMBB->getParent()->end())
1720 NextBlock = BBI;
1721
1722 // TODO: If any two of the cases has the same destination, and if one value
1723 // is the same as the other, but has one bit unset that the other has set,
1724 // use bit manipulation to do two compares at once. For example:
1725 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1726
1727 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001728 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001729 // The last case block won't fall through into 'NextBlock' if we emit the
1730 // branches in this order. See if rearranging a case value would help.
1731 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001732 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001733 std::swap(*I, BackCase);
1734 break;
1735 }
1736 }
1737 }
1738
1739 // Create a CaseBlock record representing a conditional branch to
1740 // the Case's target mbb if the value being switched on SV is equal
1741 // to C.
1742 MachineBasicBlock *CurBlock = CR.CaseBB;
1743 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1744 MachineBasicBlock *FallThrough;
1745 if (I != E-1) {
1746 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1747 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1748 } else {
1749 // If the last case doesn't match, go to the default block.
1750 FallThrough = Default;
1751 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001752
1753 Value *RHS, *LHS, *MHS;
1754 ISD::CondCode CC;
1755 if (I->High == I->Low) {
1756 // This is just small small case range :) containing exactly 1 case
1757 CC = ISD::SETEQ;
1758 LHS = SV; RHS = I->High; MHS = NULL;
1759 } else {
1760 CC = ISD::SETLE;
1761 LHS = I->Low; MHS = SV; RHS = I->High;
1762 }
1763 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1764 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001765
1766 // If emitting the first comparison, just call visitSwitchCase to emit the
1767 // code into the current block. Otherwise, push the CaseBlock onto the
1768 // vector to be later processed by SDISel, and insert the node's MBB
1769 // before the next MBB.
1770 if (CurBlock == CurMBB)
1771 visitSwitchCase(CB);
1772 else
1773 SwitchCases.push_back(CB);
1774
1775 CurBlock = FallThrough;
1776 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001777
1778 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001779}
1780
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001781static inline bool areJTsAllowed(const TargetLowering &TLI) {
1782 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1783 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1784}
1785
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001786/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001787bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001788 CaseRecVector& WorkList,
1789 Value* SV,
1790 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001791 Case& FrontCase = *CR.Range.first;
1792 Case& BackCase = *(CR.Range.second-1);
1793
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001794 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1795 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1796
1797 uint64_t TSize = 0;
1798 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1799 I!=E; ++I)
1800 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001801
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001802 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001803 return false;
1804
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001805 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1806 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001807 return false;
1808
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001809 DOUT << "Lowering jump table\n"
1810 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001811 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001812
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001813 // Get the MachineFunction which holds the current MBB. This is used when
1814 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001815 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001816
1817 // Figure out which block is immediately after the current one.
1818 MachineBasicBlock *NextBlock = 0;
1819 MachineFunction::iterator BBI = CR.CaseBB;
1820
1821 if (++BBI != CurMBB->getParent()->end())
1822 NextBlock = BBI;
1823
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001824 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1825
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001826 // Create a new basic block to hold the code for loading the address
1827 // of the jump table, and jumping to it. Update successor information;
1828 // we will either branch to the default case for the switch, or the jump
1829 // table.
1830 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1831 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1832 CR.CaseBB->addSuccessor(Default);
1833 CR.CaseBB->addSuccessor(JumpTableBB);
1834
1835 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001836 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001837 // a case statement, push the case's BB onto the vector, otherwise, push
1838 // the default BB.
1839 std::vector<MachineBasicBlock*> DestBBs;
1840 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001841 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1842 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1843 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1844
1845 if ((Low <= TEI) && (TEI <= High)) {
1846 DestBBs.push_back(I->BB);
1847 if (TEI==High)
1848 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001849 } else {
1850 DestBBs.push_back(Default);
1851 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001852 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001853
1854 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001855 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001856 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1857 E = DestBBs.end(); I != E; ++I) {
1858 if (!SuccsHandled[(*I)->getNumber()]) {
1859 SuccsHandled[(*I)->getNumber()] = true;
1860 JumpTableBB->addSuccessor(*I);
1861 }
1862 }
1863
1864 // Create a jump table index for this jump table, or return an existing
1865 // one.
1866 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1867
1868 // Set the jump table information so that we can codegen it as a second
1869 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001870 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001871 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1872 (CR.CaseBB == CurMBB));
1873 if (CR.CaseBB == CurMBB)
1874 visitJumpTableHeader(JT, JTH);
1875
1876 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001877
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001878 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001879}
1880
1881/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1882/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001883bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001884 CaseRecVector& WorkList,
1885 Value* SV,
1886 MachineBasicBlock* Default) {
1887 // Get the MachineFunction which holds the current MBB. This is used when
1888 // inserting any additional MBBs necessary to represent the switch.
1889 MachineFunction *CurMF = CurMBB->getParent();
1890
1891 // Figure out which block is immediately after the current one.
1892 MachineBasicBlock *NextBlock = 0;
1893 MachineFunction::iterator BBI = CR.CaseBB;
1894
1895 if (++BBI != CurMBB->getParent()->end())
1896 NextBlock = BBI;
1897
1898 Case& FrontCase = *CR.Range.first;
1899 Case& BackCase = *(CR.Range.second-1);
1900 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1901
1902 // Size is the number of Cases represented by this range.
1903 unsigned Size = CR.Range.second - CR.Range.first;
1904
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001905 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1906 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001907 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001908 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001909
1910 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1911 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001912 uint64_t TSize = 0;
1913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1914 I!=E; ++I)
1915 TSize += I->size();
1916
1917 uint64_t LSize = FrontCase.size();
1918 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001919 DOUT << "Selecting best pivot: \n"
1920 << "First: " << First << ", Last: " << Last <<"\n"
1921 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001922 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001923 J!=E; ++I, ++J) {
1924 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1925 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001926 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001927 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1928 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001929 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001930 // Should always split in some non-trivial place
1931 DOUT <<"=>Step\n"
1932 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1933 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1934 << "Metric: " << Metric << "\n";
1935 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001936 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001937 FMetric = Metric;
1938 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001939 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001940
1941 LSize += J->size();
1942 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001943 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001944 if (areJTsAllowed(TLI)) {
1945 // If our case is dense we *really* should handle it earlier!
1946 assert((FMetric > 0) && "Should handle dense range earlier!");
1947 } else {
1948 Pivot = CR.Range.first + Size/2;
1949 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001950
1951 CaseRange LHSR(CR.Range.first, Pivot);
1952 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001953 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001954 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1955
1956 // We know that we branch to the LHS if the Value being switched on is
1957 // less than the Pivot value, C. We use this to optimize our binary
1958 // tree a bit, by recognizing that if SV is greater than or equal to the
1959 // LHS's Case Value, and that Case Value is exactly one less than the
1960 // Pivot's Value, then we can branch directly to the LHS's Target,
1961 // rather than creating a leaf node for it.
1962 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001963 LHSR.first->High == CR.GE &&
1964 cast<ConstantInt>(C)->getSExtValue() ==
1965 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1966 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001967 } else {
1968 TrueBB = new MachineBasicBlock(LLVMBB);
1969 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1970 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1971 }
1972
1973 // Similar to the optimization above, if the Value being switched on is
1974 // known to be less than the Constant CR.LT, and the current Case Value
1975 // is CR.LT - 1, then we can branch directly to the target block for
1976 // the current Case Value, rather than emitting a RHS leaf node for it.
1977 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001978 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1979 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1980 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001981 } else {
1982 FalseBB = new MachineBasicBlock(LLVMBB);
1983 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1984 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1985 }
1986
1987 // Create a CaseBlock record representing a conditional branch to
1988 // the LHS node if the value being switched on SV is less than C.
1989 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001990 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1991 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001992
1993 if (CR.CaseBB == CurMBB)
1994 visitSwitchCase(CB);
1995 else
1996 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001997
1998 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001999}
2000
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002001/// handleBitTestsSwitchCase - if current case range has few destination and
2002/// range span less, than machine word bitwidth, encode case range into series
2003/// of masks and emit bit tests with these masks.
2004bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2005 CaseRecVector& WorkList,
2006 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002007 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002008 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002009
2010 Case& FrontCase = *CR.Range.first;
2011 Case& BackCase = *(CR.Range.second-1);
2012
2013 // Get the MachineFunction which holds the current MBB. This is used when
2014 // inserting any additional MBBs necessary to represent the switch.
2015 MachineFunction *CurMF = CurMBB->getParent();
2016
2017 unsigned numCmps = 0;
2018 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2019 I!=E; ++I) {
2020 // Single case counts one, case range - two.
2021 if (I->Low == I->High)
2022 numCmps +=1;
2023 else
2024 numCmps +=2;
2025 }
2026
2027 // Count unique destinations
2028 SmallSet<MachineBasicBlock*, 4> Dests;
2029 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2030 Dests.insert(I->BB);
2031 if (Dests.size() > 3)
2032 // Don't bother the code below, if there are too much unique destinations
2033 return false;
2034 }
2035 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2036 << "Total number of comparisons: " << numCmps << "\n";
2037
2038 // Compute span of values.
2039 Constant* minValue = FrontCase.Low;
2040 Constant* maxValue = BackCase.High;
2041 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2042 cast<ConstantInt>(minValue)->getSExtValue();
2043 DOUT << "Compare range: " << range << "\n"
2044 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2045 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2046
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002047 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002048 (!(Dests.size() == 1 && numCmps >= 3) &&
2049 !(Dests.size() == 2 && numCmps >= 5) &&
2050 !(Dests.size() >= 3 && numCmps >= 6)))
2051 return false;
2052
2053 DOUT << "Emitting bit tests\n";
2054 int64_t lowBound = 0;
2055
2056 // Optimize the case where all the case values fit in a
2057 // word without having to subtract minValue. In this case,
2058 // we can optimize away the subtraction.
2059 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002060 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002061 range = cast<ConstantInt>(maxValue)->getSExtValue();
2062 } else {
2063 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2064 }
2065
2066 CaseBitsVector CasesBits;
2067 unsigned i, count = 0;
2068
2069 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2070 MachineBasicBlock* Dest = I->BB;
2071 for (i = 0; i < count; ++i)
2072 if (Dest == CasesBits[i].BB)
2073 break;
2074
2075 if (i == count) {
2076 assert((count < 3) && "Too much destinations to test!");
2077 CasesBits.push_back(CaseBits(0, Dest, 0));
2078 count++;
2079 }
2080
2081 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2082 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2083
2084 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002085 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002086 CasesBits[i].Bits++;
2087 }
2088
2089 }
2090 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2091
2092 SelectionDAGISel::BitTestInfo BTC;
2093
2094 // Figure out which block is immediately after the current one.
2095 MachineFunction::iterator BBI = CR.CaseBB;
2096 ++BBI;
2097
2098 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2099
2100 DOUT << "Cases:\n";
2101 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2102 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2103 << ", BB: " << CasesBits[i].BB << "\n";
2104
2105 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2106 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2107 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2108 CaseBB,
2109 CasesBits[i].BB));
2110 }
2111
2112 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002113 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002114 CR.CaseBB, Default, BTC);
2115
2116 if (CR.CaseBB == CurMBB)
2117 visitBitTestHeader(BTB);
2118
2119 BitTestCases.push_back(BTB);
2120
2121 return true;
2122}
2123
2124
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002125/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002126unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2127 const SwitchInst& SI) {
2128 unsigned numCmps = 0;
2129
2130 // Start with "simple" cases
2131 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2132 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2133 Cases.push_back(Case(SI.getSuccessorValue(i),
2134 SI.getSuccessorValue(i),
2135 SMBB));
2136 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002137 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002138
2139 // Merge case into clusters
2140 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002141 // Must recompute end() each iteration because it may be
2142 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002143 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002144 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2145 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2146 MachineBasicBlock* nextBB = J->BB;
2147 MachineBasicBlock* currentBB = I->BB;
2148
2149 // If the two neighboring cases go to the same destination, merge them
2150 // into a single case.
2151 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2152 I->High = J->High;
2153 J = Cases.erase(J);
2154 } else {
2155 I = J++;
2156 }
2157 }
2158
2159 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2160 if (I->Low != I->High)
2161 // A range counts double, since it requires two compares.
2162 ++numCmps;
2163 }
2164
2165 return numCmps;
2166}
2167
2168void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002169 // Figure out which block is immediately after the current one.
2170 MachineBasicBlock *NextBlock = 0;
2171 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002172
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002173 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002174
Nate Begemanf15485a2006-03-27 01:32:24 +00002175 // If there is only the default destination, branch to it if it is not the
2176 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002177 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002178 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002179
Nate Begemanf15485a2006-03-27 01:32:24 +00002180 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002181 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002182 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002183 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002184
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002185 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002186 return;
2187 }
2188
2189 // If there are any non-default case statements, create a vector of Cases
2190 // representing each one, and sort the vector so that we can efficiently
2191 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002192 CaseVector Cases;
2193 unsigned numCmps = Clusterify(Cases, SI);
2194 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2195 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002196
Nate Begemanf15485a2006-03-27 01:32:24 +00002197 // Get the Value to be switched on and default basic blocks, which will be
2198 // inserted into CaseBlock records, representing basic blocks in the binary
2199 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002200 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002201
Nate Begemanf15485a2006-03-27 01:32:24 +00002202 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002203 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002204 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2205
2206 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002207 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002208 CaseRec CR = WorkList.back();
2209 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002210
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002211 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2212 continue;
2213
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002214 // If the range has few cases (two or less) emit a series of specific
2215 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002216 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2217 continue;
2218
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002219 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002220 // target supports indirect branches, then emit a jump table rather than
2221 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002222 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2223 continue;
2224
2225 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2226 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2227 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002228 }
2229}
2230
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002231
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002232void SelectionDAGLowering::visitSub(User &I) {
2233 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002234 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002235 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002236 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2237 const VectorType *DestTy = cast<VectorType>(I.getType());
2238 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002239 if (ElTy->isFloatingPoint()) {
2240 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002241 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002242 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2243 if (CV == CNZ) {
2244 SDOperand Op2 = getValue(I.getOperand(1));
2245 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2246 return;
2247 }
Dan Gohman7f321562007-06-25 16:23:39 +00002248 }
2249 }
2250 }
2251 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002252 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002253 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002254 SDOperand Op2 = getValue(I.getOperand(1));
2255 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2256 return;
2257 }
Dan Gohman7f321562007-06-25 16:23:39 +00002258 }
2259
2260 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002261}
2262
Dan Gohman7f321562007-06-25 16:23:39 +00002263void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002264 SDOperand Op1 = getValue(I.getOperand(0));
2265 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002266
2267 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002268}
2269
Nate Begemane21ea612005-11-18 07:42:56 +00002270void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2271 SDOperand Op1 = getValue(I.getOperand(0));
2272 SDOperand Op2 = getValue(I.getOperand(1));
2273
Duncan Sands83ec4b62008-06-06 12:08:01 +00002274 if (TLI.getShiftAmountTy().getSizeInBits() <
2275 Op2.getValueType().getSizeInBits())
Reid Spencer832254e2007-02-02 02:16:23 +00002276 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2277 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2278 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002279
Chris Lattner1c08c712005-01-07 07:47:53 +00002280 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2281}
2282
Reid Spencer45fb3f32006-11-20 01:22:35 +00002283void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002284 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2285 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2286 predicate = IC->getPredicate();
2287 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2288 predicate = ICmpInst::Predicate(IC->getPredicate());
2289 SDOperand Op1 = getValue(I.getOperand(0));
2290 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002291 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002292 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002293 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2294 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2295 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2296 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2297 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2298 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2299 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2300 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2301 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2302 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2303 default:
2304 assert(!"Invalid ICmp predicate value");
2305 Opcode = ISD::SETEQ;
2306 break;
2307 }
2308 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2309}
2310
2311void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002312 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2313 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2314 predicate = FC->getPredicate();
2315 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2316 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002317 SDOperand Op1 = getValue(I.getOperand(0));
2318 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002319 ISD::CondCode Condition, FOC, FPC;
2320 switch (predicate) {
2321 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2322 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2323 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2324 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2325 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2326 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2327 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002328 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2329 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002330 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2331 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2332 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2333 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2334 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2335 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2336 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2337 default:
2338 assert(!"Invalid FCmp predicate value");
2339 FOC = FPC = ISD::SETFALSE;
2340 break;
2341 }
2342 if (FiniteOnlyFPMath())
2343 Condition = FOC;
2344 else
2345 Condition = FPC;
2346 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002347}
2348
Nate Begemanb43e9c12008-05-12 19:40:03 +00002349void SelectionDAGLowering::visitVICmp(User &I) {
2350 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2351 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2352 predicate = IC->getPredicate();
2353 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2354 predicate = ICmpInst::Predicate(IC->getPredicate());
2355 SDOperand Op1 = getValue(I.getOperand(0));
2356 SDOperand Op2 = getValue(I.getOperand(1));
2357 ISD::CondCode Opcode;
2358 switch (predicate) {
2359 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2360 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2361 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2362 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2363 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2364 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2365 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2366 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2367 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2368 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2369 default:
2370 assert(!"Invalid ICmp predicate value");
2371 Opcode = ISD::SETEQ;
2372 break;
2373 }
2374 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2375}
2376
2377void SelectionDAGLowering::visitVFCmp(User &I) {
2378 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2379 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2380 predicate = FC->getPredicate();
2381 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2382 predicate = FCmpInst::Predicate(FC->getPredicate());
2383 SDOperand Op1 = getValue(I.getOperand(0));
2384 SDOperand Op2 = getValue(I.getOperand(1));
2385 ISD::CondCode Condition, FOC, FPC;
2386 switch (predicate) {
2387 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2388 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2389 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2390 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2391 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2392 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2393 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2394 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2395 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2396 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2397 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2398 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2399 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2400 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2401 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2402 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2403 default:
2404 assert(!"Invalid VFCmp predicate value");
2405 FOC = FPC = ISD::SETFALSE;
2406 break;
2407 }
2408 if (FiniteOnlyFPMath())
2409 Condition = FOC;
2410 else
2411 Condition = FPC;
2412
Duncan Sands83ec4b62008-06-06 12:08:01 +00002413 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002414
2415 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2416}
2417
Chris Lattner1c08c712005-01-07 07:47:53 +00002418void SelectionDAGLowering::visitSelect(User &I) {
2419 SDOperand Cond = getValue(I.getOperand(0));
2420 SDOperand TrueVal = getValue(I.getOperand(1));
2421 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002422 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2423 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002424}
2425
Reid Spencer3da59db2006-11-27 01:05:10 +00002426
2427void SelectionDAGLowering::visitTrunc(User &I) {
2428 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2429 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002430 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002431 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2432}
2433
2434void SelectionDAGLowering::visitZExt(User &I) {
2435 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2436 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2437 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002438 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002439 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2440}
2441
2442void SelectionDAGLowering::visitSExt(User &I) {
2443 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2444 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2445 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002446 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002447 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2448}
2449
2450void SelectionDAGLowering::visitFPTrunc(User &I) {
2451 // FPTrunc is never a no-op cast, no need to check
2452 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002453 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002454 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002455}
2456
2457void SelectionDAGLowering::visitFPExt(User &I){
2458 // FPTrunc is never a no-op cast, no need to check
2459 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002460 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002461 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2462}
2463
2464void SelectionDAGLowering::visitFPToUI(User &I) {
2465 // FPToUI is never a no-op cast, no need to check
2466 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002467 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002468 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2469}
2470
2471void SelectionDAGLowering::visitFPToSI(User &I) {
2472 // FPToSI is never a no-op cast, no need to check
2473 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002474 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002475 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2476}
2477
2478void SelectionDAGLowering::visitUIToFP(User &I) {
2479 // UIToFP is never a no-op cast, no need to check
2480 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002481 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002482 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2483}
2484
2485void SelectionDAGLowering::visitSIToFP(User &I){
2486 // UIToFP is never a no-op cast, no need to check
2487 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002488 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002489 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2490}
2491
2492void SelectionDAGLowering::visitPtrToInt(User &I) {
2493 // What to do depends on the size of the integer and the size of the pointer.
2494 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002495 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002496 MVT SrcVT = N.getValueType();
2497 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002498 SDOperand Result;
Duncan Sands83ec4b62008-06-06 12:08:01 +00002499 if (DestVT.getSizeInBits() < SrcVT.getSizeInBits())
Reid Spencer3da59db2006-11-27 01:05:10 +00002500 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2501 else
2502 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2503 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2504 setValue(&I, Result);
2505}
Chris Lattner1c08c712005-01-07 07:47:53 +00002506
Reid Spencer3da59db2006-11-27 01:05:10 +00002507void SelectionDAGLowering::visitIntToPtr(User &I) {
2508 // What to do depends on the size of the integer and the size of the pointer.
2509 // We can either truncate, zero extend, or no-op, accordingly.
2510 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002511 MVT SrcVT = N.getValueType();
2512 MVT DestVT = TLI.getValueType(I.getType());
2513 if (DestVT.getSizeInBits() < SrcVT.getSizeInBits())
Reid Spencer3da59db2006-11-27 01:05:10 +00002514 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2515 else
2516 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2517 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2518}
2519
2520void SelectionDAGLowering::visitBitCast(User &I) {
2521 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002522 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002523
2524 // BitCast assures us that source and destination are the same size so this
2525 // is either a BIT_CONVERT or a no-op.
2526 if (DestVT != N.getValueType())
2527 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2528 else
2529 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002530}
2531
Chris Lattner2bbd8102006-03-29 00:11:43 +00002532void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002533 SDOperand InVec = getValue(I.getOperand(0));
2534 SDOperand InVal = getValue(I.getOperand(1));
2535 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2536 getValue(I.getOperand(2)));
2537
Dan Gohman7f321562007-06-25 16:23:39 +00002538 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2539 TLI.getValueType(I.getType()),
2540 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002541}
2542
Chris Lattner2bbd8102006-03-29 00:11:43 +00002543void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002544 SDOperand InVec = getValue(I.getOperand(0));
2545 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2546 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002547 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002548 TLI.getValueType(I.getType()), InVec, InIdx));
2549}
Chris Lattnerc7029802006-03-18 01:44:44 +00002550
Chris Lattner3e104b12006-04-08 04:15:24 +00002551void SelectionDAGLowering::visitShuffleVector(User &I) {
2552 SDOperand V1 = getValue(I.getOperand(0));
2553 SDOperand V2 = getValue(I.getOperand(1));
2554 SDOperand Mask = getValue(I.getOperand(2));
2555
Dan Gohman7f321562007-06-25 16:23:39 +00002556 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2557 TLI.getValueType(I.getType()),
2558 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002559}
2560
Dan Gohman041e2eb2008-05-15 19:50:34 +00002561void SelectionDAGLowering::visitInsertValue(User &I) {
2562 assert(0 && "insertvalue instruction not implemented");
2563 abort();
2564}
2565
2566void SelectionDAGLowering::visitExtractValue(User &I) {
2567 assert(0 && "extractvalue instruction not implemented");
2568 abort();
2569}
2570
Chris Lattner3e104b12006-04-08 04:15:24 +00002571
Chris Lattner1c08c712005-01-07 07:47:53 +00002572void SelectionDAGLowering::visitGetElementPtr(User &I) {
2573 SDOperand N = getValue(I.getOperand(0));
2574 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002575
2576 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2577 OI != E; ++OI) {
2578 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002579 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002580 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002581 if (Field) {
2582 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002583 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002584 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002585 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002586 }
2587 Ty = StTy->getElementType(Field);
2588 } else {
2589 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002590
Chris Lattner7c0104b2005-11-09 04:45:33 +00002591 // If this is a constant subscript, handle it quickly.
2592 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002593 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002594 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002595 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002596 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2597 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002598 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002599 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002600
2601 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002602 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002603 SDOperand IdxN = getValue(Idx);
2604
2605 // If the index is smaller or larger than intptr_t, truncate or extend
2606 // it.
2607 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002608 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002609 } else if (IdxN.getValueType() > N.getValueType())
2610 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2611
2612 // If this is a multiply by a power of two, turn it into a shl
2613 // immediately. This is a very common case.
2614 if (isPowerOf2_64(ElementSize)) {
2615 unsigned Amt = Log2_64(ElementSize);
2616 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002617 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002618 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2619 continue;
2620 }
2621
Chris Lattner0bd48932008-01-17 07:00:52 +00002622 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2624 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002625 }
2626 }
2627 setValue(&I, N);
2628}
2629
2630void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2631 // If this is a fixed sized alloca in the entry block of the function,
2632 // allocate it statically on the stack.
2633 if (FuncInfo.StaticAllocaMap.count(&I))
2634 return; // getValue will auto-populate this.
2635
2636 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002637 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002638 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002639 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002640 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002641
2642 SDOperand AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002643 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002644 if (IntPtr < AllocSize.getValueType())
2645 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2646 else if (IntPtr > AllocSize.getValueType())
2647 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002648
Chris Lattner68cd65e2005-01-22 23:04:37 +00002649 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002650 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002651
Evan Cheng45157792007-08-16 23:46:29 +00002652 // Handle alignment. If the requested alignment is less than or equal to
2653 // the stack alignment, ignore it. If the size is greater than or equal to
2654 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002655 unsigned StackAlign =
2656 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002657 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002658 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002659
2660 // Round the size of the allocation up to the stack alignment size
2661 // by add SA-1 to the size.
2662 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002663 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002664 // Mask out the low bits for alignment purposes.
2665 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002666 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002667
Chris Lattner0bd48932008-01-17 07:00:52 +00002668 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002669 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002670 MVT::Other);
2671 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002672 setValue(&I, DSA);
2673 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002674
2675 // Inform the Frame Information that we have just allocated a variable-sized
2676 // object.
2677 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2678}
2679
Chris Lattner1c08c712005-01-07 07:47:53 +00002680void SelectionDAGLowering::visitLoad(LoadInst &I) {
2681 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002682
Chris Lattnerd3948112005-01-17 22:19:26 +00002683 SDOperand Root;
2684 if (I.isVolatile())
2685 Root = getRoot();
2686 else {
2687 // Do not serialize non-volatile loads against each other.
2688 Root = DAG.getRoot();
2689 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002690
Evan Cheng466685d2006-10-09 20:57:25 +00002691 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002692 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002693}
2694
2695SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002696 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002697 bool isVolatile,
2698 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002699 SDOperand L =
2700 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2701 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002702
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002703 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002704 DAG.setRoot(L.getValue(1));
2705 else
2706 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002707
2708 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002709}
2710
2711
2712void SelectionDAGLowering::visitStore(StoreInst &I) {
2713 Value *SrcV = I.getOperand(0);
2714 SDOperand Src = getValue(SrcV);
2715 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002716 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002717 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002718}
2719
Chris Lattner0eade312006-03-24 02:22:33 +00002720/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2721/// node.
2722void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2723 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002724 bool HasChain = !I.doesNotAccessMemory();
2725 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2726
Chris Lattner0eade312006-03-24 02:22:33 +00002727 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002728 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002729 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2730 if (OnlyLoad) {
2731 // We don't need to serialize loads against other loads.
2732 Ops.push_back(DAG.getRoot());
2733 } else {
2734 Ops.push_back(getRoot());
2735 }
2736 }
Chris Lattner0eade312006-03-24 02:22:33 +00002737
2738 // Add the intrinsic ID as an integer operand.
2739 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2740
2741 // Add all operands of the call to the operand list.
2742 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2743 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002744 assert(TLI.isTypeLegal(Op.getValueType()) &&
2745 "Intrinsic uses a non-legal type?");
2746 Ops.push_back(Op);
2747 }
2748
Duncan Sands83ec4b62008-06-06 12:08:01 +00002749 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00002750 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002751 MVT VT = TLI.getValueType(I.getType());
2752 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002753 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002754 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00002755
Duncan Sands83ec4b62008-06-06 12:08:01 +00002756 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00002757 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2758 }
2759
2760 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2761 VTs.push_back(VT);
2762 }
2763 if (HasChain)
2764 VTs.push_back(MVT::Other);
2765
Duncan Sands83ec4b62008-06-06 12:08:01 +00002766 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002767
Chris Lattner0eade312006-03-24 02:22:33 +00002768 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002769 SDOperand Result;
2770 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002771 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2772 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002773 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002774 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2775 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002776 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002777 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2778 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002779
Chris Lattnere58a7802006-04-02 03:41:14 +00002780 if (HasChain) {
2781 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2782 if (OnlyLoad)
2783 PendingLoads.push_back(Chain);
2784 else
2785 DAG.setRoot(Chain);
2786 }
Chris Lattner0eade312006-03-24 02:22:33 +00002787 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002788 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002789 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00002790 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002791 }
2792 setValue(&I, Result);
2793 }
2794}
2795
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002796/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002797static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00002798 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002799 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002800 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002801 "TypeInfo must be a global variable or NULL");
2802 return GV;
2803}
2804
Duncan Sandsf4070822007-06-15 19:04:19 +00002805/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002806/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002807static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2808 MachineBasicBlock *MBB) {
2809 // Inform the MachineModuleInfo of the personality for this landing pad.
2810 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2811 assert(CE->getOpcode() == Instruction::BitCast &&
2812 isa<Function>(CE->getOperand(0)) &&
2813 "Personality should be a function");
2814 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2815
2816 // Gather all the type infos for this landing pad and pass them along to
2817 // MachineModuleInfo.
2818 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002819 unsigned N = I.getNumOperands();
2820
2821 for (unsigned i = N - 1; i > 2; --i) {
2822 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2823 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002824 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002825 assert (FirstCatch <= N && "Invalid filter length");
2826
2827 if (FirstCatch < N) {
2828 TyInfo.reserve(N - FirstCatch);
2829 for (unsigned j = FirstCatch; j < N; ++j)
2830 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2831 MMI->addCatchTypeInfo(MBB, TyInfo);
2832 TyInfo.clear();
2833 }
2834
Duncan Sands6590b042007-08-27 15:47:50 +00002835 if (!FilterLength) {
2836 // Cleanup.
2837 MMI->addCleanup(MBB);
2838 } else {
2839 // Filter.
2840 TyInfo.reserve(FilterLength - 1);
2841 for (unsigned j = i + 1; j < FirstCatch; ++j)
2842 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2843 MMI->addFilterTypeInfo(MBB, TyInfo);
2844 TyInfo.clear();
2845 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002846
2847 N = i;
2848 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002849 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002850
2851 if (N > 3) {
2852 TyInfo.reserve(N - 3);
2853 for (unsigned j = 3; j < N; ++j)
2854 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002855 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002856 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002857}
2858
Mon P Wang63307c32008-05-05 19:05:59 +00002859
2860/// Inlined utility function to implement binary input atomic intrinsics for
2861// visitIntrinsicCall: I is a call instruction
2862// Op is the associated NodeType for I
2863const char *
2864SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2865 SDOperand Root = getRoot();
2866 SDOperand O2 = getValue(I.getOperand(2));
2867 SDOperand L = DAG.getAtomic(Op, Root,
2868 getValue(I.getOperand(1)),
2869 O2, O2.getValueType());
2870 setValue(&I, L);
2871 DAG.setRoot(L.getValue(1));
2872 return 0;
2873}
2874
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002875/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2876/// we want to emit this as a call to a named external function, return the name
2877/// otherwise lower it and return null.
2878const char *
2879SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2880 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002881 default:
2882 // By default, turn this into a target intrinsic node.
2883 visitTargetIntrinsic(I, Intrinsic);
2884 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002885 case Intrinsic::vastart: visitVAStart(I); return 0;
2886 case Intrinsic::vaend: visitVAEnd(I); return 0;
2887 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002888 case Intrinsic::returnaddress:
2889 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2890 getValue(I.getOperand(1))));
2891 return 0;
2892 case Intrinsic::frameaddress:
2893 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2894 getValue(I.getOperand(1))));
2895 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002896 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002897 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002898 break;
2899 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002900 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002901 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002902 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002903 case Intrinsic::memcpy_i64: {
2904 SDOperand Op1 = getValue(I.getOperand(1));
2905 SDOperand Op2 = getValue(I.getOperand(2));
2906 SDOperand Op3 = getValue(I.getOperand(3));
2907 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2908 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2909 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002910 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002911 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002912 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002913 case Intrinsic::memset_i64: {
2914 SDOperand Op1 = getValue(I.getOperand(1));
2915 SDOperand Op2 = getValue(I.getOperand(2));
2916 SDOperand Op3 = getValue(I.getOperand(3));
2917 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2918 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2919 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002920 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002921 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002922 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002923 case Intrinsic::memmove_i64: {
2924 SDOperand Op1 = getValue(I.getOperand(1));
2925 SDOperand Op2 = getValue(I.getOperand(2));
2926 SDOperand Op3 = getValue(I.getOperand(3));
2927 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2928
2929 // If the source and destination are known to not be aliases, we can
2930 // lower memmove as memcpy.
2931 uint64_t Size = -1ULL;
2932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2933 Size = C->getValue();
2934 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2935 AliasAnalysis::NoAlias) {
2936 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2937 I.getOperand(1), 0, I.getOperand(2), 0));
2938 return 0;
2939 }
2940
2941 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2942 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002943 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002944 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002945 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002946 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002947 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002948 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002949 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002950
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002951 Ops[0] = getRoot();
2952 Ops[1] = getValue(SPI.getLineValue());
2953 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002954
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002955 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002956 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002957 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2958
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002959 Ops[3] = DAG.getString(CompileUnit->getFileName());
2960 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002961
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002962 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002963 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002964
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002965 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002966 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002967 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002968 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002969 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002970 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2971 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002972 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002973 DAG.getConstant(LabelID, MVT::i32),
2974 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002975 }
2976
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002977 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002978 }
2979 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002980 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002981 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002982 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2983 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002984 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2985 DAG.getConstant(LabelID, MVT::i32),
2986 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002987 }
2988
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002989 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002990 }
2991 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002992 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002993 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002994 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002995 Value *SP = FSI.getSubprogram();
2996 if (SP && MMI->Verify(SP)) {
2997 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2998 // what (most?) gdb expects.
2999 DebugInfoDesc *DD = MMI->getDescFor(SP);
3000 assert(DD && "Not a debug information descriptor");
3001 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3002 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3003 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3004 CompileUnit->getFileName());
3005 // Record the source line but does create a label. It will be emitted
3006 // at asm emission time.
3007 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003008 }
3009
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003010 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003011 }
3012 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003013 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003014 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003015 Value *Variable = DI.getVariable();
3016 if (MMI && Variable && MMI->Verify(Variable))
3017 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3018 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003019 return 0;
3020 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003021
Jim Laskeyb180aa12007-02-21 22:53:45 +00003022 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003023 if (!CurMBB->isLandingPad()) {
3024 // FIXME: Mark exception register as live in. Hack for PR1508.
3025 unsigned Reg = TLI.getExceptionAddressRegister();
3026 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003027 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003028 // Insert the EXCEPTIONADDR instruction.
3029 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3030 SDOperand Ops[1];
3031 Ops[0] = DAG.getRoot();
3032 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3033 setValue(&I, Op);
3034 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003035 return 0;
3036 }
3037
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003038 case Intrinsic::eh_selector_i32:
3039 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003040 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003041 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003042 MVT::i32 : MVT::i64);
3043
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003044 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003045 if (CurMBB->isLandingPad())
3046 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003047 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003048#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003049 FuncInfo.CatchInfoLost.insert(&I);
3050#endif
Duncan Sands90291952007-07-06 09:18:59 +00003051 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3052 unsigned Reg = TLI.getExceptionSelectorRegister();
3053 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003054 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003055
3056 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003057 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003058 SDOperand Ops[2];
3059 Ops[0] = getValue(I.getOperand(1));
3060 Ops[1] = getRoot();
3061 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3062 setValue(&I, Op);
3063 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003064 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003065 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003066 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003067
3068 return 0;
3069 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003070
3071 case Intrinsic::eh_typeid_for_i32:
3072 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003073 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003074 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003075 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003076
Jim Laskey735b6f82007-02-22 15:38:06 +00003077 if (MMI) {
3078 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003079 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003080
Jim Laskey735b6f82007-02-22 15:38:06 +00003081 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003082 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003083 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003084 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003085 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003086 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003087
3088 return 0;
3089 }
3090
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003091 case Intrinsic::eh_return: {
3092 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3093
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003094 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003095 MMI->setCallsEHReturn(true);
3096 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3097 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003098 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003099 getValue(I.getOperand(1)),
3100 getValue(I.getOperand(2))));
3101 } else {
3102 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3103 }
3104
3105 return 0;
3106 }
3107
3108 case Intrinsic::eh_unwind_init: {
3109 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3110 MMI->setCallsUnwindInit(true);
3111 }
3112
3113 return 0;
3114 }
3115
3116 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003117 MVT VT = getValue(I.getOperand(1)).getValueType();
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003118 SDOperand CfaArg;
Duncan Sands83ec4b62008-06-06 12:08:01 +00003119 if (VT.getSizeInBits() > TLI.getPointerTy().getSizeInBits())
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003120 CfaArg = DAG.getNode(ISD::TRUNCATE,
3121 TLI.getPointerTy(), getValue(I.getOperand(1)));
3122 else
3123 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3124 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003125
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003126 SDOperand Offset = DAG.getNode(ISD::ADD,
3127 TLI.getPointerTy(),
3128 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3129 TLI.getPointerTy()),
3130 CfaArg);
3131 setValue(&I, DAG.getNode(ISD::ADD,
3132 TLI.getPointerTy(),
3133 DAG.getNode(ISD::FRAMEADDR,
3134 TLI.getPointerTy(),
3135 DAG.getConstant(0,
3136 TLI.getPointerTy())),
3137 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003138 return 0;
3139 }
3140
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003141 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003142 setValue(&I, DAG.getNode(ISD::FSQRT,
3143 getValue(I.getOperand(1)).getValueType(),
3144 getValue(I.getOperand(1))));
3145 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003146 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003147 setValue(&I, DAG.getNode(ISD::FPOWI,
3148 getValue(I.getOperand(1)).getValueType(),
3149 getValue(I.getOperand(1)),
3150 getValue(I.getOperand(2))));
3151 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003152 case Intrinsic::sin:
3153 setValue(&I, DAG.getNode(ISD::FSIN,
3154 getValue(I.getOperand(1)).getValueType(),
3155 getValue(I.getOperand(1))));
3156 return 0;
3157 case Intrinsic::cos:
3158 setValue(&I, DAG.getNode(ISD::FCOS,
3159 getValue(I.getOperand(1)).getValueType(),
3160 getValue(I.getOperand(1))));
3161 return 0;
3162 case Intrinsic::pow:
3163 setValue(&I, DAG.getNode(ISD::FPOW,
3164 getValue(I.getOperand(1)).getValueType(),
3165 getValue(I.getOperand(1)),
3166 getValue(I.getOperand(2))));
3167 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003168 case Intrinsic::pcmarker: {
3169 SDOperand Tmp = getValue(I.getOperand(1));
3170 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3171 return 0;
3172 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003173 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003174 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003175 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3176 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3177 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003178 setValue(&I, Tmp);
3179 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003180 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003181 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003182 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003183 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003184 assert(0 && "part_select intrinsic not implemented");
3185 abort();
3186 }
3187 case Intrinsic::part_set: {
3188 // Currently not implemented: just abort
3189 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003190 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003191 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003192 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003193 setValue(&I, DAG.getNode(ISD::BSWAP,
3194 getValue(I.getOperand(1)).getValueType(),
3195 getValue(I.getOperand(1))));
3196 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003197 case Intrinsic::cttz: {
3198 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003199 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003200 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003201 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003202 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003203 }
3204 case Intrinsic::ctlz: {
3205 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003206 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003207 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003208 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003209 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003210 }
3211 case Intrinsic::ctpop: {
3212 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003213 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003214 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003215 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003216 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003217 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003218 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003219 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003220 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3221 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003222 setValue(&I, Tmp);
3223 DAG.setRoot(Tmp.getValue(1));
3224 return 0;
3225 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003226 case Intrinsic::stackrestore: {
3227 SDOperand Tmp = getValue(I.getOperand(1));
3228 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003229 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003230 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003231 case Intrinsic::var_annotation:
3232 // Discard annotate attributes
3233 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003234
Duncan Sands36397f52007-07-27 12:58:54 +00003235 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003236 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003237
3238 SDOperand Ops[6];
3239 Ops[0] = getRoot();
3240 Ops[1] = getValue(I.getOperand(1));
3241 Ops[2] = getValue(I.getOperand(2));
3242 Ops[3] = getValue(I.getOperand(3));
3243 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3244 Ops[5] = DAG.getSrcValue(F);
3245
Duncan Sandsf7331b32007-09-11 14:10:23 +00003246 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3247 DAG.getNodeValueTypes(TLI.getPointerTy(),
3248 MVT::Other), 2,
3249 Ops, 6);
3250
3251 setValue(&I, Tmp);
3252 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003253 return 0;
3254 }
Gordon Henriksence224772008-01-07 01:30:38 +00003255
3256 case Intrinsic::gcroot:
3257 if (GCI) {
3258 Value *Alloca = I.getOperand(1);
3259 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3260
3261 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3262 GCI->addStackRoot(FI->getIndex(), TypeMap);
3263 }
3264 return 0;
3265
3266 case Intrinsic::gcread:
3267 case Intrinsic::gcwrite:
3268 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3269 return 0;
3270
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003271 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003272 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003273 return 0;
3274 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003275
3276 case Intrinsic::trap: {
3277 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3278 return 0;
3279 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003280 case Intrinsic::prefetch: {
3281 SDOperand Ops[4];
3282 Ops[0] = getRoot();
3283 Ops[1] = getValue(I.getOperand(1));
3284 Ops[2] = getValue(I.getOperand(2));
3285 Ops[3] = getValue(I.getOperand(3));
3286 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3287 return 0;
3288 }
3289
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003290 case Intrinsic::memory_barrier: {
3291 SDOperand Ops[6];
3292 Ops[0] = getRoot();
3293 for (int x = 1; x < 6; ++x)
3294 Ops[x] = getValue(I.getOperand(x));
3295
3296 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3297 return 0;
3298 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003299 case Intrinsic::atomic_lcs: {
3300 SDOperand Root = getRoot();
3301 SDOperand O3 = getValue(I.getOperand(3));
3302 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3303 getValue(I.getOperand(1)),
3304 getValue(I.getOperand(2)),
3305 O3, O3.getValueType());
3306 setValue(&I, L);
3307 DAG.setRoot(L.getValue(1));
3308 return 0;
3309 }
Mon P Wang63307c32008-05-05 19:05:59 +00003310 case Intrinsic::atomic_las:
3311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3312 case Intrinsic::atomic_lss:
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3314 case Intrinsic::atomic_load_and:
3315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3316 case Intrinsic::atomic_load_or:
3317 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3318 case Intrinsic::atomic_load_xor:
3319 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3320 case Intrinsic::atomic_load_min:
3321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3322 case Intrinsic::atomic_load_max:
3323 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3324 case Intrinsic::atomic_load_umin:
3325 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3326 case Intrinsic::atomic_load_umax:
3327 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3328 case Intrinsic::atomic_swap:
3329 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003330 }
3331}
3332
3333
Duncan Sands6f74b482007-12-19 09:48:52 +00003334void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003335 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003336 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003337 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003338 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003339 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3340 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003341
Jim Laskey735b6f82007-02-22 15:38:06 +00003342 TargetLowering::ArgListTy Args;
3343 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003344 Args.reserve(CS.arg_size());
3345 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3346 i != e; ++i) {
3347 SDOperand ArgNode = getValue(*i);
3348 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003349
Duncan Sands6f74b482007-12-19 09:48:52 +00003350 unsigned attrInd = i - CS.arg_begin() + 1;
3351 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3352 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3353 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3354 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3355 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3356 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003357 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003358 Args.push_back(Entry);
3359 }
3360
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003361 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003362 // Insert a label before the invoke call to mark the try range. This can be
3363 // used to detect deletion of the invoke via the MachineModuleInfo.
3364 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003365 // Both PendingLoads and PendingExports must be flushed here;
3366 // this call might not return.
3367 (void)getRoot();
3368 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003369 DAG.getConstant(BeginLabel, MVT::i32),
3370 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003371 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003372
Jim Laskey735b6f82007-02-22 15:38:06 +00003373 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003374 TLI.LowerCallTo(getRoot(), CS.getType(),
3375 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003376 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003377 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003378 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003379 if (CS.getType() != Type::VoidTy)
3380 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003381 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003382
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003383 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003384 // Insert a label at the end of the invoke call to mark the try range. This
3385 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3386 EndLabel = MMI->NextLabelID();
3387 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003388 DAG.getConstant(EndLabel, MVT::i32),
3389 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003390
Duncan Sands6f74b482007-12-19 09:48:52 +00003391 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003392 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3393 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003394}
3395
3396
Chris Lattner1c08c712005-01-07 07:47:53 +00003397void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003398 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003399 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003400 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003401 if (unsigned IID = F->getIntrinsicID()) {
3402 RenameFn = visitIntrinsicCall(I, IID);
3403 if (!RenameFn)
3404 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003405 }
3406 }
3407
3408 // Check for well-known libc/libm calls. If the function is internal, it
3409 // can't be a library call.
3410 unsigned NameLen = F->getNameLen();
3411 if (!F->hasInternalLinkage() && NameLen) {
3412 const char *NameStr = F->getNameStart();
3413 if (NameStr[0] == 'c' &&
3414 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3415 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3416 if (I.getNumOperands() == 3 && // Basic sanity checks.
3417 I.getOperand(1)->getType()->isFloatingPoint() &&
3418 I.getType() == I.getOperand(1)->getType() &&
3419 I.getType() == I.getOperand(2)->getType()) {
3420 SDOperand LHS = getValue(I.getOperand(1));
3421 SDOperand RHS = getValue(I.getOperand(2));
3422 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3423 LHS, RHS));
3424 return;
3425 }
3426 } else if (NameStr[0] == 'f' &&
3427 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003428 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3429 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003430 if (I.getNumOperands() == 2 && // Basic sanity checks.
3431 I.getOperand(1)->getType()->isFloatingPoint() &&
3432 I.getType() == I.getOperand(1)->getType()) {
3433 SDOperand Tmp = getValue(I.getOperand(1));
3434 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3435 return;
3436 }
3437 } else if (NameStr[0] == 's' &&
3438 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003439 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3440 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003441 if (I.getNumOperands() == 2 && // Basic sanity checks.
3442 I.getOperand(1)->getType()->isFloatingPoint() &&
3443 I.getType() == I.getOperand(1)->getType()) {
3444 SDOperand Tmp = getValue(I.getOperand(1));
3445 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3446 return;
3447 }
3448 } else if (NameStr[0] == 'c' &&
3449 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003450 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3451 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003452 if (I.getNumOperands() == 2 && // Basic sanity checks.
3453 I.getOperand(1)->getType()->isFloatingPoint() &&
3454 I.getType() == I.getOperand(1)->getType()) {
3455 SDOperand Tmp = getValue(I.getOperand(1));
3456 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3457 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003458 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003459 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003460 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003461 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003462 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003463 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003464 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003465
Chris Lattner64e14b12005-01-08 22:48:57 +00003466 SDOperand Callee;
3467 if (!RenameFn)
3468 Callee = getValue(I.getOperand(0));
3469 else
3470 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003471
Duncan Sands6f74b482007-12-19 09:48:52 +00003472 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003473}
3474
Jim Laskey735b6f82007-02-22 15:38:06 +00003475
Dan Gohmanef5d1942008-03-11 21:11:25 +00003476void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003477 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003478 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3479 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003480 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003481 }
Chris Lattner6833b062008-04-28 07:16:35 +00003482
3483 // To add support for individual return values with aggregate types,
3484 // we'd need a way to take a getresult index and determine which
3485 // values of the Call SDNode are associated with it.
3486 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3487 "Individual return values must not be aggregates!");
3488
3489 SDOperand Call = getValue(I.getOperand(0));
3490 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003491}
3492
3493
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003494/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3495/// this value and returns the result as a ValueVT value. This uses
3496/// Chain/Flag as the input and updates them for the output Chain/Flag.
3497/// If the Flag pointer is NULL, no flag is used.
3498SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003499 SDOperand &Chain,
3500 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003501 // Assemble the legal parts into the final values.
3502 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003503 SmallVector<SDOperand, 8> Parts;
3504 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003505 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003506 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003507 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003508 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003509
Chris Lattner6833b062008-04-28 07:16:35 +00003510 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003511 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003512 SDOperand P;
3513 if (Flag == 0)
3514 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3515 else {
3516 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003517 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003518 }
3519 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003520 Parts[Part+i] = P;
3521 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003522
Dan Gohman23ce5022008-04-25 18:27:55 +00003523 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3524 ValueVT);
3525 Part += NumRegs;
3526 }
Chris Lattner6833b062008-04-28 07:16:35 +00003527
3528 if (ValueVTs.size() == 1)
3529 return Values[0];
3530
Dan Gohman23ce5022008-04-25 18:27:55 +00003531 return DAG.getNode(ISD::MERGE_VALUES,
3532 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3533 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003534}
3535
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003536/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3537/// specified value into the registers specified by this object. This uses
3538/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003539/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003540void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003541 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003542 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003543 unsigned NumRegs = Regs.size();
3544 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003545 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003546 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003547 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003548 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003549
3550 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3551 &Parts[Part], NumParts, RegisterVT);
3552 Part += NumParts;
3553 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003554
3555 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003556 SmallVector<SDOperand, 8> Chains(NumRegs);
3557 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003558 SDOperand Part;
3559 if (Flag == 0)
3560 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3561 else {
3562 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003563 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003564 }
3565 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003566 }
Chris Lattner6833b062008-04-28 07:16:35 +00003567
Evan Cheng33bf38a2008-04-28 22:07:13 +00003568 if (NumRegs == 1 || Flag)
3569 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3570 // flagged to it. That is the CopyToReg nodes and the user are considered
3571 // a single scheduling unit. If we create a TokenFactor and return it as
3572 // chain, then the TokenFactor is both a predecessor (operand) of the
3573 // user as well as a successor (the TF operands are flagged to the user).
3574 // c1, f1 = CopyToReg
3575 // c2, f2 = CopyToReg
3576 // c3 = TokenFactor c1, c2
3577 // ...
3578 // = op c3, ..., f2
3579 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003580 else
3581 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003582}
Chris Lattner864635a2006-02-22 22:37:12 +00003583
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003584/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3585/// operand list. This adds the code marker and includes the number of
3586/// values added into it.
3587void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003588 std::vector<SDOperand> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003589 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003590 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003591 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3592 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003593 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003594 for (unsigned i = 0; i != NumRegs; ++i)
3595 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003596 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003597}
Chris Lattner864635a2006-02-22 22:37:12 +00003598
3599/// isAllocatableRegister - If the specified register is safe to allocate,
3600/// i.e. it isn't a stack pointer or some other special register, return the
3601/// register class for the register. Otherwise, return null.
3602static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003603isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003604 const TargetLowering &TLI,
3605 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003606 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003607 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003608 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3609 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003610 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003611
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003612 const TargetRegisterClass *RC = *RCI;
3613 // If none of the the value types for this register class are valid, we
3614 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003615 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3616 I != E; ++I) {
3617 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003618 // If we have already found this register in a different register class,
3619 // choose the one with the largest VT specified. For example, on
3620 // PowerPC, we favor f64 register classes over f32.
3621 if (FoundVT == MVT::Other ||
Duncan Sands83ec4b62008-06-06 12:08:01 +00003622 FoundVT.getSizeInBits() < (*I).getSizeInBits()) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003623 ThisVT = *I;
3624 break;
3625 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003626 }
3627 }
3628
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003629 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003630
Chris Lattner864635a2006-02-22 22:37:12 +00003631 // NOTE: This isn't ideal. In particular, this might allocate the
3632 // frame pointer in functions that need it (due to them not being taken
3633 // out of allocation, because a variable sized allocation hasn't been seen
3634 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003635 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3636 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003637 if (*I == Reg) {
3638 // We found a matching register class. Keep looking at others in case
3639 // we find one with larger registers that this physreg is also in.
3640 FoundRC = RC;
3641 FoundVT = ThisVT;
3642 break;
3643 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003644 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003645 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003646}
3647
Chris Lattner4e4b5762006-02-01 18:59:47 +00003648
Chris Lattner0c583402007-04-28 20:49:53 +00003649namespace {
3650/// AsmOperandInfo - This contains information for each constraint that we are
3651/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003652struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3653 /// CallOperand - If this is the result output operand or a clobber
3654 /// this is null, otherwise it is the incoming operand to the CallInst.
3655 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003656 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003657
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003658 /// AssignedRegs - If this is a register or register class operand, this
3659 /// contains the set of register corresponding to the operand.
3660 RegsForValue AssignedRegs;
3661
Dan Gohman23ce5022008-04-25 18:27:55 +00003662 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003663 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003664 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003665
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003666 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3667 /// busy in OutputRegs/InputRegs.
3668 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3669 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003670 std::set<unsigned> &InputRegs,
3671 const TargetRegisterInfo &TRI) const {
3672 if (isOutReg) {
3673 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3674 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3675 }
3676 if (isInReg) {
3677 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3678 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3679 }
3680 }
3681
3682private:
3683 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3684 /// specified set.
3685 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3686 const TargetRegisterInfo &TRI) {
3687 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3688 Regs.insert(Reg);
3689 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3690 for (; *Aliases; ++Aliases)
3691 Regs.insert(*Aliases);
3692 }
Chris Lattner0c583402007-04-28 20:49:53 +00003693};
3694} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003695
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003696
Chris Lattner0fe71e92008-02-21 19:43:13 +00003697/// GetRegistersForValue - Assign registers (virtual or physical) for the
3698/// specified operand. We prefer to assign virtual registers, to allow the
3699/// register allocator handle the assignment process. However, if the asm uses
3700/// features that we can't model on machineinstrs, we have SDISel do the
3701/// allocation. This produces generally horrible, but correct, code.
3702///
3703/// OpInfo describes the operand.
3704/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3705/// or any explicitly clobbered registers.
3706/// Input and OutputRegs are the set of already allocated physical registers.
3707///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003708void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003709GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003710 std::set<unsigned> &OutputRegs,
3711 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003712 // Compute whether this value requires an input register, an output register,
3713 // or both.
3714 bool isOutReg = false;
3715 bool isInReg = false;
3716 switch (OpInfo.Type) {
3717 case InlineAsm::isOutput:
3718 isOutReg = true;
3719
3720 // If this is an early-clobber output, or if there is an input
3721 // constraint that matches this, we need to reserve the input register
3722 // so no other inputs allocate to it.
3723 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3724 break;
3725 case InlineAsm::isInput:
3726 isInReg = true;
3727 isOutReg = false;
3728 break;
3729 case InlineAsm::isClobber:
3730 isOutReg = true;
3731 isInReg = true;
3732 break;
3733 }
3734
3735
3736 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003737 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003738
3739 // If this is a constraint for a single physreg, or a constraint for a
3740 // register class, find it.
3741 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3742 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3743 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003744
3745 unsigned NumRegs = 1;
3746 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003747 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003748 MVT RegVT;
3749 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003750
Chris Lattnerbf996f12007-04-30 17:29:31 +00003751
3752 // If this is a constraint for a specific physical register, like {r17},
3753 // assign it now.
3754 if (PhysReg.first) {
3755 if (OpInfo.ConstraintVT == MVT::Other)
3756 ValueVT = *PhysReg.second->vt_begin();
3757
3758 // Get the actual register value type. This is important, because the user
3759 // may have asked for (e.g.) the AX register in i32 type. We need to
3760 // remember that AX is actually i16 to get the right extension.
3761 RegVT = *PhysReg.second->vt_begin();
3762
3763 // This is a explicit reference to a physical register.
3764 Regs.push_back(PhysReg.first);
3765
3766 // If this is an expanded reference, add the rest of the regs to Regs.
3767 if (NumRegs != 1) {
3768 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003769 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00003770 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003771
3772 // Already added the first reg.
3773 --NumRegs; ++I;
3774 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00003775 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003776 Regs.push_back(*I);
3777 }
3778 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003779 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003780 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3781 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003782 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003783 }
3784
3785 // Otherwise, if this was a reference to an LLVM register class, create vregs
3786 // for this reference.
3787 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003788 const TargetRegisterClass *RC = PhysReg.second;
3789 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003790 // If this is an early clobber or tied register, our regalloc doesn't know
3791 // how to maintain the constraint. If it isn't, go ahead and create vreg
3792 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003793 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3794 // If there is some other early clobber and this is an input register,
3795 // then we are forced to pre-allocate the input reg so it doesn't
3796 // conflict with the earlyclobber.
3797 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003798 RegVT = *PhysReg.second->vt_begin();
3799
3800 if (OpInfo.ConstraintVT == MVT::Other)
3801 ValueVT = RegVT;
3802
3803 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003804 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003805 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003806 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003807
Dan Gohman23ce5022008-04-25 18:27:55 +00003808 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003809 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003810 }
3811
3812 // Otherwise, we can't allocate it. Let the code below figure out how to
3813 // maintain these constraints.
3814 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3815
3816 } else {
3817 // This is a reference to a register class that doesn't directly correspond
3818 // to an LLVM register class. Allocate NumRegs consecutive, available,
3819 // registers from the class.
3820 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3821 OpInfo.ConstraintVT);
3822 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003823
Dan Gohman6f0d0242008-02-10 18:45:23 +00003824 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003825 unsigned NumAllocated = 0;
3826 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3827 unsigned Reg = RegClassRegs[i];
3828 // See if this register is available.
3829 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3830 (isInReg && InputRegs.count(Reg))) { // Already used.
3831 // Make sure we find consecutive registers.
3832 NumAllocated = 0;
3833 continue;
3834 }
3835
3836 // Check to see if this register is allocatable (i.e. don't give out the
3837 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003838 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003839 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003840 if (!RC) { // Couldn't allocate this register.
3841 // Reset NumAllocated to make sure we return consecutive registers.
3842 NumAllocated = 0;
3843 continue;
3844 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003845 }
3846
3847 // Okay, this register is good, we can use it.
3848 ++NumAllocated;
3849
3850 // If we allocated enough consecutive registers, succeed.
3851 if (NumAllocated == NumRegs) {
3852 unsigned RegStart = (i-NumAllocated)+1;
3853 unsigned RegEnd = i+1;
3854 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003855 for (unsigned i = RegStart; i != RegEnd; ++i)
3856 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003857
Dan Gohman23ce5022008-04-25 18:27:55 +00003858 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003859 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003860 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003861 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003862 }
3863 }
3864
3865 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003866}
3867
3868
Chris Lattnerce7518c2006-01-26 22:24:51 +00003869/// visitInlineAsm - Handle a call to an InlineAsm object.
3870///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003871void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3872 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003873
Chris Lattner0c583402007-04-28 20:49:53 +00003874 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003875 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003876
3877 SDOperand Chain = getRoot();
3878 SDOperand Flag;
3879
Chris Lattner4e4b5762006-02-01 18:59:47 +00003880 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003881
Chris Lattner0c583402007-04-28 20:49:53 +00003882 // Do a prepass over the constraints, canonicalizing them, and building up the
3883 // ConstraintOperands list.
3884 std::vector<InlineAsm::ConstraintInfo>
3885 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003886
3887 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3888 // constraint. If so, we can't let the register allocator allocate any input
3889 // registers, because it will not know to avoid the earlyclobbered output reg.
3890 bool SawEarlyClobber = false;
3891
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003892 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003893 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003894 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003895 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3896 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003897
Duncan Sands83ec4b62008-06-06 12:08:01 +00003898 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00003899
3900 // Compute the value type for each operand.
3901 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003902 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003903 // Indirect outputs just consume an argument.
3904 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003905 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003906 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003907 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003908 // The return value of the call is this value. As such, there is no
3909 // corresponding argument.
3910 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3911 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3912 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3913 } else {
3914 assert(ResNo == 0 && "Asm only has one result!");
3915 OpVT = TLI.getValueType(CS.getType());
3916 }
3917 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003918 break;
3919 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003920 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003921 break;
3922 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003923 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003924 break;
3925 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003926
Chris Lattner0c583402007-04-28 20:49:53 +00003927 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003928 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003929 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003930 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3931 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003932 else {
3933 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3934 const Type *OpTy = OpInfo.CallOperandVal->getType();
3935 // If this is an indirect operand, the operand is a pointer to the
3936 // accessed type.
3937 if (OpInfo.isIndirect)
3938 OpTy = cast<PointerType>(OpTy)->getElementType();
3939
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00003940 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003941 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00003942 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003943 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3944 switch (BitSize) {
3945 default: break;
3946 case 1:
3947 case 8:
3948 case 16:
3949 case 32:
3950 case 64:
3951 OpTy = IntegerType::get(BitSize);
3952 break;
3953 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003954 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003955
3956 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003957 }
3958 }
3959
3960 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003961
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003962 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003963 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003964
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003965 // Keep track of whether we see an earlyclobber.
3966 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003967
Chris Lattner0fe71e92008-02-21 19:43:13 +00003968 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003969 if (!SawEarlyClobber &&
3970 OpInfo.Type == InlineAsm::isClobber &&
3971 OpInfo.ConstraintType == TargetLowering::C_Register) {
3972 // Note that we want to ignore things that we don't trick here, like
3973 // dirflag, fpsr, flags, etc.
3974 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3975 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3976 OpInfo.ConstraintVT);
3977 if (PhysReg.first || PhysReg.second) {
3978 // This is a register we know of.
3979 SawEarlyClobber = true;
3980 }
3981 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003982
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003983 // If this is a memory input, and if the operand is not indirect, do what we
3984 // need to to provide an address for the memory input.
3985 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3986 !OpInfo.isIndirect) {
3987 assert(OpInfo.Type == InlineAsm::isInput &&
3988 "Can only indirectify direct input operands!");
3989
3990 // Memory operands really want the address of the value. If we don't have
3991 // an indirect input, put it in the constpool if we can, otherwise spill
3992 // it to a stack slot.
3993
3994 // If the operand is a float, integer, or vector constant, spill to a
3995 // constant pool entry to get its address.
3996 Value *OpVal = OpInfo.CallOperandVal;
3997 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3998 isa<ConstantVector>(OpVal)) {
3999 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4000 TLI.getPointerTy());
4001 } else {
4002 // Otherwise, create a stack slot and emit a store to it before the
4003 // asm.
4004 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004005 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004006 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4007 MachineFunction &MF = DAG.getMachineFunction();
4008 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4009 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4010 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4011 OpInfo.CallOperand = StackSlot;
4012 }
4013
4014 // There is no longer a Value* corresponding to this operand.
4015 OpInfo.CallOperandVal = 0;
4016 // It is now an indirect operand.
4017 OpInfo.isIndirect = true;
4018 }
4019
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004020 // If this constraint is for a specific register, allocate it before
4021 // anything else.
4022 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4023 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004024 }
Chris Lattner0c583402007-04-28 20:49:53 +00004025 ConstraintInfos.clear();
4026
4027
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004028 // Second pass - Loop over all of the operands, assigning virtual or physregs
4029 // to registerclass operands.
4030 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004031 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004032
4033 // C_Register operands have already been allocated, Other/Memory don't need
4034 // to be.
4035 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4036 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4037 }
4038
Chris Lattner0c583402007-04-28 20:49:53 +00004039 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4040 std::vector<SDOperand> AsmNodeOperands;
4041 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4042 AsmNodeOperands.push_back(
4043 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4044
Chris Lattner2cc2f662006-02-01 01:28:23 +00004045
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004046 // Loop over all of the inputs, copying the operand values into the
4047 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004048 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004049
Chris Lattner0c583402007-04-28 20:49:53 +00004050 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4051 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4052
4053 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004054 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004055
Chris Lattner0c583402007-04-28 20:49:53 +00004056 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004057 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004058 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4059 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004060 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004061 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004062
Chris Lattner22873462006-02-27 23:45:39 +00004063 // Add information to the INLINEASM node to know about this output.
4064 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004065 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4066 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004067 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004068 break;
4069 }
4070
Chris Lattner2a600be2007-04-28 21:01:43 +00004071 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004072
Chris Lattner864635a2006-02-22 22:37:12 +00004073 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004074 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004075 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004076 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004077 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004078 exit(1);
4079 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004080
Chris Lattner41f62592008-04-29 04:29:54 +00004081 // If this is an indirect operand, store through the pointer after the
4082 // asm.
4083 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004084 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004085 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004086 } else {
4087 // This is the result value of the call.
4088 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4089 // Concatenate this output onto the outputs list.
4090 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004091 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004092
4093 // Add information to the INLINEASM node to know that this register is
4094 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004095 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4096 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004097 break;
4098 }
4099 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004100 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004101
Chris Lattner0c583402007-04-28 20:49:53 +00004102 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004103 // If this is required to match an output register we have already set,
4104 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004105 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004106
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004107 // Scan until we find the definition we already emitted of this operand.
4108 // When we find it, create a RegsForValue operand.
4109 unsigned CurOp = 2; // The first operand.
4110 for (; OperandNo; --OperandNo) {
4111 // Advance to the next operand.
4112 unsigned NumOps =
4113 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004114 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4115 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004116 "Skipped past definitions?");
4117 CurOp += (NumOps>>3)+1;
4118 }
4119
4120 unsigned NumOps =
4121 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004122 if ((NumOps & 7) == 2 /*REGDEF*/) {
4123 // Add NumOps>>3 registers to MatchedRegs.
4124 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004125 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004126 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4127 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004128 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4129 unsigned Reg =
4130 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4131 MatchedRegs.Regs.push_back(Reg);
4132 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004133
Chris Lattner527fae12007-02-01 01:21:12 +00004134 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004135 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004136 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4137 break;
4138 } else {
4139 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004140 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4141 // Add information to the INLINEASM node to know about this input.
4142 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4143 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4144 TLI.getPointerTy()));
4145 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4146 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004147 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004148 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004149
Chris Lattner2a600be2007-04-28 21:01:43 +00004150 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004151 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004152 "Don't know how to handle indirect other inputs yet!");
4153
Chris Lattner48884cd2007-08-25 00:47:38 +00004154 std::vector<SDOperand> Ops;
4155 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4156 Ops, DAG);
4157 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004158 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004159 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004160 exit(1);
4161 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004162
4163 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004164 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004165 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4166 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004167 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004168 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004169 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004170 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004171 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4172 "Memory operands expect pointer values");
4173
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004174 // Add information to the INLINEASM node to know about this input.
4175 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004176 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4177 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004178 AsmNodeOperands.push_back(InOperandVal);
4179 break;
4180 }
4181
Chris Lattner2a600be2007-04-28 21:01:43 +00004182 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4183 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4184 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004185 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004186 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004187
4188 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004189 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4190 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004191
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004192 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004193
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004194 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4195 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004196 break;
4197 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004198 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004199 // Add the clobbered value to the operand list, so that the register
4200 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004201 if (!OpInfo.AssignedRegs.Regs.empty())
4202 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4203 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004204 break;
4205 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004206 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004207 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004208
4209 // Finish up input operands.
4210 AsmNodeOperands[0] = Chain;
4211 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4212
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004213 Chain = DAG.getNode(ISD::INLINEASM,
4214 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004215 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004216 Flag = Chain.getValue(1);
4217
Chris Lattner6656dd12006-01-31 02:03:41 +00004218 // If this asm returns a register value, copy the result from that register
4219 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004220 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004221 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004222
4223 // If any of the results of the inline asm is a vector, it may have the
4224 // wrong width/num elts. This can happen for register classes that can
4225 // contain multiple different value types. The preg or vreg allocated may
4226 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004227 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004228 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4229 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004230 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004231 Val = DAG.getNode(ISD::BIT_CONVERT,
4232 TLI.getValueType(ResSTy->getElementType(i)), Val);
4233 }
4234 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004235 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004236 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4237 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004238 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004239
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004240 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004241 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004242
Chris Lattner6656dd12006-01-31 02:03:41 +00004243 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4244
4245 // Process indirect outputs, first output all of the flagged copies out of
4246 // physregs.
4247 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004248 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004249 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004250 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004251 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004252 }
4253
4254 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004255 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004256 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004257 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004258 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004259 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004260 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004261 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4262 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004263 DAG.setRoot(Chain);
4264}
4265
4266
Chris Lattner1c08c712005-01-07 07:47:53 +00004267void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4268 SDOperand Src = getValue(I.getOperand(0));
4269
Duncan Sands83ec4b62008-06-06 12:08:01 +00004270 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004271
4272 if (IntPtr < Src.getValueType())
4273 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4274 else if (IntPtr > Src.getValueType())
4275 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004276
4277 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004278 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004279 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004280 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004281
Reid Spencer47857812006-12-31 05:55:36 +00004282 TargetLowering::ArgListTy Args;
4283 TargetLowering::ArgListEntry Entry;
4284 Entry.Node = Src;
4285 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004286 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004287
4288 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004289 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4290 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004291 setValue(&I, Result.first); // Pointers always fit in registers
4292 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004293}
4294
4295void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004296 TargetLowering::ArgListTy Args;
4297 TargetLowering::ArgListEntry Entry;
4298 Entry.Node = getValue(I.getOperand(0));
4299 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004300 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004301 MVT IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004302 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004303 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4304 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004305 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4306 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004307}
4308
Evan Chengff9b3732008-01-30 18:18:23 +00004309// EmitInstrWithCustomInserter - This method should be implemented by targets
4310// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004311// instructions are special in various ways, which require special support to
4312// insert. The specified MachineInstr is created but not inserted into any
4313// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004314MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004315 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004316 cerr << "If a target marks an instruction with "
4317 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004318 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004319 abort();
4320 return 0;
4321}
4322
Chris Lattner39ae3622005-01-09 00:00:49 +00004323void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004324 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4325 getValue(I.getOperand(1)),
4326 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004327}
4328
4329void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004330 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4331 getValue(I.getOperand(0)),
4332 DAG.getSrcValue(I.getOperand(0)));
4333 setValue(&I, V);
4334 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004335}
4336
4337void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004338 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4339 getValue(I.getOperand(1)),
4340 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004341}
4342
4343void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004344 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4345 getValue(I.getOperand(1)),
4346 getValue(I.getOperand(2)),
4347 DAG.getSrcValue(I.getOperand(1)),
4348 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004349}
4350
Chris Lattnerfdfded52006-04-12 16:20:43 +00004351/// TargetLowering::LowerArguments - This is the default LowerArguments
4352/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004353/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4354/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004355std::vector<SDOperand>
4356TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4357 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4358 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004359 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004360 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4361 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4362
4363 // Add one result value for each formal argument.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004364 std::vector<MVT> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004365 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004366 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4367 I != E; ++I, ++j) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004368 MVT VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004369 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004370 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004371 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004372
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004373 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004374 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004375 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004376 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004377 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004378 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004379 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004380 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004381 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004382 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004383 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004384 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004385 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004386 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004387 // For ByVal, alignment should be passed from FE. BE will guess if
4388 // this info is not there but there are cases it cannot get right.
4389 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004390 FrameAlign = F.getParamAlignment(j);
4391 Flags.setByValAlign(FrameAlign);
4392 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004393 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004394 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004395 Flags.setNest();
4396 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004397
Duncan Sands83ec4b62008-06-06 12:08:01 +00004398 MVT RegisterVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004399 unsigned NumRegs = getNumRegisters(VT);
4400 for (unsigned i = 0; i != NumRegs; ++i) {
4401 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004402 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004403 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004404 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004405 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004406 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004407 MyFlags.setOrigAlign(1);
4408 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004409 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004410 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004411
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004412 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004413
4414 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004415 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004416 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004417 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004418
4419 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4420 // allows exposing the loads that may be part of the argument access to the
4421 // first DAGCombiner pass.
4422 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4423
4424 // The number of results should match up, except that the lowered one may have
4425 // an extra flag result.
4426 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4427 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4428 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4429 && "Lowering produced unexpected number of results!");
4430 Result = TmpRes.Val;
4431
Dan Gohman27a70be2007-07-02 16:18:06 +00004432 unsigned NumArgRegs = Result->getNumValues() - 1;
4433 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004434
4435 // Set up the return result vector.
4436 Ops.clear();
4437 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004438 unsigned Idx = 1;
4439 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4440 ++I, ++Idx) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004441 MVT VT = getValueType(I->getType());
4442 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004443
4444 unsigned NumParts = getNumRegisters(VT);
4445 SmallVector<SDOperand, 4> Parts(NumParts);
4446 for (unsigned j = 0; j != NumParts; ++j)
4447 Parts[j] = SDOperand(Result, i++);
4448
4449 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4450 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4451 AssertOp = ISD::AssertSext;
4452 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4453 AssertOp = ISD::AssertZext;
4454
4455 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004456 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004457 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004458 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004459 return Ops;
4460}
4461
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004462
4463/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4464/// implementation, which just inserts an ISD::CALL node, which is later custom
4465/// lowered by the target to something concrete. FIXME: When all targets are
4466/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4467std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004468TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4469 bool RetSExt, bool RetZExt, bool isVarArg,
4470 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004471 SDOperand Callee,
4472 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004473 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004474 Ops.push_back(Chain); // Op#0 - Chain
4475 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4476 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4477 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4478 Ops.push_back(Callee);
4479
4480 // Handle all of the outgoing arguments.
4481 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004482 MVT VT = getValueType(Args[i].Ty);
Reid Spencer47857812006-12-31 05:55:36 +00004483 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004484 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004485 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004486 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004487
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004488 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004489 Flags.setZExt();
4490 if (Args[i].isSExt)
4491 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004492 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004493 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004494 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004495 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004496 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004497 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004498 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004499 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004500 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004501 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004502 // For ByVal, alignment should come from FE. BE will guess if this
4503 // info is not there but there are cases it cannot get right.
4504 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004505 FrameAlign = Args[i].Alignment;
4506 Flags.setByValAlign(FrameAlign);
4507 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004508 }
Duncan Sands36397f52007-07-27 12:58:54 +00004509 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004510 Flags.setNest();
4511 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004512
Duncan Sands83ec4b62008-06-06 12:08:01 +00004513 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004514 unsigned NumParts = getNumRegisters(VT);
4515 SmallVector<SDOperand, 4> Parts(NumParts);
4516 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4517
4518 if (Args[i].isSExt)
4519 ExtendKind = ISD::SIGN_EXTEND;
4520 else if (Args[i].isZExt)
4521 ExtendKind = ISD::ZERO_EXTEND;
4522
4523 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4524
4525 for (unsigned i = 0; i != NumParts; ++i) {
4526 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004527 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004528 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004529 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004530 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004531 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004532
4533 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004534 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004535 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004536 }
4537
Dan Gohmanef5d1942008-03-11 21:11:25 +00004538 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004539 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004540 SmallVector<MVT, 4> LoweredRetTys;
4541 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004542 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004543
Dan Gohman23ce5022008-04-25 18:27:55 +00004544 // Then we translate that to a list of legal types.
4545 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004546 MVT VT = RetTys[I];
4547 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004548 unsigned NumRegs = getNumRegisters(VT);
4549 for (unsigned i = 0; i != NumRegs; ++i)
4550 LoweredRetTys.push_back(RegisterVT);
4551 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004552
Dan Gohmanef5d1942008-03-11 21:11:25 +00004553 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004554
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004555 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004556 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004557 DAG.getVTList(&LoweredRetTys[0],
4558 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004559 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004560 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004561
4562 // Gather up the call result into a single value.
4563 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004564 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4565
4566 if (RetSExt)
4567 AssertOp = ISD::AssertSext;
4568 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004569 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004570
Dan Gohmanef5d1942008-03-11 21:11:25 +00004571 SmallVector<SDOperand, 4> ReturnValues;
4572 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004573 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004574 MVT VT = RetTys[I];
4575 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004576 unsigned NumRegs = getNumRegisters(VT);
4577 unsigned RegNoEnd = NumRegs + RegNo;
4578 SmallVector<SDOperand, 4> Results;
4579 for (; RegNo != RegNoEnd; ++RegNo)
4580 Results.push_back(Res.getValue(RegNo));
4581 SDOperand ReturnValue =
4582 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4583 AssertOp);
4584 ReturnValues.push_back(ReturnValue);
4585 }
4586 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4587 DAG.getNode(ISD::MERGE_VALUES,
4588 DAG.getVTList(&RetTys[0], RetTys.size()),
4589 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004590 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004591
4592 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004593}
4594
Chris Lattner50381b62005-05-14 05:50:48 +00004595SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004596 assert(0 && "LowerOperation not implemented for this target!");
4597 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004598 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004599}
4600
Nate Begeman0aed7842006-01-28 03:14:31 +00004601SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4602 SelectionDAG &DAG) {
4603 assert(0 && "CustomPromoteOperation not implemented for this target!");
4604 abort();
4605 return SDOperand();
4606}
4607
Chris Lattner7041ee32005-01-11 05:56:49 +00004608//===----------------------------------------------------------------------===//
4609// SelectionDAGISel code
4610//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004611
Duncan Sands83ec4b62008-06-06 12:08:01 +00004612unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004613 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004614}
4615
Chris Lattner495a0b52005-08-17 06:37:43 +00004616void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004617 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004618 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004619 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004620}
Chris Lattner1c08c712005-01-07 07:47:53 +00004621
Chris Lattner1c08c712005-01-07 07:47:53 +00004622bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004623 // Get alias analysis for load/store combining.
4624 AA = &getAnalysis<AliasAnalysis>();
4625
Chris Lattner1c08c712005-01-07 07:47:53 +00004626 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004627 if (MF.getFunction()->hasCollector())
4628 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4629 else
4630 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004631 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004632 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004633
4634 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4635
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004636 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4637 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4638 // Mark landing pad.
4639 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004640
4641 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004642 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004643
Evan Chengad2070c2007-02-10 02:43:39 +00004644 // Add function live-ins to entry block live-in set.
4645 BasicBlock *EntryBB = &Fn.getEntryBlock();
4646 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004647 if (!RegInfo->livein_empty())
4648 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4649 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004650 BB->addLiveIn(I->first);
4651
Duncan Sandsf4070822007-06-15 19:04:19 +00004652#ifndef NDEBUG
4653 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4654 "Not all catch info was assigned to a landing pad!");
4655#endif
4656
Chris Lattner1c08c712005-01-07 07:47:53 +00004657 return true;
4658}
4659
Chris Lattner6833b062008-04-28 07:16:35 +00004660void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004661 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004662 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004663 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004664 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004665 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004666
Dan Gohman23ce5022008-04-25 18:27:55 +00004667 RegsForValue RFV(TLI, Reg, V->getType());
4668 SDOperand Chain = DAG.getEntryNode();
4669 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4670 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004671}
4672
Chris Lattner068a81e2005-01-17 17:15:02 +00004673void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004674LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004675 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004676 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004677 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004678 SDOperand OldRoot = SDL.DAG.getRoot();
4679 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004680
Chris Lattnerbf209482005-10-30 19:42:35 +00004681 unsigned a = 0;
4682 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4683 AI != E; ++AI, ++a)
4684 if (!AI->use_empty()) {
4685 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004686
Chris Lattnerbf209482005-10-30 19:42:35 +00004687 // If this argument is live outside of the entry block, insert a copy from
4688 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004689 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4690 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004691 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004692 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004693 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004694
Chris Lattnerbf209482005-10-30 19:42:35 +00004695 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004696 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004697 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004698}
4699
Duncan Sandsf4070822007-06-15 19:04:19 +00004700static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4701 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004702 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004703 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004704 // Apply the catch info to DestBB.
4705 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4706#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004707 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4708 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004709#endif
4710 }
4711}
4712
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004713/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4714/// whether object offset >= 0.
4715static bool
4716IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4717 if (!isa<FrameIndexSDNode>(Op)) return false;
4718
4719 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4720 int FrameIdx = FrameIdxNode->getIndex();
4721 return MFI->isFixedObjectIndex(FrameIdx) &&
4722 MFI->getObjectOffset(FrameIdx) >= 0;
4723}
4724
4725/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4726/// possibly be overwritten when lowering the outgoing arguments in a tail
4727/// call. Currently the implementation of this call is very conservative and
4728/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4729/// virtual registers would be overwritten by direct lowering.
4730static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4731 MachineFrameInfo * MFI) {
4732 RegisterSDNode * OpReg = NULL;
4733 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4734 (Op.getOpcode()== ISD::CopyFromReg &&
4735 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4736 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4737 (Op.getOpcode() == ISD::LOAD &&
4738 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4739 (Op.getOpcode() == ISD::MERGE_VALUES &&
4740 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4741 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4742 getOperand(1))))
4743 return true;
4744 return false;
4745}
4746
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004747/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004748/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004749static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4750 TargetLowering& TLI) {
4751 SDNode * Ret = NULL;
4752 SDOperand Terminator = DAG.getRoot();
4753
4754 // Find RET node.
4755 if (Terminator.getOpcode() == ISD::RET) {
4756 Ret = Terminator.Val;
4757 }
4758
4759 // Fix tail call attribute of CALL nodes.
4760 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4761 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4762 if (BI->getOpcode() == ISD::CALL) {
4763 SDOperand OpRet(Ret, 0);
4764 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4765 bool isMarkedTailCall =
4766 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4767 // If CALL node has tail call attribute set to true and the call is not
4768 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004769 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004770 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004771 if (!isMarkedTailCall) continue;
4772 if (Ret==NULL ||
4773 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4774 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004775 SmallVector<SDOperand, 32> Ops;
4776 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004777 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4778 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004779 if (idx!=3)
4780 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004781 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004782 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4783 }
4784 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004785 } else {
4786 // Look for tail call clobbered arguments. Emit a series of
4787 // copyto/copyfrom virtual register nodes to protect them.
4788 SmallVector<SDOperand, 32> Ops;
4789 SDOperand Chain = OpCall.getOperand(0), InFlag;
4790 unsigned idx=0;
4791 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4792 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4793 SDOperand Arg = *I;
4794 if (idx > 4 && (idx % 2)) {
4795 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4796 getArgFlags().isByVal();
4797 MachineFunction &MF = DAG.getMachineFunction();
4798 MachineFrameInfo *MFI = MF.getFrameInfo();
4799 if (!isByVal &&
4800 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004801 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004802 unsigned VReg = MF.getRegInfo().
4803 createVirtualRegister(TLI.getRegClassFor(VT));
4804 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4805 InFlag = Chain.getValue(1);
4806 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4807 Chain = Arg.getValue(1);
4808 InFlag = Arg.getValue(2);
4809 }
4810 }
4811 Ops.push_back(Arg);
4812 }
4813 // Link in chain of CopyTo/CopyFromReg.
4814 Ops[0] = Chain;
4815 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004816 }
4817 }
4818 }
4819}
4820
Chris Lattner1c08c712005-01-07 07:47:53 +00004821void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4822 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004823 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004824 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004825
Chris Lattnerbf209482005-10-30 19:42:35 +00004826 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004827 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004828 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004829
4830 BB = FuncInfo.MBBMap[LLVMBB];
4831 SDL.setCurrentBasicBlock(BB);
4832
Duncan Sandsf4070822007-06-15 19:04:19 +00004833 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004834
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004835 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004836 // Add a label to mark the beginning of the landing pad. Deletion of the
4837 // landing pad can thus be detected via the MachineModuleInfo.
4838 unsigned LabelID = MMI->addLandingPad(BB);
4839 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004840 DAG.getConstant(LabelID, MVT::i32),
4841 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004842
Evan Chenge47c3332007-06-27 18:45:32 +00004843 // Mark exception register as live in.
4844 unsigned Reg = TLI.getExceptionAddressRegister();
4845 if (Reg) BB->addLiveIn(Reg);
4846
4847 // Mark exception selector register as live in.
4848 Reg = TLI.getExceptionSelectorRegister();
4849 if (Reg) BB->addLiveIn(Reg);
4850
Duncan Sandsf4070822007-06-15 19:04:19 +00004851 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4852 // function and list of typeids logically belong to the invoke (or, if you
4853 // like, the basic block containing the invoke), and need to be associated
4854 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004855 // information is provided by an intrinsic (eh.selector) that can be moved
4856 // to unexpected places by the optimizers: if the unwind edge is critical,
4857 // then breaking it can result in the intrinsics being in the successor of
4858 // the landing pad, not the landing pad itself. This results in exceptions
4859 // not being caught because no typeids are associated with the invoke.
4860 // This may not be the only way things can go wrong, but it is the only way
4861 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004862 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4863
4864 if (Br && Br->isUnconditional()) { // Critical edge?
4865 BasicBlock::iterator I, E;
4866 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004867 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004868 break;
4869
4870 if (I == E)
4871 // No catch info found - try to extract some from the successor.
4872 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004873 }
4874 }
4875
Chris Lattner1c08c712005-01-07 07:47:53 +00004876 // Lower all of the non-terminator instructions.
4877 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4878 I != E; ++I)
4879 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004880
Chris Lattner1c08c712005-01-07 07:47:53 +00004881 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004882 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004883 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004884 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004885 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004886 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004887 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004888 }
4889
4890 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4891 // ensure constants are generated when needed. Remember the virtual registers
4892 // that need to be added to the Machine PHI nodes as input. We cannot just
4893 // directly add them, because expansion might result in multiple MBB's for one
4894 // BB. As such, the start of the BB might correspond to a different MBB than
4895 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004896 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004897 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004898
4899 // Emit constants only once even if used by multiple PHI nodes.
4900 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004901
Chris Lattner8c494ab2006-10-27 23:50:33 +00004902 // Vector bool would be better, but vector<bool> is really slow.
4903 std::vector<unsigned char> SuccsHandled;
4904 if (TI->getNumSuccessors())
4905 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4906
Dan Gohman532dc2e2007-07-09 20:59:04 +00004907 // Check successor nodes' PHI nodes that expect a constant to be available
4908 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004909 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4910 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004911 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004912 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004913
Chris Lattner8c494ab2006-10-27 23:50:33 +00004914 // If this terminator has multiple identical successors (common for
4915 // switches), only handle each succ once.
4916 unsigned SuccMBBNo = SuccMBB->getNumber();
4917 if (SuccsHandled[SuccMBBNo]) continue;
4918 SuccsHandled[SuccMBBNo] = true;
4919
4920 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004921 PHINode *PN;
4922
4923 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4924 // nodes and Machine PHI nodes, but the incoming operands have not been
4925 // emitted yet.
4926 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004927 (PN = dyn_cast<PHINode>(I)); ++I) {
4928 // Ignore dead phi's.
4929 if (PN->use_empty()) continue;
4930
4931 unsigned Reg;
4932 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004933
Chris Lattner8c494ab2006-10-27 23:50:33 +00004934 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4935 unsigned &RegOut = ConstantsOut[C];
4936 if (RegOut == 0) {
4937 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004938 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004939 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004940 Reg = RegOut;
4941 } else {
4942 Reg = FuncInfo.ValueMap[PHIOp];
4943 if (Reg == 0) {
4944 assert(isa<AllocaInst>(PHIOp) &&
4945 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4946 "Didn't codegen value into a register!??");
4947 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004948 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004949 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004950 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004951
4952 // Remember that this register needs to added to the machine PHI node as
4953 // the input for this MBB.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004954 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004955 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004956 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004957 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4958 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004959 }
4960 ConstantsOut.clear();
4961
4962 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004963 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004964
Nate Begemanf15485a2006-03-27 01:32:24 +00004965 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004966 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004967 SwitchCases.clear();
4968 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004969 JTCases.clear();
4970 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004971 BitTestCases.clear();
4972 BitTestCases = SDL.BitTestCases;
4973
Chris Lattnera651cf62005-01-17 19:43:36 +00004974 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004975 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004976
4977 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4978 // with correct tailcall attribute so that the target can rely on the tailcall
4979 // attribute indicating whether the call is really eligible for tail call
4980 // optimization.
4981 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004982}
4983
Nate Begemanf15485a2006-03-27 01:32:24 +00004984void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004985 DOUT << "Lowered selection DAG:\n";
4986 DEBUG(DAG.dump());
4987
Chris Lattneraf21d552005-10-10 16:47:10 +00004988 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004989 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004990
Dan Gohman417e11b2007-10-08 15:12:17 +00004991 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004992 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004993
Chris Lattner1c08c712005-01-07 07:47:53 +00004994 // Second step, hack on the DAG until it only uses operations and types that
4995 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004996#if 0 // Enable this some day.
4997 DAG.LegalizeTypes();
4998 // Someday even later, enable a dag combine pass here.
4999#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00005000 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00005001
Bill Wendling832171c2006-12-07 20:04:42 +00005002 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005003 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005004
Chris Lattneraf21d552005-10-10 16:47:10 +00005005 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00005006 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00005007
Dan Gohman417e11b2007-10-08 15:12:17 +00005008 DOUT << "Optimized legalized selection DAG:\n";
5009 DEBUG(DAG.dump());
5010
Evan Chenga9c20912006-01-21 02:32:06 +00005011 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00005012
Chris Lattnera33ef482005-03-30 01:10:47 +00005013 // Third, instruction select all of the operations to machine code, adding the
5014 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005015 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005016
Bill Wendling832171c2006-12-07 20:04:42 +00005017 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005018 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005019}
Chris Lattner1c08c712005-01-07 07:47:53 +00005020
Nate Begemanf15485a2006-03-27 01:32:24 +00005021void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5022 FunctionLoweringInfo &FuncInfo) {
5023 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5024 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005025 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005026 CurDAG = &DAG;
5027
5028 // First step, lower LLVM code to some DAG. This DAG may use operations and
5029 // types that are not supported by the target.
5030 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5031
5032 // Second step, emit the lowered DAG as machine code.
5033 CodeGenAndEmitDAG(DAG);
5034 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005035
5036 DOUT << "Total amount of phi nodes to update: "
5037 << PHINodesToUpdate.size() << "\n";
5038 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5039 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5040 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005041
Chris Lattnera33ef482005-03-30 01:10:47 +00005042 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005043 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005044 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005045 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5046 MachineInstr *PHI = PHINodesToUpdate[i].first;
5047 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5048 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005049 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5050 false));
5051 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005052 }
5053 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005054 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005055
5056 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5057 // Lower header first, if it wasn't already lowered
5058 if (!BitTestCases[i].Emitted) {
5059 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5060 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005061 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = BitTestCases[i].Parent;
5064 HSDL.setCurrentBasicBlock(BB);
5065 // Emit the code
5066 HSDL.visitBitTestHeader(BitTestCases[i]);
5067 HSDAG.setRoot(HSDL.getRoot());
5068 CodeGenAndEmitDAG(HSDAG);
5069 }
5070
5071 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5072 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5073 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005074 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005075 // Set the current basic block to the mbb we wish to insert the code into
5076 BB = BitTestCases[i].Cases[j].ThisBB;
5077 BSDL.setCurrentBasicBlock(BB);
5078 // Emit the code
5079 if (j+1 != ej)
5080 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5081 BitTestCases[i].Reg,
5082 BitTestCases[i].Cases[j]);
5083 else
5084 BSDL.visitBitTestCase(BitTestCases[i].Default,
5085 BitTestCases[i].Reg,
5086 BitTestCases[i].Cases[j]);
5087
5088
5089 BSDAG.setRoot(BSDL.getRoot());
5090 CodeGenAndEmitDAG(BSDAG);
5091 }
5092
5093 // Update PHI Nodes
5094 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5095 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5096 MachineBasicBlock *PHIBB = PHI->getParent();
5097 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5098 "This is not a machine PHI node that we are updating!");
5099 // This is "default" BB. We have two jumps to it. From "header" BB and
5100 // from last "case" BB.
5101 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005102 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5103 false));
5104 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5105 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5106 false));
5107 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5108 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005109 }
5110 // One of "cases" BB.
5111 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5112 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5113 if (cBB->succ_end() !=
5114 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005115 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5116 false));
5117 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005118 }
5119 }
5120 }
5121 }
5122
Nate Begeman9453eea2006-04-23 06:26:20 +00005123 // If the JumpTable record is filled in, then we need to emit a jump table.
5124 // Updating the PHI nodes is tricky in this case, since we need to determine
5125 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005126 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5127 // Lower header first, if it wasn't already lowered
5128 if (!JTCases[i].first.Emitted) {
5129 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5130 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005131 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005132 // Set the current basic block to the mbb we wish to insert the code into
5133 BB = JTCases[i].first.HeaderBB;
5134 HSDL.setCurrentBasicBlock(BB);
5135 // Emit the code
5136 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5137 HSDAG.setRoot(HSDL.getRoot());
5138 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005139 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005140
5141 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5142 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005143 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005144 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005145 BB = JTCases[i].second.MBB;
5146 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005147 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005148 JSDL.visitJumpTable(JTCases[i].second);
5149 JSDAG.setRoot(JSDL.getRoot());
5150 CodeGenAndEmitDAG(JSDAG);
5151
Nate Begeman37efe672006-04-22 18:53:45 +00005152 // Update PHI Nodes
5153 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5154 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5155 MachineBasicBlock *PHIBB = PHI->getParent();
5156 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5157 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005158 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005159 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005160 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5161 false));
5162 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005163 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005164 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005165 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005166 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5167 false));
5168 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005169 }
5170 }
Nate Begeman37efe672006-04-22 18:53:45 +00005171 }
5172
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005173 // If the switch block involved a branch to one of the actual successors, we
5174 // need to update PHI nodes in that block.
5175 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5176 MachineInstr *PHI = PHINodesToUpdate[i].first;
5177 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5178 "This is not a machine PHI node that we are updating!");
5179 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005180 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5181 false));
5182 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005183 }
5184 }
5185
Nate Begemanf15485a2006-03-27 01:32:24 +00005186 // If we generated any switch lowering information, build and codegen any
5187 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005188 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005189 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005190 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005191 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005192
Nate Begemanf15485a2006-03-27 01:32:24 +00005193 // Set the current basic block to the mbb we wish to insert the code into
5194 BB = SwitchCases[i].ThisBB;
5195 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005196
Nate Begemanf15485a2006-03-27 01:32:24 +00005197 // Emit the code
5198 SDL.visitSwitchCase(SwitchCases[i]);
5199 SDAG.setRoot(SDL.getRoot());
5200 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005201
5202 // Handle any PHI nodes in successors of this chunk, as if we were coming
5203 // from the original BB before switch expansion. Note that PHI nodes can
5204 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5205 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005206 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005207 for (MachineBasicBlock::iterator Phi = BB->begin();
5208 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5209 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5210 for (unsigned pn = 0; ; ++pn) {
5211 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5212 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005213 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5214 second, false));
5215 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005216 break;
5217 }
5218 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005219 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005220
5221 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005222 if (BB == SwitchCases[i].FalseBB)
5223 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005224
5225 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005226 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005227 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005228 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005229 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005230 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005231}
Evan Chenga9c20912006-01-21 02:32:06 +00005232
Jim Laskey13ec7022006-08-01 14:21:23 +00005233
Evan Chenga9c20912006-01-21 02:32:06 +00005234//===----------------------------------------------------------------------===//
5235/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5236/// target node in the graph.
5237void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5238 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005239
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005240 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005241
5242 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005243 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005244 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005245 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005246
Jim Laskey9ff542f2006-08-01 18:29:48 +00005247 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005248 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005249
5250 if (ViewSUnitDAGs) SL->viewGraph();
5251
Evan Chengcccf1232006-02-04 06:49:00 +00005252 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005253}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005254
Chris Lattner03fc53c2006-03-06 00:22:00 +00005255
Jim Laskey9ff542f2006-08-01 18:29:48 +00005256HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5257 return new HazardRecognizer();
5258}
5259
Chris Lattner75548062006-10-11 03:58:02 +00005260//===----------------------------------------------------------------------===//
5261// Helper functions used by the generated instruction selector.
5262//===----------------------------------------------------------------------===//
5263// Calls to these methods are generated by tblgen.
5264
5265/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5266/// the dag combiner simplified the 255, we still want to match. RHS is the
5267/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5268/// specified in the .td file (e.g. 255).
5269bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005270 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005271 const APInt &ActualMask = RHS->getAPIntValue();
5272 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005273
5274 // If the actual mask exactly matches, success!
5275 if (ActualMask == DesiredMask)
5276 return true;
5277
5278 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005279 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005280 return false;
5281
5282 // Otherwise, the DAG Combiner may have proven that the value coming in is
5283 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005284 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005285 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005286 return true;
5287
5288 // TODO: check to see if missing bits are just not demanded.
5289
5290 // Otherwise, this pattern doesn't match.
5291 return false;
5292}
5293
5294/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5295/// the dag combiner simplified the 255, we still want to match. RHS is the
5296/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5297/// specified in the .td file (e.g. 255).
5298bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005299 int64_t DesiredMaskS) const {
5300 const APInt &ActualMask = RHS->getAPIntValue();
5301 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005302
5303 // If the actual mask exactly matches, success!
5304 if (ActualMask == DesiredMask)
5305 return true;
5306
5307 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005308 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005309 return false;
5310
5311 // Otherwise, the DAG Combiner may have proven that the value coming in is
5312 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005313 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005314
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005315 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005316 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005317
5318 // If all the missing bits in the or are already known to be set, match!
5319 if ((NeededMask & KnownOne) == NeededMask)
5320 return true;
5321
5322 // TODO: check to see if missing bits are just not demanded.
5323
5324 // Otherwise, this pattern doesn't match.
5325 return false;
5326}
5327
Jim Laskey9ff542f2006-08-01 18:29:48 +00005328
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005329/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5330/// by tblgen. Others should not call it.
5331void SelectionDAGISel::
5332SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5333 std::vector<SDOperand> InOps;
5334 std::swap(InOps, Ops);
5335
5336 Ops.push_back(InOps[0]); // input chain.
5337 Ops.push_back(InOps[1]); // input asm string.
5338
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005339 unsigned i = 2, e = InOps.size();
5340 if (InOps[e-1].getValueType() == MVT::Flag)
5341 --e; // Don't process a flag operand if it is here.
5342
5343 while (i != e) {
5344 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5345 if ((Flags & 7) != 4 /*MEM*/) {
5346 // Just skip over this operand, copying the operands verbatim.
5347 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5348 i += (Flags >> 3) + 1;
5349 } else {
5350 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5351 // Otherwise, this is a memory operand. Ask the target to select it.
5352 std::vector<SDOperand> SelOps;
5353 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005354 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005355 exit(1);
5356 }
5357
5358 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005359 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005360 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005361 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005362 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5363 i += 2;
5364 }
5365 }
5366
5367 // Add the flag input back if present.
5368 if (e != InOps.size())
5369 Ops.push_back(InOps.back());
5370}
Devang Patel794fd752007-05-01 21:15:47 +00005371
Devang Patel19974732007-05-03 01:11:54 +00005372char SelectionDAGISel::ID = 0;