blob: d7369d3070e388845798faa06f0daa1864b68bfb [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeydcb2b832006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000073namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey03593f72006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner4333f8b2007-04-30 17:29:31 +000085namespace { struct AsmOperandInfo; }
86
Chris Lattner6f87d182006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000135 };
136}
Evan Chengc1e1d972006-01-23 07:01:07 +0000137
Chris Lattner7a60d912005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000175 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
Duncan Sands92bf2c62007-06-15 19:04:19 +0000182#ifndef NDEBUG
183 SmallSet<Instruction*, 8> CatchInfoLost;
184 SmallSet<Instruction*, 8> CatchInfoFound;
185#endif
186
Chris Lattner7a60d912005-01-07 07:47:53 +0000187 unsigned MakeReg(MVT::ValueType VT) {
188 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
189 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000190
191 /// isExportedInst - Return true if the specified value is an instruction
192 /// exported from its block.
193 bool isExportedInst(const Value *V) {
194 return ValueMap.count(V);
195 }
Misha Brukman835702a2005-04-21 22:36:52 +0000196
Chris Lattner49409cb2006-03-16 19:51:18 +0000197 unsigned CreateRegForValue(const Value *V);
198
Chris Lattner7a60d912005-01-07 07:47:53 +0000199 unsigned InitializeRegForValue(const Value *V) {
200 unsigned &R = ValueMap[V];
201 assert(R == 0 && "Already initialized this value register!");
202 return R = CreateRegForValue(V);
203 }
204 };
205}
206
Duncan Sands92bf2c62007-06-15 19:04:19 +0000207/// isFilterOrSelector - Return true if this instruction is a call to the
208/// eh.filter or the eh.selector intrinsic.
209static bool isFilterOrSelector(Instruction *I) {
210 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
211 return II->getIntrinsicID() == Intrinsic::eh_selector
212 || II->getIntrinsicID() == Intrinsic::eh_filter;
213 return false;
214}
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000217/// PHI nodes or outside of the basic block that defines it, or used by a
218/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000219static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
220 if (isa<PHINode>(I)) return true;
221 BasicBlock *BB = I->getParent();
222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000223 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000224 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000225 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000226 return true;
227 return false;
228}
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000231/// entry block, return true. This includes arguments used by switches, since
232/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000233static bool isOnlyUsedInEntryBlock(Argument *A) {
234 BasicBlock *Entry = A->getParent()->begin();
235 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000236 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000237 return false; // Use not in entry block.
238 return true;
239}
240
Chris Lattner7a60d912005-01-07 07:47:53 +0000241FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000242 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000243 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
244
Chris Lattner6871b232005-10-30 19:42:35 +0000245 // Create a vreg for each argument register that is not dead and is used
246 // outside of the entry block for the function.
247 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
248 AI != E; ++AI)
249 if (!isOnlyUsedInEntryBlock(AI))
250 InitializeRegForValue(AI);
251
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 // Initialize the mapping of values to registers. This is only set up for
253 // instruction values that are used outside of the block that defines
254 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000255 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000258 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000259 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000261 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000263 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000264
Reid Spencere0fc4df2006-10-20 07:07:24 +0000265 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000266 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 StaticAllocaMap[AI] =
Chris Lattnercb0ed0c2007-04-25 04:08:28 +0000268 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000269 }
270
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000271 for (; BB != EB; ++BB)
272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000273 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
274 if (!isa<AllocaInst>(I) ||
275 !StaticAllocaMap.count(cast<AllocaInst>(I)))
276 InitializeRegForValue(I);
277
278 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
279 // also creates the initial PHI MachineInstrs, though none of the input
280 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000281 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000282 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
283 MBBMap[BB] = MBB;
284 MF.getBasicBlockList().push_back(MBB);
285
286 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
287 // appropriate.
288 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000289 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
290 if (PN->use_empty()) continue;
291
292 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohmana8665142007-06-25 16:23:39 +0000293 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner84a03502006-10-27 23:50:33 +0000294 unsigned PHIReg = ValueMap[PN];
295 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000296 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohman04deef32007-06-21 14:42:22 +0000297 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000298 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000299 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000300 }
301}
302
Chris Lattner49409cb2006-03-16 19:51:18 +0000303/// CreateRegForValue - Allocate the appropriate number of virtual registers of
304/// the correctly promoted or expanded types. Assign these registers
305/// consecutive vreg numbers and return the first assigned number.
306unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
308
Dan Gohman7139a482007-06-27 14:34:07 +0000309 unsigned NumRegisters;
310 MVT::ValueType RegisterVT;
Dan Gohmana8665142007-06-25 16:23:39 +0000311 if (MVT::isVector(VT)) {
Dan Gohman7139a482007-06-27 14:34:07 +0000312 MVT::ValueType ElementVT;
313 NumRegisters = TLI.getVectorTypeBreakdown(VT, ElementVT, RegisterVT);
314 } else {
315 RegisterVT = TLI.getTypeToTransformTo(VT);
316 NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000317 }
Bill Wendling47917b62007-04-24 21:13:23 +0000318
Dan Gohman7139a482007-06-27 14:34:07 +0000319 unsigned R = MakeReg(RegisterVT);
320 for (unsigned i = 1; i != NumRegisters; ++i)
321 MakeReg(RegisterVT);
322
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 return R;
324}
Chris Lattner7a60d912005-01-07 07:47:53 +0000325
326//===----------------------------------------------------------------------===//
327/// SelectionDAGLowering - This is the common target-independent lowering
328/// implementation that is parameterized by a TargetLowering object.
329/// Also, targets can overload any lowering method.
330///
331namespace llvm {
332class SelectionDAGLowering {
333 MachineBasicBlock *CurMBB;
334
Chris Lattner79084302007-02-04 01:31:47 +0000335 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000336
Chris Lattner4d9651c2005-01-17 22:19:26 +0000337 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
338 /// them up and then emit token factor nodes when possible. This allows us to
339 /// get simple disambiguation between loads without worrying about alias
340 /// analysis.
341 std::vector<SDOperand> PendingLoads;
342
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000343 /// Case - A struct to record the Value for a switch case, and the
344 /// case's target basic block.
345 struct Case {
346 Constant* Low;
347 Constant* High;
348 MachineBasicBlock* BB;
349
350 Case() : Low(0), High(0), BB(0) { }
351 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
352 Low(low), High(high), BB(bb) { }
353 uint64_t size() const {
354 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
355 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
356 return (rHigh - rLow + 1ULL);
357 }
358 };
359
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000360 struct CaseBits {
361 uint64_t Mask;
362 MachineBasicBlock* BB;
363 unsigned Bits;
364
365 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
366 Mask(mask), BB(bb), Bits(bits) { }
367 };
368
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000369 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000370 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000371 typedef CaseVector::iterator CaseItr;
372 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000373
374 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
375 /// of conditional branches.
376 struct CaseRec {
377 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
378 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
379
380 /// CaseBB - The MBB in which to emit the compare and branch
381 MachineBasicBlock *CaseBB;
382 /// LT, GE - If nonzero, we know the current case value must be less-than or
383 /// greater-than-or-equal-to these Constants.
384 Constant *LT;
385 Constant *GE;
386 /// Range - A pair of iterators representing the range of case values to be
387 /// processed at this point in the binary search tree.
388 CaseRange Range;
389 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000390
391 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000392
393 /// The comparison function for sorting the switch case values in the vector.
394 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000395 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000396 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000397 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
398 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
399 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
400 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000401 }
402 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000403
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000404 struct CaseBitsCmp {
405 bool operator () (const CaseBits& C1, const CaseBits& C2) {
406 return C1.Bits > C2.Bits;
407 }
408 };
409
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000410 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000411
Chris Lattner7a60d912005-01-07 07:47:53 +0000412public:
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
416 TargetLowering &TLI;
417 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000418 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000419
Nate Begemaned728c12006-03-27 01:32:24 +0000420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000423 /// JTCases - Vector of JumpTable structures used to communicate
424 /// SwitchInst code generation information.
425 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000426 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000427
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 /// FuncInfo - Information about the function as a whole.
429 ///
430 FunctionLoweringInfo &FuncInfo;
431
432 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000433 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000434 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000435 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000436 }
437
Chris Lattner4108bb02005-01-17 19:43:36 +0000438 /// getRoot - Return the current virtual root of the Selection DAG.
439 ///
440 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000441 if (PendingLoads.empty())
442 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000443
Chris Lattner4d9651c2005-01-17 22:19:26 +0000444 if (PendingLoads.size() == 1) {
445 SDOperand Root = PendingLoads[0];
446 DAG.setRoot(Root);
447 PendingLoads.clear();
448 return Root;
449 }
450
451 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000452 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
453 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000454 PendingLoads.clear();
455 DAG.setRoot(Root);
456 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000457 }
458
Chris Lattnered0110b2006-10-27 21:36:01 +0000459 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
460
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 void visit(Instruction &I) { visit(I.getOpcode(), I); }
462
463 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000464 // Note: this doesn't use InstVisitor, because it has to work with
465 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000466 switch (Opcode) {
467 default: assert(0 && "Unknown instruction type encountered!");
468 abort();
469 // Build the switch statement using the Instruction.def file.
470#define HANDLE_INST(NUM, OPCODE, CLASS) \
471 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
472#include "llvm/Instruction.def"
473 }
474 }
475
476 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
477
Chris Lattner4024c002006-03-15 22:19:46 +0000478 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000479 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000480 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000481
482 SDOperand getIntPtrConstant(uint64_t Val) {
483 return DAG.getConstant(Val, TLI.getPointerTy());
484 }
485
Chris Lattner8471b152006-03-16 19:57:50 +0000486 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000487
Chris Lattner79084302007-02-04 01:31:47 +0000488 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 SDOperand &N = NodeMap[V];
490 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000491 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000493
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000494 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
495 std::set<unsigned> &OutputRegs,
496 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattnered0110b2006-10-27 21:36:01 +0000498 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
499 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
500 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000501 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000502 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000503 void LowerCallTo(Instruction &I,
504 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000505 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
506 MachineBasicBlock *LandingPad = NULL);
507
Chris Lattner7a60d912005-01-07 07:47:53 +0000508 // Terminator instructions.
509 void visitRet(ReturnInst &I);
510 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000511 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 void visitUnreachable(UnreachableInst &I) { /* noop */ }
513
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000514 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000515 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000516 CaseRecVector& WorkList,
517 Value* SV,
518 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000519 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000520 CaseRecVector& WorkList,
521 Value* SV,
522 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000523 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000524 CaseRecVector& WorkList,
525 Value* SV,
526 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000527 bool handleBitTestsSwitchCase(CaseRec& CR,
528 CaseRecVector& WorkList,
529 Value* SV,
530 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000531 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000532 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
533 void visitBitTestCase(MachineBasicBlock* NextMBB,
534 unsigned Reg,
535 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000536 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000537 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
538 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000539
Chris Lattner7a60d912005-01-07 07:47:53 +0000540 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000541 void visitInvoke(InvokeInst &I);
542 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
Dan Gohmana8665142007-06-25 16:23:39 +0000544 void visitBinary(User &I, unsigned OpCode);
Nate Begeman127321b2005-11-18 07:42:56 +0000545 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000546 void visitAdd(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000547 if (I.getType()->isFPOrFPVector())
548 visitBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000549 else
Dan Gohmana8665142007-06-25 16:23:39 +0000550 visitBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000551 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000552 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000553 void visitMul(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000554 if (I.getType()->isFPOrFPVector())
555 visitBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000556 else
Dan Gohmana8665142007-06-25 16:23:39 +0000557 visitBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000558 }
Dan Gohmana8665142007-06-25 16:23:39 +0000559 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
560 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
561 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
562 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
563 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
564 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
565 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
566 void visitOr (User &I) { visitBinary(I, ISD::OR); }
567 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer2eadb532007-01-21 00:29:26 +0000568 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000569 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
570 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000571 void visitICmp(User &I);
572 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000573 // Visit the conversion instructions
574 void visitTrunc(User &I);
575 void visitZExt(User &I);
576 void visitSExt(User &I);
577 void visitFPTrunc(User &I);
578 void visitFPExt(User &I);
579 void visitFPToUI(User &I);
580 void visitFPToSI(User &I);
581 void visitUIToFP(User &I);
582 void visitSIToFP(User &I);
583 void visitPtrToInt(User &I);
584 void visitIntToPtr(User &I);
585 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000586
Chris Lattner67271862006-03-29 00:11:43 +0000587 void visitExtractElement(User &I);
588 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000589 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000590
Chris Lattner7a60d912005-01-07 07:47:53 +0000591 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000592 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000593
594 void visitMalloc(MallocInst &I);
595 void visitFree(FreeInst &I);
596 void visitAlloca(AllocaInst &I);
597 void visitLoad(LoadInst &I);
598 void visitStore(StoreInst &I);
599 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
600 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000601 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000602 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000603 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000604
Chris Lattner7a60d912005-01-07 07:47:53 +0000605 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000606 void visitVAArg(VAArgInst &I);
607 void visitVAEnd(CallInst &I);
608 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000609
Chris Lattner875def92005-01-11 05:56:49 +0000610 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000611
612 void visitUserOp1(Instruction &I) {
613 assert(0 && "UserOp1 should not exist at instruction selection time!");
614 abort();
615 }
616 void visitUserOp2(Instruction &I) {
617 assert(0 && "UserOp2 should not exist at instruction selection time!");
618 abort();
619 }
620};
621} // end namespace llvm
622
Chris Lattner8471b152006-03-16 19:57:50 +0000623SDOperand SelectionDAGLowering::getValue(const Value *V) {
624 SDOperand &N = NodeMap[V];
625 if (N.Val) return N;
626
627 const Type *VTy = V->getType();
628 MVT::ValueType VT = TLI.getValueType(VTy);
629 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
630 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
631 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000632 SDOperand N1 = NodeMap[V];
633 assert(N1.Val && "visit didn't populate the ValueMap!");
634 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000635 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
636 return N = DAG.getGlobalAddress(GV, VT);
637 } else if (isa<ConstantPointerNull>(C)) {
638 return N = DAG.getConstant(0, TLI.getPointerTy());
639 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000640 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000641 return N = DAG.getNode(ISD::UNDEF, VT);
642
Dan Gohmana8665142007-06-25 16:23:39 +0000643 // Create a BUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000644 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000645 unsigned NumElements = PTy->getNumElements();
646 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
647
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000648 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000649 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
650
651 // Create a VConstant node with generic Vector type.
Dan Gohmana8665142007-06-25 16:23:39 +0000652 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
653 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000654 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000655 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
656 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000657 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000658 unsigned NumElements = PTy->getNumElements();
659 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000660
661 // Now that we know the number and type of the elements, push a
662 // Constant or ConstantFP node onto the ops list for each element of
663 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000664 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000665 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000666 for (unsigned i = 0; i != NumElements; ++i)
667 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000668 } else {
669 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
670 SDOperand Op;
671 if (MVT::isFloatingPoint(PVT))
672 Op = DAG.getConstantFP(0, PVT);
673 else
674 Op = DAG.getConstant(0, PVT);
675 Ops.assign(NumElements, Op);
676 }
677
Dan Gohmana8665142007-06-25 16:23:39 +0000678 // Create a BUILD_VECTOR node.
679 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
680 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner79084302007-02-04 01:31:47 +0000681 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000682 } else {
683 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000684 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000685 }
686 }
687
688 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
689 std::map<const AllocaInst*, int>::iterator SI =
690 FuncInfo.StaticAllocaMap.find(AI);
691 if (SI != FuncInfo.StaticAllocaMap.end())
692 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
693 }
694
Chris Lattner8c504cf2007-02-25 18:40:32 +0000695 unsigned InReg = FuncInfo.ValueMap[V];
696 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000697
698 // If this type is not legal, make it so now.
Dan Gohmana8665142007-06-25 16:23:39 +0000699 if (!MVT::isVector(VT)) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000700 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000701 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000702 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000703 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +0000704 unsigned NumVals = TLI.getNumRegisters(VT);
Evan Cheng22cf8992006-12-13 20:57:08 +0000705 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
706 if (NumVals == 1)
707 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
708 else {
709 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
710 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
Dan Gohmana8665142007-06-25 16:23:39 +0000711 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
Evan Cheng22cf8992006-12-13 20:57:08 +0000712 }
713 } else {
714 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
715 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
716 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
717 N = MVT::isFloatingPoint(VT)
718 ? DAG.getNode(ISD::FP_ROUND, VT, N)
719 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000720 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000721 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000722 // Otherwise, if this is a vector, make it available as a vector
Chris Lattner5fe1f542006-03-31 02:06:56 +0000723 // here.
Dan Gohmana8665142007-06-25 16:23:39 +0000724 MVT::ValueType ElementVT, LegalElementVT;
725 unsigned NE = TLI.getVectorTypeBreakdown(VT, ElementVT,
726 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000727
Dan Gohmana8665142007-06-25 16:23:39 +0000728 // Build a BUILD_VECTOR or CONCAT_VECTORS with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000729 SmallVector<SDOperand, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +0000730 if (ElementVT == LegalElementVT) {
731 // If the value types are legal, just BUILD the CopyFromReg nodes.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000732 for (unsigned i = 0; i != NE; ++i)
733 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000734 ElementVT));
735 } else if (ElementVT < LegalElementVT) {
Dan Gohman30978072007-05-24 14:36:04 +0000736 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000737 for (unsigned i = 0; i != NE; ++i) {
738 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000739 LegalElementVT);
740 if (MVT::isFloatingPoint(ElementVT))
741 Op = DAG.getNode(ISD::FP_ROUND, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000742 else
Dan Gohmana8665142007-06-25 16:23:39 +0000743 Op = DAG.getNode(ISD::TRUNCATE, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000744 Ops.push_back(Op);
745 }
746 } else {
747 // If the register was expanded, use BUILD_PAIR.
748 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
Dan Gohmancbd51c82007-06-13 14:55:16 +0000749 for (unsigned i = 0; i != NE; ++i) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000750 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000751 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000752 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000753 LegalElementVT);
754 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, ElementVT, Op0, Op1));
Chris Lattner5fe1f542006-03-31 02:06:56 +0000755 }
756 }
757
Dan Gohmana8665142007-06-25 16:23:39 +0000758 if (MVT::isVector(ElementVT)) {
759 N = DAG.getNode(ISD::CONCAT_VECTORS,
760 MVT::getVectorType(MVT::getVectorElementType(ElementVT),
761 NE * MVT::getVectorNumElements(ElementVT)),
762 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000763 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000764 N = DAG.getNode(ISD::BUILD_VECTOR,
765 MVT::getVectorType(ElementVT, NE),
766 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000767 }
Chris Lattner8471b152006-03-16 19:57:50 +0000768 }
769
770 return N;
771}
772
773
Chris Lattner7a60d912005-01-07 07:47:53 +0000774void SelectionDAGLowering::visitRet(ReturnInst &I) {
775 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000776 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000777 return;
778 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000779 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000780 NewValues.push_back(getRoot());
781 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
782 SDOperand RetOp = getValue(I.getOperand(i));
783
784 // If this is an integer return value, we need to promote it ourselves to
785 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
786 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000787 // FIXME: C calling convention requires the return type to be promoted to
788 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000789 if (MVT::isInteger(RetOp.getValueType()) &&
790 RetOp.getValueType() < MVT::i64) {
791 MVT::ValueType TmpVT;
792 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
793 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
794 else
795 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000796 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000797 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000798 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000799 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000800 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000801 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000802 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000803 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000804 }
805 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000806 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000807 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000808 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
809 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000810}
811
Chris Lattnered0110b2006-10-27 21:36:01 +0000812/// ExportFromCurrentBlock - If this condition isn't known to be exported from
813/// the current basic block, add it to ValueMap now so that we'll get a
814/// CopyTo/FromReg.
815void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
816 // No need to export constants.
817 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
818
819 // Already exported?
820 if (FuncInfo.isExportedInst(V)) return;
821
822 unsigned Reg = FuncInfo.InitializeRegForValue(V);
823 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
824}
825
Chris Lattner84a03502006-10-27 23:50:33 +0000826bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
827 const BasicBlock *FromBB) {
828 // The operands of the setcc have to be in this block. We don't know
829 // how to export them from some other block.
830 if (Instruction *VI = dyn_cast<Instruction>(V)) {
831 // Can export from current BB.
832 if (VI->getParent() == FromBB)
833 return true;
834
835 // Is already exported, noop.
836 return FuncInfo.isExportedInst(V);
837 }
838
839 // If this is an argument, we can export it if the BB is the entry block or
840 // if it is already exported.
841 if (isa<Argument>(V)) {
842 if (FromBB == &FromBB->getParent()->getEntryBlock())
843 return true;
844
845 // Otherwise, can only export this if it is already exported.
846 return FuncInfo.isExportedInst(V);
847 }
848
849 // Otherwise, constants can always be exported.
850 return true;
851}
852
Chris Lattnere60ae822006-10-29 21:01:20 +0000853static bool InBlock(const Value *V, const BasicBlock *BB) {
854 if (const Instruction *I = dyn_cast<Instruction>(V))
855 return I->getParent() == BB;
856 return true;
857}
858
Chris Lattnered0110b2006-10-27 21:36:01 +0000859/// FindMergedConditions - If Cond is an expression like
860void SelectionDAGLowering::FindMergedConditions(Value *Cond,
861 MachineBasicBlock *TBB,
862 MachineBasicBlock *FBB,
863 MachineBasicBlock *CurBB,
864 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000865 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000866 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000867
Reid Spencer266e42b2006-12-23 06:05:41 +0000868 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
869 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000870 BOp->getParent() != CurBB->getBasicBlock() ||
871 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
872 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000873 const BasicBlock *BB = CurBB->getBasicBlock();
874
Reid Spencer266e42b2006-12-23 06:05:41 +0000875 // If the leaf of the tree is a comparison, merge the condition into
876 // the caseblock.
877 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
878 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000879 // how to export them from some other block. If this is the first block
880 // of the sequence, no exporting is needed.
881 (CurBB == CurMBB ||
882 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
883 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000884 BOp = cast<Instruction>(Cond);
885 ISD::CondCode Condition;
886 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
887 switch (IC->getPredicate()) {
888 default: assert(0 && "Unknown icmp predicate opcode!");
889 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
890 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
891 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
892 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
893 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
894 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
895 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
896 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
897 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
898 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
899 }
900 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
901 ISD::CondCode FPC, FOC;
902 switch (FC->getPredicate()) {
903 default: assert(0 && "Unknown fcmp predicate opcode!");
904 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
905 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
906 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
907 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
908 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
909 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
910 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
911 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
912 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
913 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
914 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
915 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
916 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
917 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
918 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
919 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
920 }
921 if (FiniteOnlyFPMath())
922 Condition = FOC;
923 else
924 Condition = FPC;
925 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000926 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000927 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000928 }
929
Chris Lattnered0110b2006-10-27 21:36:01 +0000930 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000931 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000932 SwitchCases.push_back(CB);
933 return;
934 }
935
936 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000937 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000938 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000939 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000940 return;
941 }
942
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000943
944 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000945 MachineFunction::iterator BBI = CurBB;
946 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
947 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
948
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000949 if (Opc == Instruction::Or) {
950 // Codegen X | Y as:
951 // jmp_if_X TBB
952 // jmp TmpBB
953 // TmpBB:
954 // jmp_if_Y TBB
955 // jmp FBB
956 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000957
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
960
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
963 } else {
964 assert(Opc == Instruction::And && "Unknown merge op!");
965 // Codegen X & Y as:
966 // jmp_if_X TmpBB
967 // jmp FBB
968 // TmpBB:
969 // jmp_if_Y TBB
970 // jmp FBB
971 //
972 // This requires creation of TmpBB after CurBB.
973
974 // Emit the LHS condition.
975 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
976
977 // Emit the RHS condition into TmpBB.
978 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
979 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000980}
981
Chris Lattner427301f2006-10-31 22:37:42 +0000982/// If the set of cases should be emitted as a series of branches, return true.
983/// If we should emit this as a bunch of and/or'd together conditions, return
984/// false.
985static bool
986ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
987 if (Cases.size() != 2) return true;
988
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000989 // If this is two comparisons of the same values or'd or and'd together, they
990 // will get folded into a single comparison, so don't emit two blocks.
991 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
992 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
993 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
994 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
995 return false;
996 }
997
Chris Lattner427301f2006-10-31 22:37:42 +0000998 return true;
999}
1000
Chris Lattner7a60d912005-01-07 07:47:53 +00001001void SelectionDAGLowering::visitBr(BranchInst &I) {
1002 // Update machine-CFG edges.
1003 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001004
1005 // Figure out which block is immediately after the current one.
1006 MachineBasicBlock *NextBlock = 0;
1007 MachineFunction::iterator BBI = CurMBB;
1008 if (++BBI != CurMBB->getParent()->end())
1009 NextBlock = BBI;
1010
1011 if (I.isUnconditional()) {
1012 // If this is not a fall-through branch, emit the branch.
1013 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001014 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001015 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001016
Chris Lattner963ddad2006-10-24 17:57:59 +00001017 // Update machine-CFG edges.
1018 CurMBB->addSuccessor(Succ0MBB);
1019
1020 return;
1021 }
1022
1023 // If this condition is one of the special cases we handle, do special stuff
1024 // now.
1025 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001026 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001027
1028 // If this is a series of conditions that are or'd or and'd together, emit
1029 // this as a sequence of branches instead of setcc's with and/or operations.
1030 // For example, instead of something like:
1031 // cmp A, B
1032 // C = seteq
1033 // cmp D, E
1034 // F = setle
1035 // or C, F
1036 // jnz foo
1037 // Emit:
1038 // cmp A, B
1039 // je foo
1040 // cmp D, E
1041 // jle foo
1042 //
1043 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1044 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001045 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001046 BOp->getOpcode() == Instruction::Or)) {
1047 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001048 // If the compares in later blocks need to use values not currently
1049 // exported from this block, export them now. This block should always
1050 // be the first entry.
1051 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1052
Chris Lattner427301f2006-10-31 22:37:42 +00001053 // Allow some cases to be rejected.
1054 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001055 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1056 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1057 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1058 }
1059
1060 // Emit the branch for this block.
1061 visitSwitchCase(SwitchCases[0]);
1062 SwitchCases.erase(SwitchCases.begin());
1063 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001064 }
1065
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001066 // Okay, we decided not to do this, remove any inserted MBB's and clear
1067 // SwitchCases.
1068 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1069 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1070
Chris Lattner427301f2006-10-31 22:37:42 +00001071 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001072 }
1073 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001074
1075 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001076 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001077 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001078 // Use visitSwitchCase to actually insert the fast branch sequence for this
1079 // cond branch.
1080 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001081}
1082
Nate Begemaned728c12006-03-27 01:32:24 +00001083/// visitSwitchCase - Emits the necessary code to represent a single node in
1084/// the binary search tree resulting from lowering a switch instruction.
1085void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001086 SDOperand Cond;
1087 SDOperand CondLHS = getValue(CB.CmpLHS);
1088
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001089 // Build the setcc now.
1090 if (CB.CmpMHS == NULL) {
1091 // Fold "(X == true)" to X and "(X == false)" to !X to
1092 // handle common cases produced by branch lowering.
1093 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1094 Cond = CondLHS;
1095 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1096 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1097 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1098 } else
1099 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1100 } else {
1101 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001102
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001103 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1104 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1105
1106 SDOperand CmpOp = getValue(CB.CmpMHS);
1107 MVT::ValueType VT = CmpOp.getValueType();
1108
1109 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1110 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1111 } else {
1112 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1113 Cond = DAG.getSetCC(MVT::i1, SUB,
1114 DAG.getConstant(High-Low, VT), ISD::SETULE);
1115 }
1116
1117 }
1118
Nate Begemaned728c12006-03-27 01:32:24 +00001119 // Set NextBlock to be the MBB immediately after the current one, if any.
1120 // This is used to avoid emitting unnecessary branches to the next block.
1121 MachineBasicBlock *NextBlock = 0;
1122 MachineFunction::iterator BBI = CurMBB;
1123 if (++BBI != CurMBB->getParent()->end())
1124 NextBlock = BBI;
1125
1126 // If the lhs block is the next block, invert the condition so that we can
1127 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001128 if (CB.TrueBB == NextBlock) {
1129 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001130 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1131 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1132 }
1133 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001134 DAG.getBasicBlock(CB.TrueBB));
1135 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001136 DAG.setRoot(BrCond);
1137 else
1138 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001139 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001140 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001141 CurMBB->addSuccessor(CB.TrueBB);
1142 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001143}
1144
Anton Korobeynikov70378262007-03-25 15:07:15 +00001145/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001146void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001147 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001148 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001149 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001150 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1151 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1152 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1153 Table, Index));
1154 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001155}
1156
Anton Korobeynikov70378262007-03-25 15:07:15 +00001157/// visitJumpTableHeader - This function emits necessary code to produce index
1158/// in the JumpTable from switch case.
1159void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1160 SelectionDAGISel::JumpTableHeader &JTH) {
1161 // Subtract the lowest switch case value from the value being switched on
1162 // and conditional branch to default mbb if the result is greater than the
1163 // difference between smallest and largest cases.
1164 SDOperand SwitchOp = getValue(JTH.SValue);
1165 MVT::ValueType VT = SwitchOp.getValueType();
1166 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1167 DAG.getConstant(JTH.First, VT));
1168
1169 // The SDNode we just created, which holds the value being switched on
1170 // minus the the smallest case value, needs to be copied to a virtual
1171 // register so it can be used as an index into the jump table in a
1172 // subsequent basic block. This value may be smaller or larger than the
1173 // target's pointer type, and therefore require extension or truncating.
Dan Gohmana8665142007-06-25 16:23:39 +00001174 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov70378262007-03-25 15:07:15 +00001175 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1176 else
1177 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1178
1179 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1180 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1181 JT.Reg = JumpTableReg;
1182
1183 // Emit the range check for the jump table, and branch to the default
1184 // block for the switch statement if the value being switched on exceeds
1185 // the largest case in the switch.
1186 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1187 DAG.getConstant(JTH.Last-JTH.First,VT),
1188 ISD::SETUGT);
1189
1190 // Set NextBlock to be the MBB immediately after the current one, if any.
1191 // This is used to avoid emitting unnecessary branches to the next block.
1192 MachineBasicBlock *NextBlock = 0;
1193 MachineFunction::iterator BBI = CurMBB;
1194 if (++BBI != CurMBB->getParent()->end())
1195 NextBlock = BBI;
1196
1197 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1198 DAG.getBasicBlock(JT.Default));
1199
1200 if (JT.MBB == NextBlock)
1201 DAG.setRoot(BrCond);
1202 else
1203 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001204 DAG.getBasicBlock(JT.MBB)));
1205
1206 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001207}
1208
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001209/// visitBitTestHeader - This function emits necessary code to produce value
1210/// suitable for "bit tests"
1211void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1212 // Subtract the minimum value
1213 SDOperand SwitchOp = getValue(B.SValue);
1214 MVT::ValueType VT = SwitchOp.getValueType();
1215 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1216 DAG.getConstant(B.First, VT));
1217
1218 // Check range
1219 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1220 DAG.getConstant(B.Range, VT),
1221 ISD::SETUGT);
1222
1223 SDOperand ShiftOp;
Dan Gohmana8665142007-06-25 16:23:39 +00001224 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001225 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1226 else
1227 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1228
1229 // Make desired shift
1230 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1231 DAG.getConstant(1, TLI.getPointerTy()),
1232 ShiftOp);
1233
1234 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1235 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1236 B.Reg = SwitchReg;
1237
1238 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1239 DAG.getBasicBlock(B.Default));
1240
1241 // Set NextBlock to be the MBB immediately after the current one, if any.
1242 // This is used to avoid emitting unnecessary branches to the next block.
1243 MachineBasicBlock *NextBlock = 0;
1244 MachineFunction::iterator BBI = CurMBB;
1245 if (++BBI != CurMBB->getParent()->end())
1246 NextBlock = BBI;
1247
1248 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1249 if (MBB == NextBlock)
1250 DAG.setRoot(BrRange);
1251 else
1252 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1253 DAG.getBasicBlock(MBB)));
1254
1255 CurMBB->addSuccessor(B.Default);
1256 CurMBB->addSuccessor(MBB);
1257
1258 return;
1259}
1260
1261/// visitBitTestCase - this function produces one "bit test"
1262void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1263 unsigned Reg,
1264 SelectionDAGISel::BitTestCase &B) {
1265 // Emit bit tests and jumps
1266 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1267
1268 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1269 SwitchVal,
1270 DAG.getConstant(B.Mask,
1271 TLI.getPointerTy()));
1272 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1273 DAG.getConstant(0, TLI.getPointerTy()),
1274 ISD::SETNE);
1275 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1276 AndCmp, DAG.getBasicBlock(B.TargetBB));
1277
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1283 NextBlock = BBI;
1284
1285 if (NextMBB == NextBlock)
1286 DAG.setRoot(BrAnd);
1287 else
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1289 DAG.getBasicBlock(NextMBB)));
1290
1291 CurMBB->addSuccessor(B.TargetBB);
1292 CurMBB->addSuccessor(NextMBB);
1293
1294 return;
1295}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001296
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001297void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1298 // Retrieve successors.
1299 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001300 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001301
Duncan Sands97f72362007-06-13 05:51:31 +00001302 LowerCallTo(I, I.getCalledValue()->getType(),
1303 I.getCallingConv(),
1304 false,
1305 getValue(I.getOperand(0)),
1306 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001307
Duncan Sands97f72362007-06-13 05:51:31 +00001308 // If the value of the invoke is used outside of its defining block, make it
1309 // available as a virtual register.
1310 if (!I.use_empty()) {
1311 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1312 if (VMI != FuncInfo.ValueMap.end())
1313 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey14059d92007-02-25 21:43:59 +00001314 }
Duncan Sands97f72362007-06-13 05:51:31 +00001315
1316 // Drop into normal successor.
1317 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1318 DAG.getBasicBlock(Return)));
1319
1320 // Update successor info
1321 CurMBB->addSuccessor(Return);
1322 CurMBB->addSuccessor(LandingPad);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001323}
1324
1325void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1326}
1327
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001328/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001329/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001330bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001331 CaseRecVector& WorkList,
1332 Value* SV,
1333 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001334 Case& BackCase = *(CR.Range.second-1);
1335
1336 // Size is the number of Cases represented by this range.
1337 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001338 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001339 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001340
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001341 // Get the MachineFunction which holds the current MBB. This is used when
1342 // inserting any additional MBBs necessary to represent the switch.
1343 MachineFunction *CurMF = CurMBB->getParent();
1344
1345 // Figure out which block is immediately after the current one.
1346 MachineBasicBlock *NextBlock = 0;
1347 MachineFunction::iterator BBI = CR.CaseBB;
1348
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001349 if (++BBI != CurMBB->getParent()->end())
1350 NextBlock = BBI;
1351
1352 // TODO: If any two of the cases has the same destination, and if one value
1353 // is the same as the other, but has one bit unset that the other has set,
1354 // use bit manipulation to do two compares at once. For example:
1355 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1356
1357 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001358 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001359 // The last case block won't fall through into 'NextBlock' if we emit the
1360 // branches in this order. See if rearranging a case value would help.
1361 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001362 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001363 std::swap(*I, BackCase);
1364 break;
1365 }
1366 }
1367 }
1368
1369 // Create a CaseBlock record representing a conditional branch to
1370 // the Case's target mbb if the value being switched on SV is equal
1371 // to C.
1372 MachineBasicBlock *CurBlock = CR.CaseBB;
1373 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1374 MachineBasicBlock *FallThrough;
1375 if (I != E-1) {
1376 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1377 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1378 } else {
1379 // If the last case doesn't match, go to the default block.
1380 FallThrough = Default;
1381 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001382
1383 Value *RHS, *LHS, *MHS;
1384 ISD::CondCode CC;
1385 if (I->High == I->Low) {
1386 // This is just small small case range :) containing exactly 1 case
1387 CC = ISD::SETEQ;
1388 LHS = SV; RHS = I->High; MHS = NULL;
1389 } else {
1390 CC = ISD::SETLE;
1391 LHS = I->Low; MHS = SV; RHS = I->High;
1392 }
1393 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1394 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001395
1396 // If emitting the first comparison, just call visitSwitchCase to emit the
1397 // code into the current block. Otherwise, push the CaseBlock onto the
1398 // vector to be later processed by SDISel, and insert the node's MBB
1399 // before the next MBB.
1400 if (CurBlock == CurMBB)
1401 visitSwitchCase(CB);
1402 else
1403 SwitchCases.push_back(CB);
1404
1405 CurBlock = FallThrough;
1406 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001407
1408 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001409}
1410
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001411static inline bool areJTsAllowed(const TargetLowering &TLI) {
1412 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1413 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1414}
1415
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001416/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001417bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001418 CaseRecVector& WorkList,
1419 Value* SV,
1420 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001421 Case& FrontCase = *CR.Range.first;
1422 Case& BackCase = *(CR.Range.second-1);
1423
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001424 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1425 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1426
1427 uint64_t TSize = 0;
1428 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1429 I!=E; ++I)
1430 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001431
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001432 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001433 return false;
1434
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001435 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1436 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001437 return false;
1438
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001439 DOUT << "Lowering jump table\n"
1440 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001441 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001442
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001443 // Get the MachineFunction which holds the current MBB. This is used when
1444 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001445 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001446
1447 // Figure out which block is immediately after the current one.
1448 MachineBasicBlock *NextBlock = 0;
1449 MachineFunction::iterator BBI = CR.CaseBB;
1450
1451 if (++BBI != CurMBB->getParent()->end())
1452 NextBlock = BBI;
1453
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001454 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1455
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001456 // Create a new basic block to hold the code for loading the address
1457 // of the jump table, and jumping to it. Update successor information;
1458 // we will either branch to the default case for the switch, or the jump
1459 // table.
1460 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1461 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1462 CR.CaseBB->addSuccessor(Default);
1463 CR.CaseBB->addSuccessor(JumpTableBB);
1464
1465 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001466 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001467 // a case statement, push the case's BB onto the vector, otherwise, push
1468 // the default BB.
1469 std::vector<MachineBasicBlock*> DestBBs;
1470 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001471 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1472 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1473 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1474
1475 if ((Low <= TEI) && (TEI <= High)) {
1476 DestBBs.push_back(I->BB);
1477 if (TEI==High)
1478 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001479 } else {
1480 DestBBs.push_back(Default);
1481 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001482 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001483
1484 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001485 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001486 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1487 E = DestBBs.end(); I != E; ++I) {
1488 if (!SuccsHandled[(*I)->getNumber()]) {
1489 SuccsHandled[(*I)->getNumber()] = true;
1490 JumpTableBB->addSuccessor(*I);
1491 }
1492 }
1493
1494 // Create a jump table index for this jump table, or return an existing
1495 // one.
1496 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1497
1498 // Set the jump table information so that we can codegen it as a second
1499 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001500 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001501 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1502 (CR.CaseBB == CurMBB));
1503 if (CR.CaseBB == CurMBB)
1504 visitJumpTableHeader(JT, JTH);
1505
1506 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001507
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001508 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001509}
1510
1511/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1512/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001513bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001514 CaseRecVector& WorkList,
1515 Value* SV,
1516 MachineBasicBlock* Default) {
1517 // Get the MachineFunction which holds the current MBB. This is used when
1518 // inserting any additional MBBs necessary to represent the switch.
1519 MachineFunction *CurMF = CurMBB->getParent();
1520
1521 // Figure out which block is immediately after the current one.
1522 MachineBasicBlock *NextBlock = 0;
1523 MachineFunction::iterator BBI = CR.CaseBB;
1524
1525 if (++BBI != CurMBB->getParent()->end())
1526 NextBlock = BBI;
1527
1528 Case& FrontCase = *CR.Range.first;
1529 Case& BackCase = *(CR.Range.second-1);
1530 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1531
1532 // Size is the number of Cases represented by this range.
1533 unsigned Size = CR.Range.second - CR.Range.first;
1534
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001535 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1536 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001537 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001538 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001539
1540 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1541 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001542 uint64_t TSize = 0;
1543 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1544 I!=E; ++I)
1545 TSize += I->size();
1546
1547 uint64_t LSize = FrontCase.size();
1548 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001549 DOUT << "Selecting best pivot: \n"
1550 << "First: " << First << ", Last: " << Last <<"\n"
1551 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001552 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001553 J!=E; ++I, ++J) {
1554 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1555 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001556 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001557 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1558 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001559 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001560 // Should always split in some non-trivial place
1561 DOUT <<"=>Step\n"
1562 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1563 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1564 << "Metric: " << Metric << "\n";
1565 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001566 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001567 FMetric = Metric;
1568 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001569 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001570
1571 LSize += J->size();
1572 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001573 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001574 if (areJTsAllowed(TLI)) {
1575 // If our case is dense we *really* should handle it earlier!
1576 assert((FMetric > 0) && "Should handle dense range earlier!");
1577 } else {
1578 Pivot = CR.Range.first + Size/2;
1579 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001580
1581 CaseRange LHSR(CR.Range.first, Pivot);
1582 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001583 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001584 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1585
1586 // We know that we branch to the LHS if the Value being switched on is
1587 // less than the Pivot value, C. We use this to optimize our binary
1588 // tree a bit, by recognizing that if SV is greater than or equal to the
1589 // LHS's Case Value, and that Case Value is exactly one less than the
1590 // Pivot's Value, then we can branch directly to the LHS's Target,
1591 // rather than creating a leaf node for it.
1592 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001593 LHSR.first->High == CR.GE &&
1594 cast<ConstantInt>(C)->getSExtValue() ==
1595 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1596 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001597 } else {
1598 TrueBB = new MachineBasicBlock(LLVMBB);
1599 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1600 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1601 }
1602
1603 // Similar to the optimization above, if the Value being switched on is
1604 // known to be less than the Constant CR.LT, and the current Case Value
1605 // is CR.LT - 1, then we can branch directly to the target block for
1606 // the current Case Value, rather than emitting a RHS leaf node for it.
1607 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001608 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1609 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1610 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001611 } else {
1612 FalseBB = new MachineBasicBlock(LLVMBB);
1613 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1614 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1615 }
1616
1617 // Create a CaseBlock record representing a conditional branch to
1618 // the LHS node if the value being switched on SV is less than C.
1619 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001620 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1621 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001622
1623 if (CR.CaseBB == CurMBB)
1624 visitSwitchCase(CB);
1625 else
1626 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001627
1628 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001629}
1630
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001631/// handleBitTestsSwitchCase - if current case range has few destination and
1632/// range span less, than machine word bitwidth, encode case range into series
1633/// of masks and emit bit tests with these masks.
1634bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1635 CaseRecVector& WorkList,
1636 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001637 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001638 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001639
1640 Case& FrontCase = *CR.Range.first;
1641 Case& BackCase = *(CR.Range.second-1);
1642
1643 // Get the MachineFunction which holds the current MBB. This is used when
1644 // inserting any additional MBBs necessary to represent the switch.
1645 MachineFunction *CurMF = CurMBB->getParent();
1646
1647 unsigned numCmps = 0;
1648 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1649 I!=E; ++I) {
1650 // Single case counts one, case range - two.
1651 if (I->Low == I->High)
1652 numCmps +=1;
1653 else
1654 numCmps +=2;
1655 }
1656
1657 // Count unique destinations
1658 SmallSet<MachineBasicBlock*, 4> Dests;
1659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1660 Dests.insert(I->BB);
1661 if (Dests.size() > 3)
1662 // Don't bother the code below, if there are too much unique destinations
1663 return false;
1664 }
1665 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1666 << "Total number of comparisons: " << numCmps << "\n";
1667
1668 // Compute span of values.
1669 Constant* minValue = FrontCase.Low;
1670 Constant* maxValue = BackCase.High;
1671 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1672 cast<ConstantInt>(minValue)->getSExtValue();
1673 DOUT << "Compare range: " << range << "\n"
1674 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1675 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1676
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001677 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001678 (!(Dests.size() == 1 && numCmps >= 3) &&
1679 !(Dests.size() == 2 && numCmps >= 5) &&
1680 !(Dests.size() >= 3 && numCmps >= 6)))
1681 return false;
1682
1683 DOUT << "Emitting bit tests\n";
1684 int64_t lowBound = 0;
1685
1686 // Optimize the case where all the case values fit in a
1687 // word without having to subtract minValue. In this case,
1688 // we can optimize away the subtraction.
1689 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001690 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001691 range = cast<ConstantInt>(maxValue)->getSExtValue();
1692 } else {
1693 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1694 }
1695
1696 CaseBitsVector CasesBits;
1697 unsigned i, count = 0;
1698
1699 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1700 MachineBasicBlock* Dest = I->BB;
1701 for (i = 0; i < count; ++i)
1702 if (Dest == CasesBits[i].BB)
1703 break;
1704
1705 if (i == count) {
1706 assert((count < 3) && "Too much destinations to test!");
1707 CasesBits.push_back(CaseBits(0, Dest, 0));
1708 count++;
1709 }
1710
1711 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1712 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1713
1714 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001715 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001716 CasesBits[i].Bits++;
1717 }
1718
1719 }
1720 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1721
1722 SelectionDAGISel::BitTestInfo BTC;
1723
1724 // Figure out which block is immediately after the current one.
1725 MachineFunction::iterator BBI = CR.CaseBB;
1726 ++BBI;
1727
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1729
1730 DOUT << "Cases:\n";
1731 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1732 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1733 << ", BB: " << CasesBits[i].BB << "\n";
1734
1735 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1736 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1737 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1738 CaseBB,
1739 CasesBits[i].BB));
1740 }
1741
1742 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001743 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001744 CR.CaseBB, Default, BTC);
1745
1746 if (CR.CaseBB == CurMBB)
1747 visitBitTestHeader(BTB);
1748
1749 BitTestCases.push_back(BTB);
1750
1751 return true;
1752}
1753
1754
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001755// Clusterify - Transform simple list of Cases into list of CaseRange's
1756unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1757 const SwitchInst& SI) {
1758 unsigned numCmps = 0;
1759
1760 // Start with "simple" cases
1761 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1762 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1763 Cases.push_back(Case(SI.getSuccessorValue(i),
1764 SI.getSuccessorValue(i),
1765 SMBB));
1766 }
1767 sort(Cases.begin(), Cases.end(), CaseCmp());
1768
1769 // Merge case into clusters
1770 if (Cases.size()>=2)
1771 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1772 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1773 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1774 MachineBasicBlock* nextBB = J->BB;
1775 MachineBasicBlock* currentBB = I->BB;
1776
1777 // If the two neighboring cases go to the same destination, merge them
1778 // into a single case.
1779 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1780 I->High = J->High;
1781 J = Cases.erase(J);
1782 } else {
1783 I = J++;
1784 }
1785 }
1786
1787 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1788 if (I->Low != I->High)
1789 // A range counts double, since it requires two compares.
1790 ++numCmps;
1791 }
1792
1793 return numCmps;
1794}
1795
1796void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001797 // Figure out which block is immediately after the current one.
1798 MachineBasicBlock *NextBlock = 0;
1799 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001800
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001801 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001802
Nate Begemaned728c12006-03-27 01:32:24 +00001803 // If there is only the default destination, branch to it if it is not the
1804 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001805 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001806 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001807
Nate Begemaned728c12006-03-27 01:32:24 +00001808 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001809 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001810 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001811 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001812
Chris Lattner6d6fc262006-10-22 21:36:53 +00001813 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001814 return;
1815 }
1816
1817 // If there are any non-default case statements, create a vector of Cases
1818 // representing each one, and sort the vector so that we can efficiently
1819 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001820 CaseVector Cases;
1821 unsigned numCmps = Clusterify(Cases, SI);
1822 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1823 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001824
Nate Begemaned728c12006-03-27 01:32:24 +00001825 // Get the Value to be switched on and default basic blocks, which will be
1826 // inserted into CaseBlock records, representing basic blocks in the binary
1827 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001828 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001829
Nate Begemaned728c12006-03-27 01:32:24 +00001830 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001831 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001832 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1833
1834 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001835 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001836 CaseRec CR = WorkList.back();
1837 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001838
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001839 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1840 continue;
1841
Anton Korobeynikov70378262007-03-25 15:07:15 +00001842 // If the range has few cases (two or less) emit a series of specific
1843 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001844 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1845 continue;
1846
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001847 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001848 // target supports indirect branches, then emit a jump table rather than
1849 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001850 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1851 continue;
1852
1853 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1854 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1855 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001856 }
1857}
1858
Anton Korobeynikov70378262007-03-25 15:07:15 +00001859
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001860void SelectionDAGLowering::visitSub(User &I) {
1861 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001862 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001863 if (isa<VectorType>(Ty)) {
Dan Gohmana8665142007-06-25 16:23:39 +00001864 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1865 const VectorType *DestTy = cast<VectorType>(I.getType());
1866 const Type *ElTy = DestTy->getElementType();
1867 unsigned VL = DestTy->getNumElements();
1868 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
1869 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
1870 if (CV == CNZ) {
1871 SDOperand Op2 = getValue(I.getOperand(1));
1872 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1873 return;
1874 }
1875 }
1876 }
1877 if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001878 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1879 if (CFP->isExactlyValue(-0.0)) {
1880 SDOperand Op2 = getValue(I.getOperand(1));
1881 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1882 return;
1883 }
Dan Gohmana8665142007-06-25 16:23:39 +00001884 }
1885
1886 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001887}
1888
Dan Gohmana8665142007-06-25 16:23:39 +00001889void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001890 SDOperand Op1 = getValue(I.getOperand(0));
1891 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001892
1893 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001894}
1895
Nate Begeman127321b2005-11-18 07:42:56 +00001896void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1897 SDOperand Op1 = getValue(I.getOperand(0));
1898 SDOperand Op2 = getValue(I.getOperand(1));
1899
Dan Gohmana8665142007-06-25 16:23:39 +00001900 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
1901 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer2341c222007-02-02 02:16:23 +00001902 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1903 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1904 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001905
Chris Lattner7a60d912005-01-07 07:47:53 +00001906 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1907}
1908
Reid Spencerd9436b62006-11-20 01:22:35 +00001909void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001910 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1911 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1912 predicate = IC->getPredicate();
1913 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1914 predicate = ICmpInst::Predicate(IC->getPredicate());
1915 SDOperand Op1 = getValue(I.getOperand(0));
1916 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001917 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001918 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001919 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1920 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1921 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1922 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1923 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1924 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1925 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1926 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1927 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1928 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1929 default:
1930 assert(!"Invalid ICmp predicate value");
1931 Opcode = ISD::SETEQ;
1932 break;
1933 }
1934 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1935}
1936
1937void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001938 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1939 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1940 predicate = FC->getPredicate();
1941 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1942 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001943 SDOperand Op1 = getValue(I.getOperand(0));
1944 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001945 ISD::CondCode Condition, FOC, FPC;
1946 switch (predicate) {
1947 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1948 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1949 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1950 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1951 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1952 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1953 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1954 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1955 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1956 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1957 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1958 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1959 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1960 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1961 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1962 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1963 default:
1964 assert(!"Invalid FCmp predicate value");
1965 FOC = FPC = ISD::SETFALSE;
1966 break;
1967 }
1968 if (FiniteOnlyFPMath())
1969 Condition = FOC;
1970 else
1971 Condition = FPC;
1972 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001973}
1974
1975void SelectionDAGLowering::visitSelect(User &I) {
1976 SDOperand Cond = getValue(I.getOperand(0));
1977 SDOperand TrueVal = getValue(I.getOperand(1));
1978 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohmana8665142007-06-25 16:23:39 +00001979 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1980 TrueVal, FalseVal));
Chris Lattner7a60d912005-01-07 07:47:53 +00001981}
1982
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001983
1984void SelectionDAGLowering::visitTrunc(User &I) {
1985 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1986 SDOperand N = getValue(I.getOperand(0));
1987 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1988 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1989}
1990
1991void SelectionDAGLowering::visitZExt(User &I) {
1992 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1993 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1994 SDOperand N = getValue(I.getOperand(0));
1995 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1996 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1997}
1998
1999void SelectionDAGLowering::visitSExt(User &I) {
2000 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2001 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2002 SDOperand N = getValue(I.getOperand(0));
2003 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2004 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2005}
2006
2007void SelectionDAGLowering::visitFPTrunc(User &I) {
2008 // FPTrunc is never a no-op cast, no need to check
2009 SDOperand N = getValue(I.getOperand(0));
2010 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2011 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2012}
2013
2014void SelectionDAGLowering::visitFPExt(User &I){
2015 // FPTrunc is never a no-op cast, no need to check
2016 SDOperand N = getValue(I.getOperand(0));
2017 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2018 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2019}
2020
2021void SelectionDAGLowering::visitFPToUI(User &I) {
2022 // FPToUI is never a no-op cast, no need to check
2023 SDOperand N = getValue(I.getOperand(0));
2024 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2025 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2026}
2027
2028void SelectionDAGLowering::visitFPToSI(User &I) {
2029 // FPToSI is never a no-op cast, no need to check
2030 SDOperand N = getValue(I.getOperand(0));
2031 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2032 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2033}
2034
2035void SelectionDAGLowering::visitUIToFP(User &I) {
2036 // UIToFP is never a no-op cast, no need to check
2037 SDOperand N = getValue(I.getOperand(0));
2038 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2039 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2040}
2041
2042void SelectionDAGLowering::visitSIToFP(User &I){
2043 // UIToFP is never a no-op cast, no need to check
2044 SDOperand N = getValue(I.getOperand(0));
2045 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2046 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2047}
2048
2049void SelectionDAGLowering::visitPtrToInt(User &I) {
2050 // What to do depends on the size of the integer and the size of the pointer.
2051 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002052 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002053 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002054 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002055 SDOperand Result;
2056 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2057 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2058 else
2059 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2060 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2061 setValue(&I, Result);
2062}
Chris Lattner7a60d912005-01-07 07:47:53 +00002063
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002064void SelectionDAGLowering::visitIntToPtr(User &I) {
2065 // What to do depends on the size of the integer and the size of the pointer.
2066 // We can either truncate, zero extend, or no-op, accordingly.
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType SrcVT = N.getValueType();
2069 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2070 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2071 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2072 else
2073 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2074 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2075}
2076
2077void SelectionDAGLowering::visitBitCast(User &I) {
2078 SDOperand N = getValue(I.getOperand(0));
2079 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002080
2081 // BitCast assures us that source and destination are the same size so this
2082 // is either a BIT_CONVERT or a no-op.
2083 if (DestVT != N.getValueType())
2084 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2085 else
2086 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002087}
2088
Chris Lattner67271862006-03-29 00:11:43 +00002089void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002090 SDOperand InVec = getValue(I.getOperand(0));
2091 SDOperand InVal = getValue(I.getOperand(1));
2092 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2093 getValue(I.getOperand(2)));
2094
Dan Gohmana8665142007-06-25 16:23:39 +00002095 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2096 TLI.getValueType(I.getType()),
2097 InVec, InVal, InIdx));
Chris Lattner32206f52006-03-18 01:44:44 +00002098}
2099
Chris Lattner67271862006-03-29 00:11:43 +00002100void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002101 SDOperand InVec = getValue(I.getOperand(0));
2102 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2103 getValue(I.getOperand(1)));
Dan Gohmana8665142007-06-25 16:23:39 +00002104 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002105 TLI.getValueType(I.getType()), InVec, InIdx));
2106}
Chris Lattner32206f52006-03-18 01:44:44 +00002107
Chris Lattner098c01e2006-04-08 04:15:24 +00002108void SelectionDAGLowering::visitShuffleVector(User &I) {
2109 SDOperand V1 = getValue(I.getOperand(0));
2110 SDOperand V2 = getValue(I.getOperand(1));
2111 SDOperand Mask = getValue(I.getOperand(2));
2112
Dan Gohmana8665142007-06-25 16:23:39 +00002113 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2114 TLI.getValueType(I.getType()),
2115 V1, V2, Mask));
Chris Lattner098c01e2006-04-08 04:15:24 +00002116}
2117
2118
Chris Lattner7a60d912005-01-07 07:47:53 +00002119void SelectionDAGLowering::visitGetElementPtr(User &I) {
2120 SDOperand N = getValue(I.getOperand(0));
2121 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002122
2123 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2124 OI != E; ++OI) {
2125 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002126 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002127 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002128 if (Field) {
2129 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002130 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002131 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002132 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002133 }
2134 Ty = StTy->getElementType(Field);
2135 } else {
2136 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002137
Chris Lattner43535a12005-11-09 04:45:33 +00002138 // If this is a constant subscript, handle it quickly.
2139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002140 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002141 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002142 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002143 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2144 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002145 }
Chris Lattner43535a12005-11-09 04:45:33 +00002146
2147 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002148 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002149 SDOperand IdxN = getValue(Idx);
2150
2151 // If the index is smaller or larger than intptr_t, truncate or extend
2152 // it.
2153 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002154 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002155 } else if (IdxN.getValueType() > N.getValueType())
2156 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2157
2158 // If this is a multiply by a power of two, turn it into a shl
2159 // immediately. This is a very common case.
2160 if (isPowerOf2_64(ElementSize)) {
2161 unsigned Amt = Log2_64(ElementSize);
2162 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002163 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002164 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2165 continue;
2166 }
2167
2168 SDOperand Scale = getIntPtrConstant(ElementSize);
2169 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2170 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002171 }
2172 }
2173 setValue(&I, N);
2174}
2175
2176void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2177 // If this is a fixed sized alloca in the entry block of the function,
2178 // allocate it statically on the stack.
2179 if (FuncInfo.StaticAllocaMap.count(&I))
2180 return; // getValue will auto-populate this.
2181
2182 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002183 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002184 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002185 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002186 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002187
2188 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002189 MVT::ValueType IntPtr = TLI.getPointerTy();
2190 if (IntPtr < AllocSize.getValueType())
2191 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2192 else if (IntPtr > AllocSize.getValueType())
2193 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002194
Chris Lattnereccb73d2005-01-22 23:04:37 +00002195 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002196 getIntPtrConstant(TySize));
2197
2198 // Handle alignment. If the requested alignment is less than or equal to the
2199 // stack alignment, ignore it and round the size of the allocation up to the
2200 // stack alignment size. If the size is greater than the stack alignment, we
2201 // note this in the DYNAMIC_STACKALLOC node.
2202 unsigned StackAlign =
2203 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2204 if (Align <= StackAlign) {
2205 Align = 0;
2206 // Add SA-1 to the size.
2207 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2208 getIntPtrConstant(StackAlign-1));
2209 // Mask out the low bits for alignment purposes.
2210 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2211 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2212 }
2213
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002214 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002215 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2216 MVT::Other);
2217 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002218 setValue(&I, DSA);
2219 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002220
2221 // Inform the Frame Information that we have just allocated a variable-sized
2222 // object.
2223 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2224}
2225
Chris Lattner7a60d912005-01-07 07:47:53 +00002226void SelectionDAGLowering::visitLoad(LoadInst &I) {
2227 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002228
Chris Lattner4d9651c2005-01-17 22:19:26 +00002229 SDOperand Root;
2230 if (I.isVolatile())
2231 Root = getRoot();
2232 else {
2233 // Do not serialize non-volatile loads against each other.
2234 Root = DAG.getRoot();
2235 }
Chris Lattner4024c002006-03-15 22:19:46 +00002236
Evan Chenge71fe34d2006-10-09 20:57:25 +00002237 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002238 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002239}
2240
2241SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002242 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002243 bool isVolatile,
2244 unsigned Alignment) {
Dan Gohmana8665142007-06-25 16:23:39 +00002245 SDOperand L =
2246 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2247 isVolatile, Alignment);
Chris Lattner4d9651c2005-01-17 22:19:26 +00002248
Chris Lattner4024c002006-03-15 22:19:46 +00002249 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002250 DAG.setRoot(L.getValue(1));
2251 else
2252 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002253
2254 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002255}
2256
2257
2258void SelectionDAGLowering::visitStore(StoreInst &I) {
2259 Value *SrcV = I.getOperand(0);
2260 SDOperand Src = getValue(SrcV);
2261 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002262 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002263 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002264}
2265
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002266/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2267/// access memory and has no other side effects at all.
2268static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2269#define GET_NO_MEMORY_INTRINSICS
2270#include "llvm/Intrinsics.gen"
2271#undef GET_NO_MEMORY_INTRINSICS
2272 return false;
2273}
2274
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002275// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2276// have any side-effects or if it only reads memory.
2277static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2278#define GET_SIDE_EFFECT_INFO
2279#include "llvm/Intrinsics.gen"
2280#undef GET_SIDE_EFFECT_INFO
2281 return false;
2282}
2283
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002284/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2285/// node.
2286void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2287 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002288 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002289 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002290
2291 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002292 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002293 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2294 if (OnlyLoad) {
2295 // We don't need to serialize loads against other loads.
2296 Ops.push_back(DAG.getRoot());
2297 } else {
2298 Ops.push_back(getRoot());
2299 }
2300 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002301
2302 // Add the intrinsic ID as an integer operand.
2303 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2304
2305 // Add all operands of the call to the operand list.
2306 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2307 SDOperand Op = getValue(I.getOperand(i));
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002308 assert(TLI.isTypeLegal(Op.getValueType()) &&
2309 "Intrinsic uses a non-legal type?");
2310 Ops.push_back(Op);
2311 }
2312
2313 std::vector<MVT::ValueType> VTs;
2314 if (I.getType() != Type::VoidTy) {
2315 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00002316 if (MVT::isVector(VT)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002317 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002318 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2319
2320 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2321 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2322 }
2323
2324 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2325 VTs.push_back(VT);
2326 }
2327 if (HasChain)
2328 VTs.push_back(MVT::Other);
2329
Chris Lattnerbd887772006-08-14 23:53:35 +00002330 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2331
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002332 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002333 SDOperand Result;
2334 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002335 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2336 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002337 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002338 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2339 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002340 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002341 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2342 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002343
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002344 if (HasChain) {
2345 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2346 if (OnlyLoad)
2347 PendingLoads.push_back(Chain);
2348 else
2349 DAG.setRoot(Chain);
2350 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002351 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002352 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohmana8665142007-06-25 16:23:39 +00002353 MVT::ValueType VT = TLI.getValueType(PTy);
2354 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002355 }
2356 setValue(&I, Result);
2357 }
2358}
2359
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002360/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2361/// (possibly constant folded), return it. Otherwise return NULL.
2362static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2363 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2364 return GV;
2365 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2366 if (CE->getOpcode() == Instruction::BitCast)
2367 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2368 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2369 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2370 if (!CE->getOperand(i)->isNullValue())
2371 return NULL;
2372 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2373 }
2374 }
2375 return NULL;
2376}
2377
Duncan Sands92bf2c62007-06-15 19:04:19 +00002378/// addCatchInfo - Extract the personality and type infos from an eh.selector
2379/// or eh.filter call, and add them to the specified machine basic block.
2380static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2381 MachineBasicBlock *MBB) {
2382 // Inform the MachineModuleInfo of the personality for this landing pad.
2383 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2384 assert(CE->getOpcode() == Instruction::BitCast &&
2385 isa<Function>(CE->getOperand(0)) &&
2386 "Personality should be a function");
2387 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2388
2389 // Gather all the type infos for this landing pad and pass them along to
2390 // MachineModuleInfo.
2391 std::vector<GlobalVariable *> TyInfo;
2392 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2393 Constant *C = cast<Constant>(I.getOperand(i));
2394 GlobalVariable *GV = ExtractGlobalVariable(C);
2395 assert (GV || isa<ConstantPointerNull>(C) &&
2396 "TypeInfo must be a global variable or NULL");
2397 TyInfo.push_back(GV);
2398 }
2399 if (I.getCalledFunction()->getIntrinsicID() == Intrinsic::eh_filter)
2400 MMI->addFilterTypeInfo(MBB, TyInfo);
2401 else
2402 MMI->addCatchTypeInfo(MBB, TyInfo);
2403}
2404
Evan Cheng77f541d2007-06-27 18:45:32 +00002405/// propagateEHRegister - The specified EH register is required in a successor
2406/// of the EH landing pad. Propagate it (by adding it to livein) to all the
2407/// blocks in the paths between the landing pad and the specified block.
2408static void propagateEHRegister(MachineBasicBlock *MBB, unsigned EHReg,
2409 SmallPtrSet<MachineBasicBlock*, 8> Visited) {
2410 if (MBB->isLandingPad() || !Visited.insert(MBB))
2411 return;
2412
2413 MBB->addLiveIn(EHReg);
2414 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
2415 E = MBB->pred_end(); PI != E; ++PI)
2416 propagateEHRegister(*PI, EHReg, Visited);
2417}
2418
2419static void propagateEHRegister(MachineBasicBlock *MBB, unsigned EHReg) {
2420 SmallPtrSet<MachineBasicBlock*, 8> Visited;
2421 propagateEHRegister(MBB, EHReg, Visited);
2422}
2423
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002424/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2425/// we want to emit this as a call to a named external function, return the name
2426/// otherwise lower it and return null.
2427const char *
2428SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2429 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002430 default:
2431 // By default, turn this into a target intrinsic node.
2432 visitTargetIntrinsic(I, Intrinsic);
2433 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002434 case Intrinsic::vastart: visitVAStart(I); return 0;
2435 case Intrinsic::vaend: visitVAEnd(I); return 0;
2436 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002437 case Intrinsic::returnaddress:
2438 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2439 getValue(I.getOperand(1))));
2440 return 0;
2441 case Intrinsic::frameaddress:
2442 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2443 getValue(I.getOperand(1))));
2444 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002445 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002446 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002447 break;
2448 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002449 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002450 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002451 case Intrinsic::memcpy_i32:
2452 case Intrinsic::memcpy_i64:
2453 visitMemIntrinsic(I, ISD::MEMCPY);
2454 return 0;
2455 case Intrinsic::memset_i32:
2456 case Intrinsic::memset_i64:
2457 visitMemIntrinsic(I, ISD::MEMSET);
2458 return 0;
2459 case Intrinsic::memmove_i32:
2460 case Intrinsic::memmove_i64:
2461 visitMemIntrinsic(I, ISD::MEMMOVE);
2462 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002463
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002464 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002465 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002466 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002467 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002468 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002469
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002470 Ops[0] = getRoot();
2471 Ops[1] = getValue(SPI.getLineValue());
2472 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002473
Jim Laskeyc56315c2007-01-26 21:22:28 +00002474 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002475 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002476 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2477
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002478 Ops[3] = DAG.getString(CompileUnit->getFileName());
2479 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002480
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002481 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002482 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002483
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002484 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002485 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002486 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002487 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002488 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002489 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2490 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002491 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002492 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002493 }
2494
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002495 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002496 }
2497 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002498 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002499 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002500 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2501 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002502 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002503 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002504 }
2505
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002506 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002507 }
2508 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002509 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002510 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002511 if (MMI && FSI.getSubprogram() &&
2512 MMI->Verify(FSI.getSubprogram())) {
2513 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002514 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002515 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002516 }
2517
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002518 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002519 }
2520 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002521 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002522 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002523 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002524 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002525 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002526 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002527 }
2528
2529 return 0;
2530 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002531
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002532 case Intrinsic::eh_exception: {
Evan Cheng77f541d2007-06-27 18:45:32 +00002533 if (ExceptionHandling) {
2534 if (!CurMBB->isLandingPad() && TLI.getExceptionAddressRegister())
2535 propagateEHRegister(CurMBB, TLI.getExceptionAddressRegister());
Duncan Sands61166502007-06-06 10:05:18 +00002536
Jim Laskey504e9942007-02-22 15:38:06 +00002537 // Insert the EXCEPTIONADDR instruction.
2538 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2539 SDOperand Ops[1];
2540 Ops[0] = DAG.getRoot();
2541 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2542 setValue(&I, Op);
2543 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002544 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002545 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002546 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002547 return 0;
2548 }
2549
Jim Laskeyd5453d72007-03-01 20:24:30 +00002550 case Intrinsic::eh_selector:
2551 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002552 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002553
Duncan Sands92bf2c62007-06-15 19:04:19 +00002554 if (ExceptionHandling && MMI) {
2555 if (CurMBB->isLandingPad())
2556 addCatchInfo(I, MMI, CurMBB);
Evan Cheng77f541d2007-06-27 18:45:32 +00002557 else {
Duncan Sands92bf2c62007-06-15 19:04:19 +00002558#ifndef NDEBUG
Duncan Sands92bf2c62007-06-15 19:04:19 +00002559 FuncInfo.CatchInfoLost.insert(&I);
2560#endif
Evan Cheng77f541d2007-06-27 18:45:32 +00002561 if (TLI.getExceptionSelectorRegister())
2562 propagateEHRegister(CurMBB, TLI.getExceptionSelectorRegister());
2563 }
Jim Laskey504e9942007-02-22 15:38:06 +00002564
2565 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002566 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002567 SDOperand Ops[2];
2568 Ops[0] = getValue(I.getOperand(1));
2569 Ops[1] = getRoot();
2570 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2571 setValue(&I, Op);
2572 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002573 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002574 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002575 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002576
2577 return 0;
2578 }
2579
2580 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002581 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002582
Jim Laskey504e9942007-02-22 15:38:06 +00002583 if (MMI) {
2584 // Find the type id for the given typeinfo.
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002585 Constant *C = cast<Constant>(I.getOperand(1));
2586 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002587 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002588 "TypeInfo must be a global variable or NULL");
2589
Jim Laskey504e9942007-02-22 15:38:06 +00002590 unsigned TypeID = MMI->getTypeIDFor(GV);
2591 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002592 } else {
2593 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002594 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002595
2596 return 0;
2597 }
2598
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002599 case Intrinsic::sqrt_f32:
2600 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002601 setValue(&I, DAG.getNode(ISD::FSQRT,
2602 getValue(I.getOperand(1)).getValueType(),
2603 getValue(I.getOperand(1))));
2604 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002605 case Intrinsic::powi_f32:
2606 case Intrinsic::powi_f64:
2607 setValue(&I, DAG.getNode(ISD::FPOWI,
2608 getValue(I.getOperand(1)).getValueType(),
2609 getValue(I.getOperand(1)),
2610 getValue(I.getOperand(2))));
2611 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002612 case Intrinsic::pcmarker: {
2613 SDOperand Tmp = getValue(I.getOperand(1));
2614 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2615 return 0;
2616 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002617 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002618 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002619 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2620 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2621 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002622 setValue(&I, Tmp);
2623 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002624 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002625 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002626 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002627 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002628 assert(0 && "part_select intrinsic not implemented");
2629 abort();
2630 }
2631 case Intrinsic::part_set: {
2632 // Currently not implemented: just abort
2633 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002634 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002635 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002636 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002637 setValue(&I, DAG.getNode(ISD::BSWAP,
2638 getValue(I.getOperand(1)).getValueType(),
2639 getValue(I.getOperand(1))));
2640 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002641 case Intrinsic::cttz: {
2642 SDOperand Arg = getValue(I.getOperand(1));
2643 MVT::ValueType Ty = Arg.getValueType();
2644 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2645 if (Ty < MVT::i32)
2646 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2647 else if (Ty > MVT::i32)
2648 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2649 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002650 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002651 }
2652 case Intrinsic::ctlz: {
2653 SDOperand Arg = getValue(I.getOperand(1));
2654 MVT::ValueType Ty = Arg.getValueType();
2655 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2656 if (Ty < MVT::i32)
2657 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2658 else if (Ty > MVT::i32)
2659 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2660 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002661 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002662 }
2663 case Intrinsic::ctpop: {
2664 SDOperand Arg = getValue(I.getOperand(1));
2665 MVT::ValueType Ty = Arg.getValueType();
2666 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2667 if (Ty < MVT::i32)
2668 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2669 else if (Ty > MVT::i32)
2670 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2671 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002672 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002673 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002674 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002675 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002676 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2677 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002678 setValue(&I, Tmp);
2679 DAG.setRoot(Tmp.getValue(1));
2680 return 0;
2681 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002682 case Intrinsic::stackrestore: {
2683 SDOperand Tmp = getValue(I.getOperand(1));
2684 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002685 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002686 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002687 case Intrinsic::prefetch:
2688 // FIXME: Currently discarding prefetches.
2689 return 0;
Tanya Lattnere199f972007-06-15 22:26:58 +00002690
2691 case Intrinsic::var_annotation:
2692 // Discard annotate attributes
2693 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002694 }
2695}
2696
2697
Jim Laskey31fef782007-02-23 21:45:01 +00002698void SelectionDAGLowering::LowerCallTo(Instruction &I,
2699 const Type *CalledValueTy,
2700 unsigned CallingConv,
2701 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002702 SDOperand Callee, unsigned OpIdx,
2703 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002704 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002705 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002706 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002707 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2708 unsigned BeginLabel = 0, EndLabel = 0;
2709
Jim Laskey504e9942007-02-22 15:38:06 +00002710 TargetLowering::ArgListTy Args;
2711 TargetLowering::ArgListEntry Entry;
2712 Args.reserve(I.getNumOperands());
2713 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2714 Value *Arg = I.getOperand(i);
2715 SDOperand ArgNode = getValue(Arg);
2716 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands671e8c42007-05-07 20:49:28 +00002717
2718 unsigned attrInd = i - OpIdx + 1;
2719 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2720 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2721 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2722 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002723 Args.push_back(Entry);
2724 }
2725
Duncan Sands61166502007-06-06 10:05:18 +00002726 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002727 // Insert a label before the invoke call to mark the try range. This can be
2728 // used to detect deletion of the invoke via the MachineModuleInfo.
2729 BeginLabel = MMI->NextLabelID();
2730 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2731 DAG.getConstant(BeginLabel, MVT::i32)));
2732 }
2733
Jim Laskey504e9942007-02-22 15:38:06 +00002734 std::pair<SDOperand,SDOperand> Result =
2735 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002736 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002737 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002738 Callee, Args, DAG);
2739 if (I.getType() != Type::VoidTy)
2740 setValue(&I, Result.first);
2741 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002742
Duncan Sands61166502007-06-06 10:05:18 +00002743 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002744 // Insert a label at the end of the invoke call to mark the try range. This
2745 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2746 EndLabel = MMI->NextLabelID();
2747 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2748 DAG.getConstant(EndLabel, MVT::i32)));
2749
2750 // Inform MachineModuleInfo of range.
2751 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2752 }
Jim Laskey504e9942007-02-22 15:38:06 +00002753}
2754
2755
Chris Lattner7a60d912005-01-07 07:47:53 +00002756void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002757 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002758 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002759 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002760 if (unsigned IID = F->getIntrinsicID()) {
2761 RenameFn = visitIntrinsicCall(I, IID);
2762 if (!RenameFn)
2763 return;
2764 } else { // Not an LLVM intrinsic.
2765 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002766 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2767 if (I.getNumOperands() == 3 && // Basic sanity checks.
2768 I.getOperand(1)->getType()->isFloatingPoint() &&
2769 I.getType() == I.getOperand(1)->getType() &&
2770 I.getType() == I.getOperand(2)->getType()) {
2771 SDOperand LHS = getValue(I.getOperand(1));
2772 SDOperand RHS = getValue(I.getOperand(2));
2773 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2774 LHS, RHS));
2775 return;
2776 }
2777 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002778 if (I.getNumOperands() == 2 && // Basic sanity checks.
2779 I.getOperand(1)->getType()->isFloatingPoint() &&
2780 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002781 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002782 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2783 return;
2784 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002785 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002786 if (I.getNumOperands() == 2 && // Basic sanity checks.
2787 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002788 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002789 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002790 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2791 return;
2792 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002793 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002794 if (I.getNumOperands() == 2 && // Basic sanity checks.
2795 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002796 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002797 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002798 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2799 return;
2800 }
2801 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002802 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002803 } else if (isa<InlineAsm>(I.getOperand(0))) {
2804 visitInlineAsm(I);
2805 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002806 }
Misha Brukman835702a2005-04-21 22:36:52 +00002807
Chris Lattner18d2b342005-01-08 22:48:57 +00002808 SDOperand Callee;
2809 if (!RenameFn)
2810 Callee = getValue(I.getOperand(0));
2811 else
2812 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002813
Jim Laskey31fef782007-02-23 21:45:01 +00002814 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002815 I.getCallingConv(),
2816 I.isTailCall(),
2817 Callee,
2818 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002819}
2820
Jim Laskey504e9942007-02-22 15:38:06 +00002821
Chris Lattner6f87d182006-02-22 22:37:12 +00002822SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002823 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002824 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2825 Chain = Val.getValue(1);
2826 Flag = Val.getValue(2);
2827
2828 // If the result was expanded, copy from the top part.
2829 if (Regs.size() > 1) {
2830 assert(Regs.size() == 2 &&
2831 "Cannot expand to more than 2 elts yet!");
2832 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002833 Chain = Hi.getValue(1);
2834 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002835 if (DAG.getTargetLoweringInfo().isLittleEndian())
2836 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2837 else
2838 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002839 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002840
Chris Lattner705948d2006-06-08 18:22:48 +00002841 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002842 // appropriate type.
2843 if (RegVT == ValueVT)
2844 return Val;
2845
Chris Lattner77f04792007-03-25 05:00:54 +00002846 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002847 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
2848 return DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner77f04792007-03-25 05:00:54 +00002849 }
2850
Chris Lattner705948d2006-06-08 18:22:48 +00002851 if (MVT::isInteger(RegVT)) {
2852 if (ValueVT < RegVT)
2853 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2854 else
2855 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002856 }
Chris Lattner77f04792007-03-25 05:00:54 +00002857
2858 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2859 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002860}
2861
Chris Lattner571d9642006-02-23 19:21:04 +00002862/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2863/// specified value into the registers specified by this object. This uses
2864/// Chain/Flag as the input and updates them for the output Chain/Flag.
2865void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002866 SDOperand &Chain, SDOperand &Flag,
2867 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002868 if (Regs.size() == 1) {
2869 // If there is a single register and the types differ, this must be
2870 // a promotion.
2871 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002872 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002873 assert(MVT::isVector(Val.getValueType()) &&
2874 "Not a vector-vector cast?");
2875 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002876 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002877 if (RegVT < ValueVT)
2878 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2879 else
2880 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002881 } else if (MVT::isFloatingPoint(RegVT) &&
2882 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002883 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002884 } else if (MVT::getSizeInBits(RegVT) ==
2885 MVT::getSizeInBits(Val.getValueType())) {
2886 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2887 } else {
2888 assert(0 && "Unknown mismatch!");
2889 }
Chris Lattner571d9642006-02-23 19:21:04 +00002890 }
2891 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2892 Flag = Chain.getValue(1);
2893 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002894 std::vector<unsigned> R(Regs);
2895 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2896 std::reverse(R.begin(), R.end());
2897
2898 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002899 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002900 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002901 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002902 Flag = Chain.getValue(1);
2903 }
2904 }
2905}
Chris Lattner6f87d182006-02-22 22:37:12 +00002906
Chris Lattner571d9642006-02-23 19:21:04 +00002907/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2908/// operand list. This adds the code marker and includes the number of
2909/// values added into it.
2910void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002911 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002912 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2913 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002914 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2915 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2916}
Chris Lattner6f87d182006-02-22 22:37:12 +00002917
2918/// isAllocatableRegister - If the specified register is safe to allocate,
2919/// i.e. it isn't a stack pointer or some other special register, return the
2920/// register class for the register. Otherwise, return null.
2921static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002922isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2923 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002924 MVT::ValueType FoundVT = MVT::Other;
2925 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002926 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2927 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002928 MVT::ValueType ThisVT = MVT::Other;
2929
Chris Lattnerb1124f32006-02-22 23:09:03 +00002930 const TargetRegisterClass *RC = *RCI;
2931 // If none of the the value types for this register class are valid, we
2932 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002933 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2934 I != E; ++I) {
2935 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002936 // If we have already found this register in a different register class,
2937 // choose the one with the largest VT specified. For example, on
2938 // PowerPC, we favor f64 register classes over f32.
2939 if (FoundVT == MVT::Other ||
2940 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2941 ThisVT = *I;
2942 break;
2943 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002944 }
2945 }
2946
Chris Lattnerbec582f2006-04-02 00:24:45 +00002947 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002948
Chris Lattner6f87d182006-02-22 22:37:12 +00002949 // NOTE: This isn't ideal. In particular, this might allocate the
2950 // frame pointer in functions that need it (due to them not being taken
2951 // out of allocation, because a variable sized allocation hasn't been seen
2952 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002953 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2954 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002955 if (*I == Reg) {
2956 // We found a matching register class. Keep looking at others in case
2957 // we find one with larger registers that this physreg is also in.
2958 FoundRC = RC;
2959 FoundVT = ThisVT;
2960 break;
2961 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002962 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002963 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002964}
2965
Chris Lattner1558fc62006-02-01 18:59:47 +00002966
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002967namespace {
2968/// AsmOperandInfo - This contains information for each constraint that we are
2969/// lowering.
2970struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2971 /// ConstraintCode - This contains the actual string for the code, like "m".
2972 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00002973
2974 /// ConstraintType - Information about the constraint code, e.g. Register,
2975 /// RegisterClass, Memory, Other, Unknown.
2976 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002977
2978 /// CallOperand/CallOperandval - If this is the result output operand or a
2979 /// clobber, this is null, otherwise it is the incoming operand to the
2980 /// CallInst. This gets modified as the asm is processed.
2981 SDOperand CallOperand;
2982 Value *CallOperandVal;
2983
2984 /// ConstraintVT - The ValueType for the operand value.
2985 MVT::ValueType ConstraintVT;
2986
Chris Lattner8cfd33b2007-04-30 21:11:17 +00002987 /// AssignedRegs - If this is a register or register class operand, this
2988 /// contains the set of register corresponding to the operand.
2989 RegsForValue AssignedRegs;
2990
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002991 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00002992 : InlineAsm::ConstraintInfo(info),
2993 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002994 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
2995 }
Chris Lattneref073322007-04-30 17:16:27 +00002996
2997 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00002998
2999 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3000 /// busy in OutputRegs/InputRegs.
3001 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3002 std::set<unsigned> &OutputRegs,
3003 std::set<unsigned> &InputRegs) const {
3004 if (isOutReg)
3005 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3006 if (isInReg)
3007 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3008 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003009};
3010} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003011
Chris Lattneref073322007-04-30 17:16:27 +00003012/// getConstraintGenerality - Return an integer indicating how general CT is.
3013static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3014 switch (CT) {
3015 default: assert(0 && "Unknown constraint type!");
3016 case TargetLowering::C_Other:
3017 case TargetLowering::C_Unknown:
3018 return 0;
3019 case TargetLowering::C_Register:
3020 return 1;
3021 case TargetLowering::C_RegisterClass:
3022 return 2;
3023 case TargetLowering::C_Memory:
3024 return 3;
3025 }
3026}
3027
3028void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3029 assert(!Codes.empty() && "Must have at least one constraint");
3030
3031 std::string *Current = &Codes[0];
3032 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3033 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3034 ConstraintCode = *Current;
3035 ConstraintType = CurType;
3036 return;
3037 }
3038
3039 unsigned CurGenerality = getConstraintGenerality(CurType);
3040
3041 // If we have multiple constraints, try to pick the most general one ahead
3042 // of time. This isn't a wonderful solution, but handles common cases.
3043 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3044 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3045 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3046 if (ThisGenerality > CurGenerality) {
3047 // This constraint letter is more general than the previous one,
3048 // use it.
3049 CurType = ThisType;
3050 Current = &Codes[j];
3051 CurGenerality = ThisGenerality;
3052 }
3053 }
3054
3055 ConstraintCode = *Current;
3056 ConstraintType = CurType;
3057}
3058
3059
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003060void SelectionDAGLowering::
3061GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003062 std::set<unsigned> &OutputRegs,
3063 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003064 // Compute whether this value requires an input register, an output register,
3065 // or both.
3066 bool isOutReg = false;
3067 bool isInReg = false;
3068 switch (OpInfo.Type) {
3069 case InlineAsm::isOutput:
3070 isOutReg = true;
3071
3072 // If this is an early-clobber output, or if there is an input
3073 // constraint that matches this, we need to reserve the input register
3074 // so no other inputs allocate to it.
3075 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3076 break;
3077 case InlineAsm::isInput:
3078 isInReg = true;
3079 isOutReg = false;
3080 break;
3081 case InlineAsm::isClobber:
3082 isOutReg = true;
3083 isInReg = true;
3084 break;
3085 }
3086
3087
3088 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003089 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003090
3091 // If this is a constraint for a single physreg, or a constraint for a
3092 // register class, find it.
3093 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3094 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3095 OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003096
3097 unsigned NumRegs = 1;
3098 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohman04deef32007-06-21 14:42:22 +00003099 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003100 MVT::ValueType RegVT;
3101 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3102
Chris Lattner4333f8b2007-04-30 17:29:31 +00003103
3104 // If this is a constraint for a specific physical register, like {r17},
3105 // assign it now.
3106 if (PhysReg.first) {
3107 if (OpInfo.ConstraintVT == MVT::Other)
3108 ValueVT = *PhysReg.second->vt_begin();
3109
3110 // Get the actual register value type. This is important, because the user
3111 // may have asked for (e.g.) the AX register in i32 type. We need to
3112 // remember that AX is actually i16 to get the right extension.
3113 RegVT = *PhysReg.second->vt_begin();
3114
3115 // This is a explicit reference to a physical register.
3116 Regs.push_back(PhysReg.first);
3117
3118 // If this is an expanded reference, add the rest of the regs to Regs.
3119 if (NumRegs != 1) {
3120 TargetRegisterClass::iterator I = PhysReg.second->begin();
3121 TargetRegisterClass::iterator E = PhysReg.second->end();
3122 for (; *I != PhysReg.first; ++I)
3123 assert(I != E && "Didn't find reg!");
3124
3125 // Already added the first reg.
3126 --NumRegs; ++I;
3127 for (; NumRegs; --NumRegs, ++I) {
3128 assert(I != E && "Ran out of registers to allocate!");
3129 Regs.push_back(*I);
3130 }
3131 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003132 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3133 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3134 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003135 }
3136
3137 // Otherwise, if this was a reference to an LLVM register class, create vregs
3138 // for this reference.
3139 std::vector<unsigned> RegClassRegs;
Chris Lattnerf852e332007-06-15 19:11:01 +00003140 const TargetRegisterClass *RC = PhysReg.second;
3141 if (RC) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003142 // If this is an early clobber or tied register, our regalloc doesn't know
3143 // how to maintain the constraint. If it isn't, go ahead and create vreg
3144 // and let the regalloc do the right thing.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003145 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3146 // If there is some other early clobber and this is an input register,
3147 // then we are forced to pre-allocate the input reg so it doesn't
3148 // conflict with the earlyclobber.
3149 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003150 RegVT = *PhysReg.second->vt_begin();
3151
3152 if (OpInfo.ConstraintVT == MVT::Other)
3153 ValueVT = RegVT;
3154
3155 // Create the appropriate number of virtual registers.
3156 SSARegMap *RegMap = MF.getSSARegMap();
3157 for (; NumRegs; --NumRegs)
3158 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3159
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003160 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3161 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3162 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003163 }
3164
3165 // Otherwise, we can't allocate it. Let the code below figure out how to
3166 // maintain these constraints.
3167 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3168
3169 } else {
3170 // This is a reference to a register class that doesn't directly correspond
3171 // to an LLVM register class. Allocate NumRegs consecutive, available,
3172 // registers from the class.
3173 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3174 OpInfo.ConstraintVT);
3175 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003176
Chris Lattner4333f8b2007-04-30 17:29:31 +00003177 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3178 unsigned NumAllocated = 0;
3179 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3180 unsigned Reg = RegClassRegs[i];
3181 // See if this register is available.
3182 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3183 (isInReg && InputRegs.count(Reg))) { // Already used.
3184 // Make sure we find consecutive registers.
3185 NumAllocated = 0;
3186 continue;
3187 }
3188
3189 // Check to see if this register is allocatable (i.e. don't give out the
3190 // stack pointer).
Chris Lattnerf852e332007-06-15 19:11:01 +00003191 if (RC == 0) {
3192 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3193 if (!RC) { // Couldn't allocate this register.
3194 // Reset NumAllocated to make sure we return consecutive registers.
3195 NumAllocated = 0;
3196 continue;
3197 }
Chris Lattner4333f8b2007-04-30 17:29:31 +00003198 }
3199
3200 // Okay, this register is good, we can use it.
3201 ++NumAllocated;
3202
3203 // If we allocated enough consecutive registers, succeed.
3204 if (NumAllocated == NumRegs) {
3205 unsigned RegStart = (i-NumAllocated)+1;
3206 unsigned RegEnd = i+1;
3207 // Mark all of the allocated registers used.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003208 for (unsigned i = RegStart; i != RegEnd; ++i)
3209 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003210
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003211 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3212 OpInfo.ConstraintVT);
3213 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3214 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003215 }
3216 }
3217
3218 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003219 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003220}
3221
3222
Chris Lattner476e67b2006-01-26 22:24:51 +00003223/// visitInlineAsm - Handle a call to an InlineAsm object.
3224///
3225void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3226 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003227
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003228 /// ConstraintOperands - Information about all of the constraints.
3229 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003230
3231 SDOperand Chain = getRoot();
3232 SDOperand Flag;
3233
Chris Lattner1558fc62006-02-01 18:59:47 +00003234 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003235
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003236 // Do a prepass over the constraints, canonicalizing them, and building up the
3237 // ConstraintOperands list.
3238 std::vector<InlineAsm::ConstraintInfo>
3239 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003240
3241 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3242 // constraint. If so, we can't let the register allocator allocate any input
3243 // registers, because it will not know to avoid the earlyclobbered output reg.
3244 bool SawEarlyClobber = false;
3245
3246 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003247 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3248 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3249 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3250
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003251 MVT::ValueType OpVT = MVT::Other;
3252
3253 // Compute the value type for each operand.
3254 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003255 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003256 if (!OpInfo.isIndirect) {
3257 // The return value of the call is this value. As such, there is no
3258 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003259 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3260 OpVT = TLI.getValueType(I.getType());
3261 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003262 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003263 }
3264 break;
3265 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003266 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003267 break;
3268 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003269 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003270 break;
3271 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003272
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003273 // If this is an input or an indirect output, process the call argument.
3274 if (OpInfo.CallOperandVal) {
3275 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3276 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003277 // If this is an indirect operand, the operand is a pointer to the
3278 // accessed type.
3279 if (OpInfo.isIndirect)
3280 OpTy = cast<PointerType>(OpTy)->getElementType();
3281
3282 // If OpTy is not a first-class value, it may be a struct/union that we
3283 // can tile with integers.
3284 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3285 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3286 switch (BitSize) {
3287 default: break;
3288 case 1:
3289 case 8:
3290 case 16:
3291 case 32:
3292 case 64:
3293 OpTy = IntegerType::get(BitSize);
3294 break;
3295 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003296 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003297
3298 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003299 }
3300
3301 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003302
Chris Lattneref073322007-04-30 17:16:27 +00003303 // Compute the constraint code and ConstraintType to use.
3304 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003305
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003306 // Keep track of whether we see an earlyclobber.
3307 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003308
3309 // If this is a memory input, and if the operand is not indirect, do what we
3310 // need to to provide an address for the memory input.
3311 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3312 !OpInfo.isIndirect) {
3313 assert(OpInfo.Type == InlineAsm::isInput &&
3314 "Can only indirectify direct input operands!");
3315
3316 // Memory operands really want the address of the value. If we don't have
3317 // an indirect input, put it in the constpool if we can, otherwise spill
3318 // it to a stack slot.
3319
3320 // If the operand is a float, integer, or vector constant, spill to a
3321 // constant pool entry to get its address.
3322 Value *OpVal = OpInfo.CallOperandVal;
3323 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3324 isa<ConstantVector>(OpVal)) {
3325 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3326 TLI.getPointerTy());
3327 } else {
3328 // Otherwise, create a stack slot and emit a store to it before the
3329 // asm.
3330 const Type *Ty = OpVal->getType();
3331 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3332 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3333 MachineFunction &MF = DAG.getMachineFunction();
3334 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3335 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3336 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3337 OpInfo.CallOperand = StackSlot;
3338 }
3339
3340 // There is no longer a Value* corresponding to this operand.
3341 OpInfo.CallOperandVal = 0;
3342 // It is now an indirect operand.
3343 OpInfo.isIndirect = true;
3344 }
3345
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003346 // If this constraint is for a specific register, allocate it before
3347 // anything else.
3348 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3349 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003350 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003351 ConstraintInfos.clear();
3352
3353
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003354 // Second pass - Loop over all of the operands, assigning virtual or physregs
3355 // to registerclass operands.
3356 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3357 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3358
3359 // C_Register operands have already been allocated, Other/Memory don't need
3360 // to be.
3361 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3362 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3363 }
3364
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003365 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3366 std::vector<SDOperand> AsmNodeOperands;
3367 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3368 AsmNodeOperands.push_back(
3369 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3370
Chris Lattner3a5ed552006-02-01 01:28:23 +00003371
Chris Lattner5c79f982006-02-21 23:12:12 +00003372 // Loop over all of the inputs, copying the operand values into the
3373 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003374 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003375
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003376 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3377 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3378
3379 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3380 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003381
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003382 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003383 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003384 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3385 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003386 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003387 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003388
Chris Lattner9fed5b62006-02-27 23:45:39 +00003389 // Add information to the INLINEASM node to know about this output.
3390 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003391 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3392 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003393 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003394 break;
3395 }
3396
Chris Lattnerb2e55562007-04-28 21:01:43 +00003397 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003398
Chris Lattner6f87d182006-02-22 22:37:12 +00003399 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003400 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003401 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003402 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003403 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003404 exit(1);
3405 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003406
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003407 if (!OpInfo.isIndirect) {
3408 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003409 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003410 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003411 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003412 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003413 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003414 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003415 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003416 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003417
3418 // Add information to the INLINEASM node to know that this register is
3419 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003420 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3421 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003422 break;
3423 }
3424 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003425 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003426
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003427 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003428 // If this is required to match an output register we have already set,
3429 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003430 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003431
Chris Lattner571d9642006-02-23 19:21:04 +00003432 // Scan until we find the definition we already emitted of this operand.
3433 // When we find it, create a RegsForValue operand.
3434 unsigned CurOp = 2; // The first operand.
3435 for (; OperandNo; --OperandNo) {
3436 // Advance to the next operand.
3437 unsigned NumOps =
3438 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003439 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3440 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003441 "Skipped past definitions?");
3442 CurOp += (NumOps>>3)+1;
3443 }
3444
3445 unsigned NumOps =
3446 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003447 if ((NumOps & 7) == 2 /*REGDEF*/) {
3448 // Add NumOps>>3 registers to MatchedRegs.
3449 RegsForValue MatchedRegs;
3450 MatchedRegs.ValueVT = InOperandVal.getValueType();
3451 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3452 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3453 unsigned Reg =
3454 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3455 MatchedRegs.Regs.push_back(Reg);
3456 }
Chris Lattner571d9642006-02-23 19:21:04 +00003457
Chris Lattnere3eeb242007-02-01 01:21:12 +00003458 // Use the produced MatchedRegs object to
3459 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3460 TLI.getPointerTy());
3461 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3462 break;
3463 } else {
3464 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3465 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003466 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003467 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003468
Chris Lattnerb2e55562007-04-28 21:01:43 +00003469 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003470 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003471 "Don't know how to handle indirect other inputs yet!");
3472
Chris Lattner6f043b92006-10-31 19:41:18 +00003473 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003474 OpInfo.ConstraintCode[0],
3475 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003476 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003477 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003478 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003479 exit(1);
3480 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003481
3482 // Add information to the INLINEASM node to know about this input.
3483 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003484 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3485 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003486 AsmNodeOperands.push_back(InOperandVal);
3487 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003488 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003489 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003490 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3491 "Memory operands expect pointer values");
3492
Chris Lattner7ef7a642006-02-24 01:11:24 +00003493 // Add information to the INLINEASM node to know about this input.
3494 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003495 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3496 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003497 AsmNodeOperands.push_back(InOperandVal);
3498 break;
3499 }
3500
Chris Lattnerb2e55562007-04-28 21:01:43 +00003501 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3502 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3503 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003504 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003505 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003506
3507 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003508 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3509 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003510
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003511 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3512 TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003513
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003514 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3515 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003516 break;
3517 }
Chris Lattner571d9642006-02-23 19:21:04 +00003518 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003519 // Add the clobbered value to the operand list, so that the register
3520 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003521 if (!OpInfo.AssignedRegs.Regs.empty())
3522 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3523 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003524 break;
3525 }
Chris Lattner571d9642006-02-23 19:21:04 +00003526 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003527 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003528
3529 // Finish up input operands.
3530 AsmNodeOperands[0] = Chain;
3531 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3532
Chris Lattnerbd887772006-08-14 23:53:35 +00003533 Chain = DAG.getNode(ISD::INLINEASM,
3534 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003535 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003536 Flag = Chain.getValue(1);
3537
Chris Lattner2e56e892006-01-31 02:03:41 +00003538 // If this asm returns a register value, copy the result from that register
3539 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003540 if (!RetValRegs.Regs.empty()) {
3541 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3542
3543 // If the result of the inline asm is a vector, it may have the wrong
3544 // width/num elts. Make sure to convert it to the right type with
Dan Gohmana8665142007-06-25 16:23:39 +00003545 // bit_convert.
3546 if (MVT::isVector(Val.getValueType())) {
Chris Lattner51114992007-04-12 06:00:20 +00003547 const VectorType *VTy = cast<VectorType>(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00003548 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner51114992007-04-12 06:00:20 +00003549
Dan Gohmana8665142007-06-25 16:23:39 +00003550 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner51114992007-04-12 06:00:20 +00003551 }
3552
3553 setValue(&I, Val);
3554 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003555
Chris Lattner2e56e892006-01-31 02:03:41 +00003556 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3557
3558 // Process indirect outputs, first output all of the flagged copies out of
3559 // physregs.
3560 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003561 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003562 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003563 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3564 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003565 }
3566
3567 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003568 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003569 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003570 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003571 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003572 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003573 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003574 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3575 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003576 DAG.setRoot(Chain);
3577}
3578
3579
Chris Lattner7a60d912005-01-07 07:47:53 +00003580void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3581 SDOperand Src = getValue(I.getOperand(0));
3582
3583 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003584
3585 if (IntPtr < Src.getValueType())
3586 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3587 else if (IntPtr > Src.getValueType())
3588 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003589
3590 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003591 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003592 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3593 Src, getIntPtrConstant(ElementSize));
3594
Reid Spencere63b6512006-12-31 05:55:36 +00003595 TargetLowering::ArgListTy Args;
3596 TargetLowering::ArgListEntry Entry;
3597 Entry.Node = Src;
3598 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003599 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003600
3601 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003602 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003603 DAG.getExternalSymbol("malloc", IntPtr),
3604 Args, DAG);
3605 setValue(&I, Result.first); // Pointers always fit in registers
3606 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003607}
3608
3609void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003610 TargetLowering::ArgListTy Args;
3611 TargetLowering::ArgListEntry Entry;
3612 Entry.Node = getValue(I.getOperand(0));
3613 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003614 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003615 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003616 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003617 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003618 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3619 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003620}
3621
Chris Lattner13d7c252005-08-26 20:54:47 +00003622// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3623// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3624// instructions are special in various ways, which require special support to
3625// insert. The specified MachineInstr is created but not inserted into any
3626// basic blocks, and the scheduler passes ownership of it to this method.
3627MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3628 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003629 cerr << "If a target marks an instruction with "
3630 << "'usesCustomDAGSchedInserter', it must implement "
3631 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003632 abort();
3633 return 0;
3634}
3635
Chris Lattner58cfd792005-01-09 00:00:49 +00003636void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003637 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3638 getValue(I.getOperand(1)),
3639 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003640}
3641
3642void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003643 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3644 getValue(I.getOperand(0)),
3645 DAG.getSrcValue(I.getOperand(0)));
3646 setValue(&I, V);
3647 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003648}
3649
3650void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003651 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3652 getValue(I.getOperand(1)),
3653 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003654}
3655
3656void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003657 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3658 getValue(I.getOperand(1)),
3659 getValue(I.getOperand(2)),
3660 DAG.getSrcValue(I.getOperand(1)),
3661 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003662}
3663
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003664/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3665/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3666static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3667 unsigned &i, SelectionDAG &DAG,
3668 TargetLowering &TLI) {
3669 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3670 return SDOperand(Arg, i++);
3671
3672 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3673 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3674 if (NumVals == 1) {
3675 return DAG.getNode(ISD::BIT_CONVERT, VT,
3676 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3677 } else if (NumVals == 2) {
3678 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3679 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3680 if (!TLI.isLittleEndian())
3681 std::swap(Lo, Hi);
3682 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3683 } else {
3684 // Value scalarized into many values. Unimp for now.
3685 assert(0 && "Cannot expand i64 -> i16 yet!");
3686 }
3687 return SDOperand();
3688}
3689
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003690/// TargetLowering::LowerArguments - This is the default LowerArguments
3691/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003692/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3693/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003694std::vector<SDOperand>
3695TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003696 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003697 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003698 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3699 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003700 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003701 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3702 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3703
3704 // Add one result value for each formal argument.
3705 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003706 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003707 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3708 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003709 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003710 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003711 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003712 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003713
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003714 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3715 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003716 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003717 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003718 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003719 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003720 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003721 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003722 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003723 Flags |= ISD::ParamFlags::StructReturn;
3724 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003725
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003726 switch (getTypeAction(VT)) {
3727 default: assert(0 && "Unknown type action!");
3728 case Legal:
3729 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003730 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003731 break;
3732 case Promote:
3733 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003734 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003735 break;
3736 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003737 if (!MVT::isVector(VT)) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003738 // If this is a large integer, it needs to be broken up into small
3739 // integers. Figure out what the destination type is and how many small
3740 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003741 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00003742 unsigned NumVals = getNumRegisters(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003743 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003744 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003745 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003746 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003747 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3748 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003749 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3750 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003751 } else {
3752 // Otherwise, this is a vector type. We only support legal vectors
3753 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003754 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3755 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003756
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003757 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003758 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003759 MVT::ValueType TVT =
3760 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003761 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3762 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003763 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003764 } else {
3765 assert(0 && "Don't support illegal by-val vector arguments yet!");
3766 }
3767 }
3768 break;
3769 }
3770 }
Evan Cheng9618df12006-04-25 23:03:35 +00003771
Chris Lattner3d826992006-05-16 06:45:34 +00003772 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003773
3774 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003775 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3776 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003777 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003778
3779 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003780
3781 // Set up the return result vector.
3782 Ops.clear();
3783 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003784 unsigned Idx = 1;
3785 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3786 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003787 MVT::ValueType VT = getValueType(I->getType());
3788
3789 switch (getTypeAction(VT)) {
3790 default: assert(0 && "Unknown type action!");
3791 case Legal:
3792 Ops.push_back(SDOperand(Result, i++));
3793 break;
3794 case Promote: {
3795 SDOperand Op(Result, i++);
3796 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003797 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003798 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3799 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003800 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003801 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3802 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003803 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3804 } else {
3805 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3806 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3807 }
3808 Ops.push_back(Op);
3809 break;
3810 }
3811 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003812 if (!MVT::isVector(VT)) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003813 // If this is a large integer or a floating point node that needs to be
3814 // expanded, it needs to be reassembled from small integers. Figure out
3815 // what the source elt type is and how many small integers it is.
3816 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003817 } else {
3818 // Otherwise, this is a vector type. We only support legal vectors
3819 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003820 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003821 unsigned NumElems = PTy->getNumElements();
3822 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003823
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003824 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003825 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003826 MVT::ValueType TVT =
3827 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003828 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003829 SDOperand N = SDOperand(Result, i++);
Dan Gohmana8665142007-06-25 16:23:39 +00003830 // Handle copies from vectors to registers.
3831 N = DAG.getNode(ISD::BIT_CONVERT, TVT, N);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003832 Ops.push_back(N);
3833 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003834 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003835 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003836 }
3837 }
3838 break;
3839 }
3840 }
3841 return Ops;
3842}
3843
Chris Lattneraaa23d92006-05-16 22:53:20 +00003844
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003845/// ExpandScalarCallArgs - Recursively expand call argument node by
3846/// bit_converting it or extract a pair of elements from the larger node.
3847static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003848 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003849 SmallVector<SDOperand, 32> &Ops,
3850 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003851 TargetLowering &TLI,
3852 bool isFirst = true) {
3853
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003854 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003855 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003856 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003857 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3858 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003859 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003860 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003861 return;
3862 }
3863
3864 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3865 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3866 if (NumVals == 1) {
3867 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003868 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003869 } else if (NumVals == 2) {
3870 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3871 DAG.getConstant(0, TLI.getPointerTy()));
3872 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3873 DAG.getConstant(1, TLI.getPointerTy()));
3874 if (!TLI.isLittleEndian())
3875 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003876 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3877 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003878 } else {
3879 // Value scalarized into many values. Unimp for now.
3880 assert(0 && "Cannot expand i64 -> i16 yet!");
3881 }
3882}
3883
Chris Lattneraaa23d92006-05-16 22:53:20 +00003884/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3885/// implementation, which just inserts an ISD::CALL node, which is later custom
3886/// lowered by the target to something concrete. FIXME: When all targets are
3887/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3888std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003889TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3890 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003891 unsigned CallingConv, bool isTailCall,
3892 SDOperand Callee,
3893 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003894 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003895 Ops.push_back(Chain); // Op#0 - Chain
3896 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3897 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3898 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3899 Ops.push_back(Callee);
3900
3901 // Handle all of the outgoing arguments.
3902 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003903 MVT::ValueType VT = getValueType(Args[i].Ty);
3904 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003905 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003906 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003907 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003908
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003909 if (Args[i].isSExt)
3910 Flags |= ISD::ParamFlags::SExt;
3911 if (Args[i].isZExt)
3912 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003913 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003914 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003915 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003916 Flags |= ISD::ParamFlags::StructReturn;
3917 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003918
Chris Lattneraaa23d92006-05-16 22:53:20 +00003919 switch (getTypeAction(VT)) {
3920 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003921 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003922 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003923 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003924 break;
3925 case Promote:
3926 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003927 unsigned ExtOp;
3928 if (Args[i].isSExt)
3929 ExtOp = ISD::SIGN_EXTEND;
3930 else if (Args[i].isZExt)
3931 ExtOp = ISD::ZERO_EXTEND;
3932 else
3933 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003934 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3935 } else {
3936 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen9a4d9872007-06-07 21:07:15 +00003937 // A true promotion would change the size of the argument.
3938 // Instead, pretend this is an int. If FP objects are not
3939 // passed the same as ints, the original type should be Legal
3940 // and we should not get here.
3941 Op = DAG.getNode(ISD::BIT_CONVERT,
3942 VT==MVT::f32 ? MVT::i32 :
3943 (VT==MVT::f64 ? MVT::i64 :
3944 MVT::Other),
3945 Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003946 }
3947 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003948 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003949 break;
3950 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003951 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003952 // If this is a large integer, it needs to be broken down into small
3953 // integers. Figure out what the source elt type is and how many small
3954 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003955 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003956 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003957 // Otherwise, this is a vector type. We only support legal vectors
3958 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003959 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003960 unsigned NumElems = PTy->getNumElements();
3961 const Type *EltTy = PTy->getElementType();
3962
3963 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003964 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003965 MVT::ValueType TVT =
3966 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003967 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00003968 // Insert a BIT_CONVERT of the original type to the vector type.
3969 Op = DAG.getNode(ISD::BIT_CONVERT, TVT, Op);
Chris Lattner938155c2006-05-17 20:43:21 +00003970 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003971 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003972 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003973 assert(0 && "Don't support illegal by-val vector call args yet!");
3974 abort();
3975 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003976 }
3977 break;
3978 }
3979 }
3980
3981 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003982 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003983
3984 if (RetTy != Type::VoidTy) {
3985 MVT::ValueType VT = getValueType(RetTy);
3986 switch (getTypeAction(VT)) {
3987 default: assert(0 && "Unknown type action!");
3988 case Legal:
3989 RetTys.push_back(VT);
3990 break;
3991 case Promote:
3992 RetTys.push_back(getTypeToTransformTo(VT));
3993 break;
3994 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003995 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003996 // If this is a large integer, it needs to be reassembled from small
3997 // integers. Figure out what the source elt type is and how many small
3998 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003999 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004000 unsigned NumVals = getNumRegisters(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004001 for (unsigned i = 0; i != NumVals; ++i)
4002 RetTys.push_back(NVT);
4003 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004004 // Otherwise, this is a vector type. We only support legal vectors
4005 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004006 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004007 unsigned NumElems = PTy->getNumElements();
4008 const Type *EltTy = PTy->getElementType();
4009
4010 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004011 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00004012 MVT::ValueType TVT =
4013 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004014 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4015 RetTys.push_back(TVT);
4016 } else {
4017 assert(0 && "Don't support illegal by-val vector call results yet!");
4018 abort();
4019 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004020 }
4021 }
4022 }
4023
4024 RetTys.push_back(MVT::Other); // Always has a chain.
4025
4026 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004027 SDOperand Res = DAG.getNode(ISD::CALL,
4028 DAG.getVTList(&RetTys[0], RetTys.size()),
4029 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004030
4031 // This returns a pair of operands. The first element is the
4032 // return value for the function (if RetTy is not VoidTy). The second
4033 // element is the outgoing token chain.
4034 SDOperand ResVal;
4035 if (RetTys.size() != 1) {
4036 MVT::ValueType VT = getValueType(RetTy);
4037 if (RetTys.size() == 2) {
4038 ResVal = Res;
4039
4040 // If this value was promoted, truncate it down.
4041 if (ResVal.getValueType() != VT) {
Dan Gohmana8665142007-06-25 16:23:39 +00004042 if (MVT::isVector(VT)) {
4043 // Insert a BIT_CONVERT to convert from the packed result type to the
4044 // new vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004045 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4046 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004047
4048 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004049 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00004050 MVT::ValueType TVT =
4051 MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004052 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00004053 // Insert a BIT_CONVERT of the FORMAL_ARGUMENTS to a
4054 // "N x PTyElementVT" vector type.
4055 ResVal = DAG.getNode(ISD::BIT_CONVERT, TVT, ResVal);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004056 } else {
4057 abort();
4058 }
4059 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004060 unsigned AssertOp = ISD::AssertSext;
4061 if (!RetTyIsSigned)
4062 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004063 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4064 DAG.getValueType(VT));
4065 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4066 } else {
4067 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004068 if (getTypeAction(VT) == Expand)
4069 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4070 else
4071 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004072 }
4073 }
4074 } else if (RetTys.size() == 3) {
4075 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4076 Res.getValue(0), Res.getValue(1));
4077
4078 } else {
4079 assert(0 && "Case not handled yet!");
4080 }
4081 }
4082
4083 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4084}
4085
Chris Lattner29dcc712005-05-14 05:50:48 +00004086SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004087 assert(0 && "LowerOperation not implemented for this target!");
4088 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004089 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004090}
4091
Nate Begeman595ec732006-01-28 03:14:31 +00004092SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4093 SelectionDAG &DAG) {
4094 assert(0 && "CustomPromoteOperation not implemented for this target!");
4095 abort();
4096 return SDOperand();
4097}
4098
Evan Cheng6781b6e2006-02-15 21:59:04 +00004099/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004100/// operand.
4101static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004102 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004103 MVT::ValueType CurVT = VT;
4104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4105 uint64_t Val = C->getValue() & 255;
4106 unsigned Shift = 8;
4107 while (CurVT != MVT::i8) {
4108 Val = (Val << Shift) | Val;
4109 Shift <<= 1;
4110 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004111 }
4112 return DAG.getConstant(Val, VT);
4113 } else {
4114 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4115 unsigned Shift = 8;
4116 while (CurVT != MVT::i8) {
4117 Value =
4118 DAG.getNode(ISD::OR, VT,
4119 DAG.getNode(ISD::SHL, VT, Value,
4120 DAG.getConstant(Shift, MVT::i8)), Value);
4121 Shift <<= 1;
4122 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004123 }
4124
4125 return Value;
4126 }
4127}
4128
Evan Cheng6781b6e2006-02-15 21:59:04 +00004129/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4130/// used when a memcpy is turned into a memset when the source is a constant
4131/// string ptr.
4132static SDOperand getMemsetStringVal(MVT::ValueType VT,
4133 SelectionDAG &DAG, TargetLowering &TLI,
4134 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004135 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004136 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004137 if (TLI.isLittleEndian())
4138 Offset = Offset + MSB - 1;
4139 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004140 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004141 Offset += TLI.isLittleEndian() ? -1 : 1;
4142 }
4143 return DAG.getConstant(Val, VT);
4144}
4145
Evan Cheng81fcea82006-02-14 08:22:34 +00004146/// getMemBasePlusOffset - Returns base and offset node for the
4147static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4148 SelectionDAG &DAG, TargetLowering &TLI) {
4149 MVT::ValueType VT = Base.getValueType();
4150 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4151}
4152
Evan Chengdb2a7a72006-02-14 20:12:38 +00004153/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004154/// to replace the memset / memcpy is below the threshold. It also returns the
4155/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004156static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4157 unsigned Limit, uint64_t Size,
4158 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004159 MVT::ValueType VT;
4160
4161 if (TLI.allowsUnalignedMemoryAccesses()) {
4162 VT = MVT::i64;
4163 } else {
4164 switch (Align & 7) {
4165 case 0:
4166 VT = MVT::i64;
4167 break;
4168 case 4:
4169 VT = MVT::i32;
4170 break;
4171 case 2:
4172 VT = MVT::i16;
4173 break;
4174 default:
4175 VT = MVT::i8;
4176 break;
4177 }
4178 }
4179
Evan Chengd5026102006-02-14 09:11:59 +00004180 MVT::ValueType LVT = MVT::i64;
4181 while (!TLI.isTypeLegal(LVT))
4182 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4183 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004184
Evan Chengd5026102006-02-14 09:11:59 +00004185 if (VT > LVT)
4186 VT = LVT;
4187
Evan Cheng04514992006-02-14 23:05:54 +00004188 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004189 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004190 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004191 while (VTSize > Size) {
4192 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004193 VTSize >>= 1;
4194 }
Evan Chengd5026102006-02-14 09:11:59 +00004195 assert(MVT::isInteger(VT));
4196
4197 if (++NumMemOps > Limit)
4198 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004199 MemOps.push_back(VT);
4200 Size -= VTSize;
4201 }
Evan Chengd5026102006-02-14 09:11:59 +00004202
4203 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004204}
4205
Chris Lattner875def92005-01-11 05:56:49 +00004206void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004207 SDOperand Op1 = getValue(I.getOperand(1));
4208 SDOperand Op2 = getValue(I.getOperand(2));
4209 SDOperand Op3 = getValue(I.getOperand(3));
4210 SDOperand Op4 = getValue(I.getOperand(4));
4211 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4212 if (Align == 0) Align = 1;
4213
4214 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4215 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004216
4217 // Expand memset / memcpy to a series of load / store ops
4218 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004219 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004220 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004221 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004222 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004223 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4224 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004225 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004226 unsigned Offset = 0;
4227 for (unsigned i = 0; i < NumMemOps; i++) {
4228 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004229 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004230 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004231 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004232 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004233 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004234 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004235 Offset += VTSize;
4236 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004237 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004238 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004239 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004240 case ISD::MEMCPY: {
4241 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4242 Size->getValue(), Align, TLI)) {
4243 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004244 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004245 GlobalAddressSDNode *G = NULL;
4246 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004247 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004248
4249 if (Op2.getOpcode() == ISD::GlobalAddress)
4250 G = cast<GlobalAddressSDNode>(Op2);
4251 else if (Op2.getOpcode() == ISD::ADD &&
4252 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4253 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4254 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004255 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004256 }
4257 if (G) {
4258 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004259 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004260 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004261 if (!Str.empty()) {
4262 CopyFromStr = true;
4263 SrcOff += SrcDelta;
4264 }
4265 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004266 }
4267
Evan Chenge2038bd2006-02-15 01:54:51 +00004268 for (unsigned i = 0; i < NumMemOps; i++) {
4269 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004270 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004271 SDOperand Value, Chain, Store;
4272
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004273 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004274 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4275 Chain = getRoot();
4276 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004277 DAG.getStore(Chain, Value,
4278 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004279 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004280 } else {
4281 Value = DAG.getLoad(VT, getRoot(),
4282 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004283 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004284 Chain = Value.getValue(1);
4285 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004286 DAG.getStore(Chain, Value,
4287 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004288 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004289 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004290 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004291 SrcOff += VTSize;
4292 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004293 }
4294 }
4295 break;
4296 }
4297 }
4298
4299 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004300 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4301 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004302 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004303 }
4304 }
4305
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004306 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004307}
4308
Chris Lattner875def92005-01-11 05:56:49 +00004309//===----------------------------------------------------------------------===//
4310// SelectionDAGISel code
4311//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004312
4313unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4314 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4315}
4316
Chris Lattnerc9950c12005-08-17 06:37:43 +00004317void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004318 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004319 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004320}
Chris Lattner7a60d912005-01-07 07:47:53 +00004321
Chris Lattner35397782005-12-05 07:10:48 +00004322
Chris Lattnerbba52192006-10-28 19:22:10 +00004323
Chris Lattner7a60d912005-01-07 07:47:53 +00004324bool SelectionDAGISel::runOnFunction(Function &Fn) {
4325 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4326 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004327 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004328
4329 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4330
Duncan Sands74137362007-06-13 16:53:21 +00004331 if (ExceptionHandling)
4332 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4333 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4334 // Mark landing pad.
4335 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands61166502007-06-06 10:05:18 +00004336
4337 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004338 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004339
Evan Cheng276b44b2007-02-10 02:43:39 +00004340 // Add function live-ins to entry block live-in set.
4341 BasicBlock *EntryBB = &Fn.getEntryBlock();
4342 BB = FuncInfo.MBBMap[EntryBB];
4343 if (!MF.livein_empty())
4344 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4345 E = MF.livein_end(); I != E; ++I)
4346 BB->addLiveIn(I->first);
4347
Duncan Sands92bf2c62007-06-15 19:04:19 +00004348#ifndef NDEBUG
4349 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4350 "Not all catch info was assigned to a landing pad!");
4351#endif
4352
Chris Lattner7a60d912005-01-07 07:47:53 +00004353 return true;
4354}
4355
Chris Lattnered0110b2006-10-27 21:36:01 +00004356SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4357 unsigned Reg) {
4358 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004359 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004360 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004361 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004362
4363 // If this type is not legal, we must make sure to not create an invalid
4364 // register use.
4365 MVT::ValueType SrcVT = Op.getValueType();
4366 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004367 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004368 return DAG.getCopyToReg(getRoot(), Reg, Op);
Dan Gohmana8665142007-06-25 16:23:39 +00004369 } else if (MVT::isVector(SrcVT)) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004370 // Handle copies from generic vectors to registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004371 MVT::ValueType ElementVT, LegalElementVT;
4372 unsigned NE = TLI.getVectorTypeBreakdown(SrcVT,
4373 ElementVT, LegalElementVT);
4374 uint64_t SrcVL = MVT::getVectorNumElements(SrcVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004375
Chris Lattner5fe1f542006-03-31 02:06:56 +00004376 // Loop over all of the elements of the resultant vector,
Dan Gohmana8665142007-06-25 16:23:39 +00004377 // EXTRACT_VECTOR_ELT'ing or EXTRACT_SUBVECTOR'ing them, converting them
4378 // to LegalElementVT, then copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004379 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004380 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004381 for (unsigned i = 0; i != NE; ++i) {
Dan Gohmana8665142007-06-25 16:23:39 +00004382 SDOperand Elt = MVT::isVector(ElementVT) ?
4383 DAG.getNode(ISD::EXTRACT_SUBVECTOR, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004384 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) :
Dan Gohmana8665142007-06-25 16:23:39 +00004385 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004386 Op, DAG.getConstant(i, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004387 if (ElementVT == LegalElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004388 // Elements are legal.
4389 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
Dan Gohmana8665142007-06-25 16:23:39 +00004390 } else if (LegalElementVT > ElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004391 // Elements are promoted.
Dan Gohmana8665142007-06-25 16:23:39 +00004392 if (MVT::isFloatingPoint(LegalElementVT))
4393 Elt = DAG.getNode(ISD::FP_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004394 else
Dan Gohmana8665142007-06-25 16:23:39 +00004395 Elt = DAG.getNode(ISD::ANY_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004396 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4397 } else {
4398 // Elements are expanded.
4399 // The src value is expanded into multiple registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004400 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004401 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004402 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004403 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004404 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4405 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4406 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004407 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004408 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4409 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004410 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004411 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004412 if (MVT::isFloatingPoint(SrcVT))
4413 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4414 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004415 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004416 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004417 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004418 DestVT = TLI.getTypeToExpandTo(SrcVT);
Dan Gohman04deef32007-06-21 14:42:22 +00004419 unsigned NumVals = TLI.getNumRegisters(SrcVT);
Evan Cheng22cf8992006-12-13 20:57:08 +00004420 if (NumVals == 1)
4421 return DAG.getCopyToReg(getRoot(), Reg,
4422 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4423 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004424 // The src value is expanded into multiple registers.
4425 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004426 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004427 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004428 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004429 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004430 return DAG.getCopyToReg(Op, Reg+1, Hi);
4431 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004432}
4433
Chris Lattner16f64df2005-01-17 17:15:02 +00004434void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004435LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004436 std::vector<SDOperand> &UnorderedChains) {
4437 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004438 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004439 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004440 SDOperand OldRoot = SDL.DAG.getRoot();
4441 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004442
Chris Lattner6871b232005-10-30 19:42:35 +00004443 unsigned a = 0;
4444 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4445 AI != E; ++AI, ++a)
4446 if (!AI->use_empty()) {
4447 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004448
Chris Lattner6871b232005-10-30 19:42:35 +00004449 // If this argument is live outside of the entry block, insert a copy from
4450 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004451 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4452 if (VMI != FuncInfo.ValueMap.end()) {
4453 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004454 UnorderedChains.push_back(Copy);
4455 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004456 }
Chris Lattner6871b232005-10-30 19:42:35 +00004457
Chris Lattner6871b232005-10-30 19:42:35 +00004458 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004459 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004460 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004461}
4462
Duncan Sands92bf2c62007-06-15 19:04:19 +00004463static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4464 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4465 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4466 "Copying catch info out of a landing pad!");
4467 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4468 if (isFilterOrSelector(I)) {
4469 // Apply the catch info to DestBB.
4470 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4471#ifndef NDEBUG
4472 FLI.CatchInfoFound.insert(I);
4473#endif
4474 }
4475}
4476
Chris Lattner7a60d912005-01-07 07:47:53 +00004477void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4478 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004479 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004480 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004481
4482 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004483
Chris Lattner6871b232005-10-30 19:42:35 +00004484 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004485 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004486 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004487
4488 BB = FuncInfo.MBBMap[LLVMBB];
4489 SDL.setCurrentBasicBlock(BB);
4490
Duncan Sands92bf2c62007-06-15 19:04:19 +00004491 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands61166502007-06-06 10:05:18 +00004492
Duncan Sands92bf2c62007-06-15 19:04:19 +00004493 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4494 // Add a label to mark the beginning of the landing pad. Deletion of the
4495 // landing pad can thus be detected via the MachineModuleInfo.
4496 unsigned LabelID = MMI->addLandingPad(BB);
4497 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4498 DAG.getConstant(LabelID, MVT::i32)));
4499
Evan Cheng77f541d2007-06-27 18:45:32 +00004500 // Mark exception register as live in.
4501 unsigned Reg = TLI.getExceptionAddressRegister();
4502 if (Reg) BB->addLiveIn(Reg);
4503
4504 // Mark exception selector register as live in.
4505 Reg = TLI.getExceptionSelectorRegister();
4506 if (Reg) BB->addLiveIn(Reg);
4507
Duncan Sands92bf2c62007-06-15 19:04:19 +00004508 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4509 // function and list of typeids logically belong to the invoke (or, if you
4510 // like, the basic block containing the invoke), and need to be associated
4511 // with it in the dwarf exception handling tables. Currently however the
4512 // information is provided by intrinsics (eh.filter and eh.selector) that
4513 // can be moved to unexpected places by the optimizers: if the unwind edge
4514 // is critical, then breaking it can result in the intrinsics being in the
4515 // successor of the landing pad, not the landing pad itself. This results
4516 // in exceptions not being caught because no typeids are associated with
4517 // the invoke. This may not be the only way things can go wrong, but it
4518 // is the only way we try to work around for the moment.
4519 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4520
4521 if (Br && Br->isUnconditional()) { // Critical edge?
4522 BasicBlock::iterator I, E;
4523 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4524 if (isFilterOrSelector(I))
4525 break;
4526
4527 if (I == E)
4528 // No catch info found - try to extract some from the successor.
4529 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands61166502007-06-06 10:05:18 +00004530 }
4531 }
4532
Chris Lattner7a60d912005-01-07 07:47:53 +00004533 // Lower all of the non-terminator instructions.
4534 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4535 I != E; ++I)
4536 SDL.visit(*I);
Duncan Sands97f72362007-06-13 05:51:31 +00004537
Chris Lattner7a60d912005-01-07 07:47:53 +00004538 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004539 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004540 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004541 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004542 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004543 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004544 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004545 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004546 }
4547
4548 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4549 // ensure constants are generated when needed. Remember the virtual registers
4550 // that need to be added to the Machine PHI nodes as input. We cannot just
4551 // directly add them, because expansion might result in multiple MBB's for one
4552 // BB. As such, the start of the BB might correspond to a different MBB than
4553 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004554 //
Chris Lattner84a03502006-10-27 23:50:33 +00004555 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004556
4557 // Emit constants only once even if used by multiple PHI nodes.
4558 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004559
Chris Lattner84a03502006-10-27 23:50:33 +00004560 // Vector bool would be better, but vector<bool> is really slow.
4561 std::vector<unsigned char> SuccsHandled;
4562 if (TI->getNumSuccessors())
4563 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4564
Chris Lattner7a60d912005-01-07 07:47:53 +00004565 // Check successor nodes PHI nodes that expect a constant to be available from
4566 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004567 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4568 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004569 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004570 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004571
Chris Lattner84a03502006-10-27 23:50:33 +00004572 // If this terminator has multiple identical successors (common for
4573 // switches), only handle each succ once.
4574 unsigned SuccMBBNo = SuccMBB->getNumber();
4575 if (SuccsHandled[SuccMBBNo]) continue;
4576 SuccsHandled[SuccMBBNo] = true;
4577
4578 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004579 PHINode *PN;
4580
4581 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4582 // nodes and Machine PHI nodes, but the incoming operands have not been
4583 // emitted yet.
4584 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004585 (PN = dyn_cast<PHINode>(I)); ++I) {
4586 // Ignore dead phi's.
4587 if (PN->use_empty()) continue;
4588
4589 unsigned Reg;
4590 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004591
Chris Lattner84a03502006-10-27 23:50:33 +00004592 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4593 unsigned &RegOut = ConstantsOut[C];
4594 if (RegOut == 0) {
4595 RegOut = FuncInfo.CreateRegForValue(C);
4596 UnorderedChains.push_back(
4597 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004598 }
Chris Lattner84a03502006-10-27 23:50:33 +00004599 Reg = RegOut;
4600 } else {
4601 Reg = FuncInfo.ValueMap[PHIOp];
4602 if (Reg == 0) {
4603 assert(isa<AllocaInst>(PHIOp) &&
4604 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4605 "Didn't codegen value into a register!??");
4606 Reg = FuncInfo.CreateRegForValue(PHIOp);
4607 UnorderedChains.push_back(
4608 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004609 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004610 }
Chris Lattner84a03502006-10-27 23:50:33 +00004611
4612 // Remember that this register needs to added to the machine PHI node as
4613 // the input for this MBB.
4614 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohmana8665142007-06-25 16:23:39 +00004615 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004616 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner84a03502006-10-27 23:50:33 +00004617 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4618 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004619 }
4620 ConstantsOut.clear();
4621
Chris Lattner718b5c22005-01-13 17:59:43 +00004622 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004623 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004624 SDOperand Root = SDL.getRoot();
4625 if (Root.getOpcode() != ISD::EntryToken) {
4626 unsigned i = 0, e = UnorderedChains.size();
4627 for (; i != e; ++i) {
4628 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4629 if (UnorderedChains[i].Val->getOperand(0) == Root)
4630 break; // Don't add the root if we already indirectly depend on it.
4631 }
4632
4633 if (i == e)
4634 UnorderedChains.push_back(Root);
4635 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004636 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4637 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004638 }
4639
Chris Lattner7a60d912005-01-07 07:47:53 +00004640 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004641 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004642
Nate Begemaned728c12006-03-27 01:32:24 +00004643 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004644 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004645 SwitchCases.clear();
4646 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004647 JTCases.clear();
4648 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004649 BitTestCases.clear();
4650 BitTestCases = SDL.BitTestCases;
4651
Chris Lattner4108bb02005-01-17 19:43:36 +00004652 // Make sure the root of the DAG is up-to-date.
4653 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004654}
4655
Nate Begemaned728c12006-03-27 01:32:24 +00004656void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004657 // Get alias analysis for load/store combining.
4658 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4659
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004660 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004661 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004662
Bill Wendling22e978a2006-12-07 20:04:42 +00004663 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004664 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004665
Chris Lattner7a60d912005-01-07 07:47:53 +00004666 // Second step, hack on the DAG until it only uses operations and types that
4667 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004668 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004669
Bill Wendling22e978a2006-12-07 20:04:42 +00004670 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004671 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004672
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004673 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004674 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004675
Evan Cheng739a6a42006-01-21 02:32:06 +00004676 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004677
Chris Lattner5ca31d92005-03-30 01:10:47 +00004678 // Third, instruction select all of the operations to machine code, adding the
4679 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004680 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004681
Bill Wendling22e978a2006-12-07 20:04:42 +00004682 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004683 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004684}
Chris Lattner7a60d912005-01-07 07:47:53 +00004685
Nate Begemaned728c12006-03-27 01:32:24 +00004686void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4687 FunctionLoweringInfo &FuncInfo) {
4688 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4689 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004690 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004691 CurDAG = &DAG;
4692
4693 // First step, lower LLVM code to some DAG. This DAG may use operations and
4694 // types that are not supported by the target.
4695 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4696
4697 // Second step, emit the lowered DAG as machine code.
4698 CodeGenAndEmitDAG(DAG);
4699 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004700
4701 DOUT << "Total amount of phi nodes to update: "
4702 << PHINodesToUpdate.size() << "\n";
4703 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4704 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4705 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004706
Chris Lattner5ca31d92005-03-30 01:10:47 +00004707 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004708 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004709 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004710 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4711 MachineInstr *PHI = PHINodesToUpdate[i].first;
4712 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4713 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004714 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004715 PHI->addMachineBasicBlockOperand(BB);
4716 }
4717 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004718 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004719
4720 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4721 // Lower header first, if it wasn't already lowered
4722 if (!BitTestCases[i].Emitted) {
4723 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4724 CurDAG = &HSDAG;
4725 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4726 // Set the current basic block to the mbb we wish to insert the code into
4727 BB = BitTestCases[i].Parent;
4728 HSDL.setCurrentBasicBlock(BB);
4729 // Emit the code
4730 HSDL.visitBitTestHeader(BitTestCases[i]);
4731 HSDAG.setRoot(HSDL.getRoot());
4732 CodeGenAndEmitDAG(HSDAG);
4733 }
4734
4735 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4736 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4737 CurDAG = &BSDAG;
4738 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4739 // Set the current basic block to the mbb we wish to insert the code into
4740 BB = BitTestCases[i].Cases[j].ThisBB;
4741 BSDL.setCurrentBasicBlock(BB);
4742 // Emit the code
4743 if (j+1 != ej)
4744 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4745 BitTestCases[i].Reg,
4746 BitTestCases[i].Cases[j]);
4747 else
4748 BSDL.visitBitTestCase(BitTestCases[i].Default,
4749 BitTestCases[i].Reg,
4750 BitTestCases[i].Cases[j]);
4751
4752
4753 BSDAG.setRoot(BSDL.getRoot());
4754 CodeGenAndEmitDAG(BSDAG);
4755 }
4756
4757 // Update PHI Nodes
4758 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4759 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4760 MachineBasicBlock *PHIBB = PHI->getParent();
4761 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4762 "This is not a machine PHI node that we are updating!");
4763 // This is "default" BB. We have two jumps to it. From "header" BB and
4764 // from last "case" BB.
4765 if (PHIBB == BitTestCases[i].Default) {
4766 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4767 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004768 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004769 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4770 }
4771 // One of "cases" BB.
4772 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4773 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4774 if (cBB->succ_end() !=
4775 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4776 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4777 PHI->addMachineBasicBlockOperand(cBB);
4778 }
4779 }
4780 }
4781 }
4782
Nate Begeman866b4b42006-04-23 06:26:20 +00004783 // If the JumpTable record is filled in, then we need to emit a jump table.
4784 // Updating the PHI nodes is tricky in this case, since we need to determine
4785 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004786 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4787 // Lower header first, if it wasn't already lowered
4788 if (!JTCases[i].first.Emitted) {
4789 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4790 CurDAG = &HSDAG;
4791 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4792 // Set the current basic block to the mbb we wish to insert the code into
4793 BB = JTCases[i].first.HeaderBB;
4794 HSDL.setCurrentBasicBlock(BB);
4795 // Emit the code
4796 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4797 HSDAG.setRoot(HSDL.getRoot());
4798 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004799 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004800
4801 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4802 CurDAG = &JSDAG;
4803 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004804 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004805 BB = JTCases[i].second.MBB;
4806 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004807 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004808 JSDL.visitJumpTable(JTCases[i].second);
4809 JSDAG.setRoot(JSDL.getRoot());
4810 CodeGenAndEmitDAG(JSDAG);
4811
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004812 // Update PHI Nodes
4813 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4814 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4815 MachineBasicBlock *PHIBB = PHI->getParent();
4816 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4817 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004818 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004819 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004820 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004821 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004822 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004823 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004824 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004825 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004826 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004827 }
4828 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004829 }
4830
Chris Lattner76a7bc82006-10-22 23:00:53 +00004831 // If the switch block involved a branch to one of the actual successors, we
4832 // need to update PHI nodes in that block.
4833 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4834 MachineInstr *PHI = PHINodesToUpdate[i].first;
4835 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4836 "This is not a machine PHI node that we are updating!");
4837 if (BB->isSuccessor(PHI->getParent())) {
4838 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4839 PHI->addMachineBasicBlockOperand(BB);
4840 }
4841 }
4842
Nate Begemaned728c12006-03-27 01:32:24 +00004843 // If we generated any switch lowering information, build and codegen any
4844 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004845 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004846 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004847 CurDAG = &SDAG;
4848 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004849
Nate Begemaned728c12006-03-27 01:32:24 +00004850 // Set the current basic block to the mbb we wish to insert the code into
4851 BB = SwitchCases[i].ThisBB;
4852 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004853
Nate Begemaned728c12006-03-27 01:32:24 +00004854 // Emit the code
4855 SDL.visitSwitchCase(SwitchCases[i]);
4856 SDAG.setRoot(SDL.getRoot());
4857 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004858
4859 // Handle any PHI nodes in successors of this chunk, as if we were coming
4860 // from the original BB before switch expansion. Note that PHI nodes can
4861 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4862 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004863 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004864 for (MachineBasicBlock::iterator Phi = BB->begin();
4865 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4866 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4867 for (unsigned pn = 0; ; ++pn) {
4868 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4869 if (PHINodesToUpdate[pn].first == Phi) {
4870 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4871 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4872 break;
4873 }
4874 }
Nate Begemaned728c12006-03-27 01:32:24 +00004875 }
Chris Lattner707339a52006-09-07 01:59:34 +00004876
4877 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004878 if (BB == SwitchCases[i].FalseBB)
4879 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004880
4881 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004882 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004883 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004884 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004885 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004886 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004887}
Evan Cheng739a6a42006-01-21 02:32:06 +00004888
Jim Laskey95eda5b2006-08-01 14:21:23 +00004889
Evan Cheng739a6a42006-01-21 02:32:06 +00004890//===----------------------------------------------------------------------===//
4891/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4892/// target node in the graph.
4893void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4894 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004895
Jim Laskey29e635d2006-08-02 12:30:23 +00004896 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004897
4898 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004899 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004900 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004901 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004902
Jim Laskey03593f72006-08-01 18:29:48 +00004903 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004904 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004905 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004906}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004907
Chris Lattner47639db2006-03-06 00:22:00 +00004908
Jim Laskey03593f72006-08-01 18:29:48 +00004909HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4910 return new HazardRecognizer();
4911}
4912
Chris Lattner6df34962006-10-11 03:58:02 +00004913//===----------------------------------------------------------------------===//
4914// Helper functions used by the generated instruction selector.
4915//===----------------------------------------------------------------------===//
4916// Calls to these methods are generated by tblgen.
4917
4918/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4919/// the dag combiner simplified the 255, we still want to match. RHS is the
4920/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4921/// specified in the .td file (e.g. 255).
4922bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4923 int64_t DesiredMaskS) {
4924 uint64_t ActualMask = RHS->getValue();
4925 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4926
4927 // If the actual mask exactly matches, success!
4928 if (ActualMask == DesiredMask)
4929 return true;
4930
4931 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4932 if (ActualMask & ~DesiredMask)
4933 return false;
4934
4935 // Otherwise, the DAG Combiner may have proven that the value coming in is
4936 // either already zero or is not demanded. Check for known zero input bits.
4937 uint64_t NeededMask = DesiredMask & ~ActualMask;
Dan Gohman309d3d52007-06-22 14:59:07 +00004938 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner6df34962006-10-11 03:58:02 +00004939 return true;
4940
4941 // TODO: check to see if missing bits are just not demanded.
4942
4943 // Otherwise, this pattern doesn't match.
4944 return false;
4945}
4946
4947/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4948/// the dag combiner simplified the 255, we still want to match. RHS is the
4949/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4950/// specified in the .td file (e.g. 255).
4951bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4952 int64_t DesiredMaskS) {
4953 uint64_t ActualMask = RHS->getValue();
4954 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4955
4956 // If the actual mask exactly matches, success!
4957 if (ActualMask == DesiredMask)
4958 return true;
4959
4960 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4961 if (ActualMask & ~DesiredMask)
4962 return false;
4963
4964 // Otherwise, the DAG Combiner may have proven that the value coming in is
4965 // either already zero or is not demanded. Check for known zero input bits.
4966 uint64_t NeededMask = DesiredMask & ~ActualMask;
4967
4968 uint64_t KnownZero, KnownOne;
Dan Gohman309d3d52007-06-22 14:59:07 +00004969 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner6df34962006-10-11 03:58:02 +00004970
4971 // If all the missing bits in the or are already known to be set, match!
4972 if ((NeededMask & KnownOne) == NeededMask)
4973 return true;
4974
4975 // TODO: check to see if missing bits are just not demanded.
4976
4977 // Otherwise, this pattern doesn't match.
4978 return false;
4979}
4980
Jim Laskey03593f72006-08-01 18:29:48 +00004981
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004982/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4983/// by tblgen. Others should not call it.
4984void SelectionDAGISel::
4985SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4986 std::vector<SDOperand> InOps;
4987 std::swap(InOps, Ops);
4988
4989 Ops.push_back(InOps[0]); // input chain.
4990 Ops.push_back(InOps[1]); // input asm string.
4991
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004992 unsigned i = 2, e = InOps.size();
4993 if (InOps[e-1].getValueType() == MVT::Flag)
4994 --e; // Don't process a flag operand if it is here.
4995
4996 while (i != e) {
4997 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4998 if ((Flags & 7) != 4 /*MEM*/) {
4999 // Just skip over this operand, copying the operands verbatim.
5000 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5001 i += (Flags >> 3) + 1;
5002 } else {
5003 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5004 // Otherwise, this is a memory operand. Ask the target to select it.
5005 std::vector<SDOperand> SelOps;
5006 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00005007 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005008 exit(1);
5009 }
5010
5011 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00005012 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00005013 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00005014 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005015 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5016 i += 2;
5017 }
5018 }
5019
5020 // Add the flag input back if present.
5021 if (e != InOps.size())
5022 Ops.push_back(InOps.back());
5023}
Devang Patel09f162c2007-05-01 21:15:47 +00005024
Devang Patel8c78a0b2007-05-03 01:11:54 +00005025char SelectionDAGISel::ID = 0;